我很难相处CryptoSwift
得很好Ruby's OpenSSL AES
我的斯威夫特代码:
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
我显然不是加密领域最有经验的人,但您能给我的任何帮助将不胜感激!