Python加密(不对称)

时间:2015-07-22 18:22:46

标签: python encryption cryptography

我对加密感兴趣了一段时间,我决定在Python中使用我自己的加密脚本。我遇到了一些“少数人”。问题。我确信解决方案很简单,但对于我的生活,我无法弄清楚。

所以:这是我的加密/解密脚本放在一个脚本中:

def encrypt(key1, msg):
    encrypted =[]
    for i, c in enumerate(msg):
            msg_c = ord(c)
            encrypted.append(unichr((msg_c + key1) % (key1+key2)))
    return ''.join(encrypted)

def decrypt(key2, encryped):
    decrypted = []
    for i, c in enumerate(encryped):
        enc_c = ord(c)
        decrypted.append(unichr((enc_c + key2) % (key1+key2)))
    return ''.join(decrypted)

if __name__ == '__main__':
    key1 = int(raw_input("Key 1: "))
    key2 = int(raw_input("Key 2: "))
    msg = raw_input("Message to Encrypt: ")
    encrypted = encrypt(key1, msg)
    decrypted = decrypt(key2, encrypted)

print 'Encrypted: ', repr(encrypted)
print 'Decrypted: ', repr(decrypted)

因此,如果我将密钥1设置为5521并将密钥2设置为223并将我的消息设置为加密测试,则会收到以下输出:

Encrypted:  u'\u15e5\u15f6\u1604\u1605'
Decrypted:  u'Test'

所以,这很有效。这很好,很棒。它显示了Test将使用密钥1和密钥2加密。但是,我想将其分成两个单独的脚本。一个加密和另一个解密。

所以我的加密脚本是这样的:

def encrypt(key1, msg):
    encrypted =[]
    for i, c in enumerate(msg):
            msg_c = ord(c)
            encrypted.append(unichr((msg_c + key1) % (key1+key2)))
    return ''.join(encrypted)
if __name__ == '__main__':
    key1 = int(raw_input("Key 1: "))
    key2 = int(raw_input("Key 2: "))
    msg = raw_input("Message to Encrypt: ")
    encrypted = encrypt(key1, msg)

print 'Encrypted: ', repr(encrypted)

使用与第一个脚本相同的输入,我得到以下输出:

Encrypted:  u'\u15e5\u15f6\u1604\u1605'

所以,这也很好。它给了我与以前相同的加密字符串。然而,这是我的Decrypt脚本:

def decrypt(key2, encryped):
    decrypted = []
    for i, c in enumerate(encryped):
        enc_c = ord(c)
        decrypted.append(unichr((enc_c + key2) % (key1+key2)))
    return ''.join(decrypted)

if __name__ == '__main__':
    key1 = int(raw_input("Key 1: "))
    key2 = int(raw_input("Key 2: "))
    encrypted = raw_input("Message to Decrypt: ")
    decrypted = decrypt(key2, encrypted)

print 'Decrypted: ', repr(decrypted)

现在,如果我输入相同的两个键,我将消息输入解密为:u' \ u15e5 \ u15f6 \ u1604 \ u1605'我得到以下输出:

Decrypted:  u'\u0154\u0106\u013b\u0154\u0110\u0114\u0144\u0114\u013b\u0154\u0110\u0114\u0145\u0115\u013b\u0154\u0110\u0115\u010f\u0113\u013b\u0154\u0110\u0115\u010f\u0114\u0106'

如果我修改输入以排除你''并且只放置\ u15e5 \ u15f6 \ u1604 \ u1605部分,我明白了:

Decrypted: u'\u013b\u0154\u0110\u0114\u0144\u0114\u013b\u0154\u0110\u0114\u0145\u0115\u013b\u0154\u0110\u0115\u010f\u0113\u013b\u0154\u0110\u0115\u010f\u0114'

关于我做错了什么的任何想法?好像我应该得到相同的输出," u'测试'"但由于某种原因,我不是。

0 个答案:

没有答案