Python Rsa密码错误

Python Rsa密码错误,python,Python,我用Python3.4编写了以下代码 import sys DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def main(): filename = 'encrypted_file.txt' mode = 'encrypt' if mode == 'encrypt': message = '''"Journalists belong in the gutter because that is where

我用Python3.4编写了以下代码

        import sys
DEFAULT_BLOCK_SIZE = 128
BYTE_SIZE = 256
def main():
    filename = 'encrypted_file.txt'
    mode = 'encrypt'
    if mode == 'encrypt':
        message = '''"Journalists belong in the gutter because that is where the ruling classes throw their guilty secrets." -Gerald Priestland "TheFounding Fathers gave the free press the protection it must have to bare the secrets of government and inform the people." -Hugo Black'''
        pubKeyFilename = 'vineeth_pubkey.txt'
        print('Encrypting and writing to %s...' % (filename))
        encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message)
        print('Encrypted text:')
        print(encryptedText)
    elif mode == 'decrypt':
        privKeyFilename = 'vineeth_privkey.txt'
        print('Reading from %s and decrypting...' % (filename))
        decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)
        print('Decrypted text:')
        print(decryptedText)

def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
    messageBytes = message.encode('ascii')
    blockInts = []
    for blockStart in range(0, len(messageBytes), blockSize):
        blockInt = 0
        for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))):
            blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))
        blockInts.append(blockInt)
    return blockInts

def getTextFromBlocks(blockInts, messageLength,blockSize=DEFAULT_BLOCK_SIZE):
    message = []
    for blockInt in blockInts:
        blockMessage = []
        for i in range(blockSize- 1, -1, -1):
            if len(message) + i < messageLength:
                asciiNumber = blockInt // (BYTE_SIZE ** i)
                blockInt = blockInt % (BYTE_SIZE ** i)
                blockMessage.insert(0, chr(asciiNumber))
        message.extend(blockMessage)
    return ''.join(message)

def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):
    encryptedBlocks = []
    n, e = key
    for block in getBlocksFromText(message, blockSize):
        encryptedBlocks.append(pow(block, e, n))
    return encryptedBlocks

def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE):
    decryptedBlocks = []
    n, d = key
    for block in encryptedBlocks:
        decryptedBlocks.append(pow(block, d, n))
    return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)

def readKeyFile(keyFilename):
    fo = open(keyFilename)
    content = fo.read()
    fo.close()
    keySize, n, EorD = content.split(',')
    return (int(keySize), int(n), int(EorD))

def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE):
    keySize, n, e = readKeyFile(keyFilename)
    if keySize < blockSize * 8:
        print'ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or less than the key size. Either increase the block size or use different keys.' % (blockSize * 8, keySize)
        sys.exit()
    encryptedBlocks = encryptMessage(message, (n, e), blockSize)
    for i in range(len(encryptedBlocks)):
        encryptedBlocks[i] = str(encryptedBlocks[i])
    encryptedContent = ','.join(encryptedBlocks)
    encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
    fo = open(messageFilename, 'w')
    fo.write(encryptedContent)
    fo.close()
    return encryptedContent

def readFromFileAndDecrypt(messageFilename, keyFilename):
    keySize, n, d = readKeyFile(keyFilename)
    fo = open(messageFilename)
    content = fo.read()
    messageLength, blockSize, encryptedMessage = content.split('_')
    messageLength = int(messageLength)
    blockSize = int(blockSize)
    if keySize < blockSize * 8:
        print 'ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or less than the keysize. Did you specify the correct key file and encrypted file?' % (blockSize * 8, keySize)
    encryptedBlocks = []
    for block in encryptedMessage.split(','):
        encryptedBlocks.append(int(block))
    return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize)

if __name__ == '__main__':
    main()
导入系统 默认块大小=128 字节大小=256 def main(): 文件名='encrypted_file.txt' 模式='encrypt' 如果模式==“加密”: 信息=''''“记者属于贫民区,因为那是统治阶级抛出他们罪恶秘密的地方。”-杰拉尔德·普里斯兰“创始人给予了自由新闻界必须的保护,使其能够揭露政府的秘密并告知人民。”-雨果·布莱克“ pubKeyFilename='Vineth_pubkey.txt' 打印('加密并写入%s...%(文件名)) encryptedText=EncryptedWriteFile(文件名、pubKeyFilename、消息) 打印('加密文本:') 打印(加密文本) elif模式==“解密”: privKeyFilename='Vineth_privkey.txt' 打印('从%s读取并解密…'%(文件名)) decryptedText=readFromFileAndDecrypt(文件名,privKeyFilename) 打印('解密文本:') 打印(解密文本) def getBlocksFromText(消息,块大小=默认块大小): messageBytes=message.encode('ascii') blockInts=[] 对于范围(0,len(messageBytes),blockSize)内的blockStart: blockInt=0 对于范围内的i(blockStart,min(blockStart+blockSize,len(messageBytes)): blockInt+=messageBytes[i]*(字节大小**(i%blockSize)) blockInts.append(blockInt) 返回blockInts def getTextFromBlocks(blockInts、messageLength、blockSize=默认块大小): 消息=[] 对于blockInts中的blockInt: blockMessage=[] 对于范围内的i(块大小-1,-1,-1): 如果len(message)+i 在Python2.7中使用时,会生成以下错误

    Traceback (most recent call last):
    File "E:\Python27\My programs\rsa.py", line 94, in <module>
    main()
  File "E:\Python27\My programs\rsa.py", line 11, in main
    encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message)
  File "E:\Python27\My programs\rsa.py", line 69, in encryptAndWriteToFile
    encryptedBlocks = encryptMessage(message, (n, e), blockSize)
  File "E:\Python27\My programs\rsa.py", line 46, in encryptMessage
    for block in getBlocksFromText(message, blockSize):
  File "E:\Python27\My programs\rsa.py", line 27, in getBlocksFromText
    blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
回溯(最近一次呼叫最后一次):
文件“E:\Python27\My programs\rsa.py”,第94行,在
main()
文件“E:\Python27\My programs\rsa.py”,第11行,在main中
encryptedText=EncryptedWriteFile(文件名、pubKeyFilename、消息)
EncryptAndWriteFile中第69行的文件“E:\Python27\My programs\rsa.py”
encryptedBlocks=encryptMessage(消息,(n,e),块大小)
encryptMessage中第46行的文件“E:\Python27\My programs\rsa.py”
对于getBlocksFromText中的块(消息,块大小):
getBlocksFromText中第27行的文件“E:\Python27\My programs\rsa.py”
blockInt+=messageBytes[i]*(字节大小**(i%blockSize))
TypeError:不支持+=:'int'和'str'的操作数类型
有没有人能帮助排除这段代码的故障,使它在Python2.7中工作

谢谢

另外,它在python 3.4中工作。

查看错误

TypeError:不支持+=:'int'和'str'的操作数类型

它源于

getBlocksFromText中第27行的文件“E:\Python27\My programs\rsa.py” blockInt+=messageBytes[i]*(字节大小**(i%blockSize))

您正在尝试对int和字符串执行and操作。您需要将它们转换为相同的类型

numbers = 12345
letters = 'abcde'
num_letters = '12345'

# this works:
str(numbers)
int(num_letters)

# this doesn't work:
int(letters)

我知道这个错误,但我不知道如何将int和string转换成相同的类型。如果您发布代码的编辑版本,这将非常有用。谢谢这可能不是原因。在Python3中,仍然不能在
int
str
上使用
+=
进行操作。问题可能是Python 2中的行为不同,从而导致不同的数据类型。也许缺少一个显式c