Encrypt/Decrypt iOS 中的字符串使用 CryptoSwift
Encrypt/Decrypt string in iOS using CryptoSwift
我正在尝试加密一个字符串,然后使用 CryptoSwift 将其解密。这是代码:
let key: [UInt8] = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c]
let iv: [UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
let message = "Hello there!".dataUsingEncoding(NSUTF8StringEncoding)!.arrayOfBytes()
do {
let encryptedBytes = try ChaCha20(key: key, iv: iv)!.encrypt(message)
let decryptedBytes = try ChaCha20(key: key, iv: iv)!.decrypt(encryptedBytes)
let data = NSData.withBytes(decryptedBytes)
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
print(decrypted) // this should print "Hello there!", but it doesn't
}
catch { ... }
我认为这应该打印出 "Hello there!"
原始字符串。但是我得到了这个:(<48656c6c 6f207468 65726521>, 4)
知道我做错了什么吗?
我想通了。更改了这一行:
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
至:
let decrypted = String(bytes: decryptedBytes, encoding: NSUTF8StringEncoding)
现在可以使用了。
我正在尝试加密一个字符串,然后使用 CryptoSwift 将其解密。这是代码:
let key: [UInt8] = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c]
let iv: [UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
let message = "Hello there!".dataUsingEncoding(NSUTF8StringEncoding)!.arrayOfBytes()
do {
let encryptedBytes = try ChaCha20(key: key, iv: iv)!.encrypt(message)
let decryptedBytes = try ChaCha20(key: key, iv: iv)!.decrypt(encryptedBytes)
let data = NSData.withBytes(decryptedBytes)
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
print(decrypted) // this should print "Hello there!", but it doesn't
}
catch { ... }
我认为这应该打印出 "Hello there!"
原始字符串。但是我得到了这个:(<48656c6c 6f207468 65726521>, 4)
知道我做错了什么吗?
我想通了。更改了这一行:
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
至:
let decrypted = String(bytes: decryptedBytes, encoding: NSUTF8StringEncoding)
现在可以使用了。