2

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

这就是我在 swift 中的功能:

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' 

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

4

1 回答 1

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()```
于 2019-08-02T18:33:58.373 回答