gpt4 book ai didi

ruby - CryptoSwift 和 Ruby AES 的填充错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:21:15 24 4
gpt4 key购买 nike

我很难让 CryptoSwiftRuby 的 OpenSSL AES 完美搭配

我的 Swift 代码:

let key = ("12345678901234567890123456789012" as NSString).dataUsingEncoding(NSUTF8StringEncoding)?.arrayOfBytes() //32 chars because im testing AES 256
let iv = Cipher.randomIV(AES.blockSize)
let data = NSData(bytes: iv, length: Int(iv.count))
let ivstring = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
print(ivstring)

let message = "Hello World".dataUsingEncoding(NSUTF8StringEncoding)?.arrayOfBytes()

do
{

let encrypted = try AES(key: key!, iv: iv, blockMode: .CBC)?.encrypt(message!, padding: PKCS7())
let decrypted = try AES(key: key!, iv: iv, blockMode: .CBC)?.decrypt(encrypted!, padding: PKCS7())

let encData = NSData(bytes: encrypted!, length: Int(encrypted!.count))
let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let result = String(base64String)
print(result)

let decData = NSData(bytes: decrypted!, length: Int(decrypted!.count))
let result2 = NSString(data: decData, encoding: NSUTF8StringEncoding)
print(result2!)

}
catch
{

}

哪些输出:

7oR9lu+ROC7PW7bDqXcRxw==
XzZj2OTTbA8zaedeoVh0KA==
Hello World

然后在 Ruby 中我做:

key = "12345678901234567890123456789012"
iv = "7oR9lu+ROC7PW7bDqXcRxw=="

encrypted = "XzZj2OTTbA8zaedeoVh0KA=="

decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
decipher.key = key
decipher.iv = iv
plain = decipher.update(encrypted) + decipher.final

ruby 代码在最后一行 plain = decipher.update(encrypted) + decipher.final 上抛出一个错误声明:

OpenSSL::Cipher::CipherError
=================================================
> wrong final block length

我显然不是加密方面最有经验的人,但如果你能给我任何帮助,我将不胜感激!

最佳答案

在解密之前,您需要对数据和 iv 进行 base 64 解码。您目前正在通过 AES 直接发送 base 64 编码数据。

不要忘记在解密后去除填充。

关于ruby - CryptoSwift 和 Ruby AES 的填充错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com