【问题标题】:Convert string with accent into numbers (RSA encryption)将带重音的字符串转换为数字(RSA 加密)
【发布时间】:2019-05-25 16:50:39
【问题描述】:

我的数学老师要求我们用 Python 编写 RSA 加密/解密过程。所以我创建了以下函数: lettre_chiffre(T) 使用 ord() 函数将字符串中的每个字符转换为数字 chiffre_lettre(T) 与 chr() 相反 由于这些函数创建了 4 个数字块,我需要在 RSA 中使用 5 个数字块进行加密,以防止频率分析。 问题是 ord 函数不适用于法语口音“锓à”...... 因此,我对使用 bytearray 方法很感兴趣,但我不知道如何使用它。

我怎样才能使这个程序与重音一起工作。用 bytearray 加密和解密的 byte 不适用于 "é" 和 "à" 例如。

python 

def lettre_chiffre(T):
    Message_chiffre = str('')
    for lettre in T:
        if ord(lettre) < 10000:
            nombre = str(ord(lettre))
            while len(nombre) != 4:
                nombre = str('0') + nombre
            Message_chiffre += nombre
        else:
            print("erreur lettre : ",lettre)
    while len(Message_chiffre)%4 != 0:
        Message_chiffre = str('0') + Message_chiffre
    return str(Message_chiffre)

def chiffre_lettre(T):
    Message_lettre = str('')
    A =T
    for i in range(int(len(str(A))/4)):
        nombre = str(A)[4*i:4*i+4]
        if int(nombre) < 10000:
            Message_lettre += str(chr(int(nombre)))
    return Message_lettre

【问题讨论】:

  • 这不是因为这个解决方案总是存在问题:有重音“é”,“à”......
  • 所以我不能将字符串“é”编码成字节然后解码。它不会给我“é”?
  • 在我的 wase 口音中不能使用 chr 和 ord
  • 什么不起作用?编码、解码、加密还是解密?请提供minimal reproducible example 好吗?
  • >>> test = bytearray("é",'utf8') >>> print(test) bytearray(b'\xc3\xa9') 当我解码时我没有“é”

标签: python string rsa non-ascii-characters


【解决方案1】:

参考这篇文章:https://stackoverflow.com/a/2788599

你需要的是

>>> '\xc3\xa9'.decode('utf8')
u'\xe9'
>>> u = '\xc3\xa9'.decode('utf8')
>>> u
u'\xe9'
>>> ucd.name(u)
'LATIN SMALL LETTER E WITH ACUTE'

【讨论】:

  • 而且 'e'.encode('utf8') 也可能对你有用。
猜你喜欢
  • 1970-01-01
  • 2017-10-31
  • 2017-09-05
  • 2017-11-12
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2011-07-02
相关资源
最近更新 更多