AES密码术有问题(特别是使用CryptoSwift加密和使用PyCryptodome解密)

时间:2019-08-02 18:02:06

标签: python swift encryption pycryptodome cryptoswift

我目前正在尝试使用AES加密技术来加密和解密始终具有9个字符长度的字符串。我想做的是快速加密字符串,然后在python中解密该加密字符串。我在CryptoSwift中使用AES加密,在PyCryptodome中使用解密。

这就是我迅速执行的功能:

import CryptoSwift
func crypto_testing() {
        print("Cryptography!")

        let ivString = "0000000000000000"
        let keyString = "This is a key123"

        let key = [UInt8](keyString.utf8)
        let iv = [UInt8](ivString.utf8)
        let stringToEncrypt = "123456789"


        let enc = try! aesEncrypt(stringToEncrypt: stringToEncrypt, key: key, iv: iv)
        print("ENCRYPT:",enc)
    }


    func aesEncrypt(stringToEncrypt: String, key: Array<UInt8>, iv: Array<UInt8>) throws -> String {
        let data = stringToEncrypt.data(using: String.Encoding.utf8)
        let encrypted = try AES(key: key, blockMode: CFB(iv: iv), padding: .noPadding).encrypt((data?.bytes)!)
        return encrypted.toHexString() //result
    }

通过运行crypto_testing函数得到的结果是:

Cryptography!
ENCRYPT: 5d02105a49e55d2ff7

此外,这就是我的解密函数在python中的样子:

import binascii
from Crypto.Cipher import AES

KEY = b'This is a key123'
IV = b'0000000000000000'
MODE = AES.MODE_CFB

def decrypt(key, iv, encrypted_text):
    aes = AES.new(key, MODE, iv)
    encrypted_text_bytes = binascii.a2b_hex(encrypted_text)
    decrypted_text = aes.decrypt(encrypted_text_bytes)
    return decrypted_text

decrypted_text = decrypt(KEY, IV, encrypted_text)
print(decrypted_text)

将加密消息插入解密函数的结果如下:

>>> decrypt(b'This is a key123', b'0000000000000000', '5d02105a49e55d2ff7')

b'1%\xdc\xc8\xa0\r\xbd\xb8\xf0' 

如果有人对这里出了什么问题有任何线索,那将是一个很大的帮助。

1 个答案:

答案 0 :(得分:0)

尝试一下:


let stringToEncrypt = "123456789"

var aes: AES

var encrypted: [UInt8]

do {

aes = try AES(key: key, blockMode: CBC(iv: iv), padding: . noPadding)

 encrypted = try aes.encrypt(stringToEncrypt.bytes)

}

let base64Encypted = encrypted.toBase64()```