【问题标题】:How to encrypt a string using RSA scheme?如何使用 RSA 方案加密字符串?
【发布时间】:2018-10-15 16:01:41
【问题描述】:

我正在使用来自此站点的 RSA 实施教程:https://sahandsaba.com/cryptography-rsa-part-1.html

他们使用此功能进行加密:

def power(x, m, n):
    """Calculate x^m modulo n using O(log(m)) operations."""
    a = 1
    while m > 0:
        if m % 2 == 1:
            a = (a * x) % n
        x = (x * x) % n
        m //= 2
    return a

def rsa_encrypt(message, n, e):
    return modular.power(message, e, n)

然后他加密了一个数字:

>>> message = 123
>>> cipher = rsa_encrypt(message, n, e)

我如何加密整个字符串?我想使用此实现加密由哈希生成的字符串。

【问题讨论】:

  • 字符串是字符,字符有一个 ascii 值 ord('B') - 一个整数值。构建一个可以转换string -> ord -> rsa and rsa -> ord -> string 的链 - 哈希通常是不可逆的,因此您只能恢复哈希 - 而不是原始字符串。

标签: python encryption hash rsa


【解决方案1】:

你缺少的两个函数是从一个字节序列到一个数字,然后返回:

def bytes2num(b):
    return b[0] + 256 * bytes2num(b[1:]) if b else 0

def num2bytes(n):
    return bytes([n % 256]) + num2bytes(n // 256) if n else b''

如果你想使用字符串,你可以定义函数:

def str2num(s):
    return bytes2num(s.encode('utf-8'))

def num2str(n):
    return num2bytes(n).decode('utf-8')

如果您的消息很长,您应该迭代这些实现。

测试:

>>> s = 'Hello, world!'

>>> str2num(s)
2645608968347327576478451524936

>>> num2str(2645608968347327576478451524936)
'Hello, world!'

【讨论】:

  • 不,您不需要将字符串分割成块。另请参阅此问题:crypto.stackexchange.com/questions/32344/…
  • @sushionthefork:它从字节值创建一个大数字。如果字节序列s组成,那么代表它的数字是b0*256^0+b1*256^1+b2*256^2+.. .+bN*256^N
  • @sushionthefork:作为进一步说明,您可以将字节序列视为 base256 数字,因此这是与 base10 的通常转换。
  • 这是一个内联if。另一种写法是if b: return b[0] + 256 * bytes2num(b[1:]); else: return 0。当字节序列为空时返回 0 是该递归函数的基本情况。
  • @fferri 在 python 3 中(我假设你正在使用它,由于 str/bytes 命名),你可以用内置函数替换 bytes2num/num2bytes 的自定义逻辑:@987654330 @ 和n.to_bytes((n.bit_length() - 1) // 8 + 1, 'little'),分别。
猜你喜欢
  • 1970-01-01
  • 2014-10-29
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多