Rsa密码

2024-09-29 05:22:54 发布

您现在位置: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 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()

在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'

有没有人能帮忙排除这段代码的故障,让它在Python2.7中工作?你知道吗

谢谢!你知道吗

另外,它在python3.4中工作。你知道吗


Tags: thekeyinmessageforsizedefblock
1条回答
网友
1楼 · 发布于 2024-09-29 05:22:54

看看这个错误

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

它是从

File "E:\Python27\My programs\rsa.py", line 27, in getBlocksFromText blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))

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

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

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

# this doesn't work:
int(letters)

相关问题 更多 >