我使用CryptoSwift进行AES加密/解密。当我运行此代码时,它会抛出错误:
"致命错误:数组索引超出范围"。
使用here
的参考这可能是什么原因? 任何建议都会非常感激。
代码:
let key = "1234567890123456" // key
let iv = "1234567890123456" // random
let message = "This is test string"
override func viewDidLoad() {
super.viewDidLoad()
// encrypt
let encrypted = AES(key: key, iv: iv, blockMode: .CBC)
let enc = encrypted?.encrypt(message.utf8Array, padding: PKCS7())
println("enc >> \(enc)")
// decrypt
let decrypted = AES(key: key, iv: iv, blockMode: .CBC)
let dec = encrypted?.decrypt(enc!, padding: PKCS7())
println("dec >> \(dec)")
答案 0 :(得分:0)
问题可能在这里:message.utf8Array
,您将String转换为Array。这是一个有效的例子:
let key = "1234567890123456" // key
let iv = "1234567890123456" // random
let message = "This is test string"
let aes = AES(key: key, iv: iv, blockMode: .CBC)
// encrypt
let enc = try! aes?.encrypt(message.dataUsingEncoding(NSUTF8StringEncoding)!.arrayOfBytes(), padding: PKCS7())
print("enc >> \(enc)")
// decrypt
let dec = try! aes?.decrypt(enc!, padding: PKCS7())
let str = NSString(data: NSData.withBytes(dec!), encoding: NSUTF8StringEncoding)
print("dec >> \(str)")