我正在为Swift-only
和Extension
String
加密/解密NSData
工作,而隐藏部分正在根据@Zaph提供的答案工作相关问题:Issue using CCCrypt (CommonCrypt) in Swift
使用Objective-C中的旧的NSData + AESCrypt.m类别测试了crypt输出
我一直在解密部分工作时出现问题:代码编译并运行正常,但结果不是最初加密的预期文本。
extension NSData {
func AES256EncryptDataWithKey(key: String) -> NSData {
let keyData: NSData! = (key as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafePointer<UInt8>(keyData.bytes)
let keyLength = size_t(kCCKeySizeAES256)
let dataLength = UInt(self.length)
let dataBytes = UnsafePointer<UInt8>(self.bytes)
let bufferData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
var bufferPointer = UnsafeMutablePointer<UInt8>(bufferData.mutableBytes)
let bufferLength = size_t(bufferData.length)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesEncrypted: UInt = 0
var cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
bufferPointer, bufferLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
bufferData.length = Int(numBytesEncrypted) // Requiered to adjust buffer size
return bufferData as NSData
} else {
println("Error: \(cryptStatus)")
return NSData()
}
}
func AES256DecryptDataWithKey(key: String) -> NSData {
let keyData: NSData! = (key as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafePointer<UInt8>(keyData.bytes)
let keyLength = size_t(kCCKeySizeAES256)
let dataLength = UInt(self.length)
let dataBytes = UnsafePointer<UInt8>(self.bytes)
let string = self.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let bufferData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
var bufferPointer = UnsafeMutablePointer<UInt8>(bufferData.mutableBytes)
let bufferLength = size_t(bufferData.length)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesDecrypted: UInt = 0
var cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
bufferPointer, bufferLength,
&numBytesDecrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
bufferData.length = Int(numBytesDecrypted) // Requiered to adjust buffer size
return bufferData as NSData
} else {
println("Error: \(cryptStatus)")
return NSData()
}
}
}
extension String {
func AES256EncryptStringWithKey(key: String) -> String {
let data = (self as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let encryptedData = data.AES256EncryptDataWithKey(key)
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = encryptedData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return base64cryptString
}
func AES256DecryptStringWithKey(key: String) -> String {
let data: NSData! = (self as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let decryptedData = data.AES256DecryptDataWithKey(key)
// Not all data is a UTF-8 string so Base64 is used
let base64decryptString = decryptedData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return base64decryptString
}
}
您可以看到String.encryptStringWithKey()
调用NSData.encryptDataWithKey()
。因此,扩展程序适用于String
和NSData
let string: String = "Don´t try to read this text. Top Secret Stuff"
let key = "12345678901234567890123456789012"
println("Original String : \(string)");
let encryptedString = string.AES256EncryptStringWithKey(key)
println("Encrypted String : \(encryptedString)")
let decryptedString = encryptedString.AES256DecryptStringWithKey(key)
println("Decrypted String: \(decryptedString)")
任何帮助将不胜感激
答案 0 :(得分:2)
不同之处在于NSData + AESCrypt.m正在使用CBC模式(默认值),其中iv为NULL。问题中的代码是使用ECB模式。
最佳做法是使用随机iv的CBC模式。 iv通常预先加密到加密数据,因此解密可以在解密之前将iv和数据分开。
不要使用NSData + AESCrypt.m,它尚未维护,是NSData上的一个类别,不支持ARC。对Objective-C考虑RNCryptor,它是主动维护的。
这是我在&#34; NSData + AESCrypt.m&#34;,方法AES256EncryptWithKey:
kCCOptionPKCS7Padding + kCCOptionECBMode
中所做的更改。我添加了kCCOptionECBMode
,这就是全部。
这是我的电话: NSString * keyString = @&#34; 12345678901234567890123456789012&#34 ;;
NSString *message = @"Don´t try to read this text. Top Secret Stuff";
NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
NSData *crypData = [data AES256EncryptWithKey:keyString];
NSLog(@"crypData: %@", crypData);
输出:
crypData: <118a32dc c23f7caa 883abc3c 1c7f0770 e200016b 2737acfa 17bb96fb a02b02a7 c147603b 06acd863 94bb8ff2 6cb14515>
与上述代码相同(与上一个问题相同):
cryptData = <118a32dc c23f7caa 883abc3c 1c7f0770 e200016b 2737acfa 17bb96fb a02b02a7 c147603b 06acd863 94bb8ff2 6cb14515>
这只是让所有输入都相同的问题:操作,算法,选项,keyBytes,keyLength,dataBytes,dataLength和iv,如果是非ECB模式。 CCCrypt
只是一个函数调用,这就是全部。输入相同的输入,得到相同的输出。
输入NSLog()
语句,最好是数据和字符串的十六进制转储。根据需要进行比较和修复。
信不信由你,这是电子安全的简单部分。
答案 1 :(得分:1)
Swift 2.0 AES128加密和解密。
应将以下标头导入Obj-c网桥标头以便工作
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonKeyDerivation.h>
static func AES128Encryption()
{
let keyString = "12345678901234567890123456789012"
let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafeMutablePointer<Void>(keyData.bytes)
print("keyLength = \(keyData.length), keyData = \(keyData)")
let message = "Don´t try to read this text. Top Secret Stuff"
let data: NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let dataLength = size_t(data.length)
let dataBytes = UnsafeMutablePointer<Void>(data.bytes)
print("dataLength = \(dataLength), data = \(data)")
let cryptData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
let cryptLength = size_t(cryptData!.length)
let keyLength = size_t(kCCKeySizeAES256)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding + kCCOptionECBMode)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
// let x: UInt = numBytesEncrypted
cryptData!.length = Int(numBytesEncrypted)
print("cryptLength = \(numBytesEncrypted), cryptData = \(cryptData)")
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = cryptData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
print("base64cryptString = \(base64cryptString)")
} else {
print("Error: \(cryptStatus)")
}
}
static func AES128Decryption(data:NSData) //data = cryptData
{
let keyString = "12345678901234567890123456789012"
let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafeMutablePointer<Void>(keyData.bytes)
print("keyLength = \(keyData.length), keyData = \(keyData)")
//let message = "Don´t try to read this text. Top Secret Stuff"
// let data: NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let dataLength = size_t(data.length)
let dataBytes = UnsafeMutablePointer<Void>(data.bytes)
print("dataLength = \(dataLength), data = \(data)")
let cryptData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
let cryptLength = size_t(cryptData!.length)
let keyLength = size_t(kCCKeySizeAES256)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding + kCCOptionECBMode)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
// let x: UInt = numBytesEncrypted
cryptData!.length = Int(numBytesEncrypted)
print("DecryptcryptLength = \(numBytesEncrypted), Decrypt = \(cryptData)")
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = cryptData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
print("base64DecryptString = \(base64cryptString)")
print( "utf8 actual string = \(NSString(data: cryptData!, encoding: NSUTF8StringEncoding))");
} else {
print("Error: \(cryptStatus)")
}
}
答案 2 :(得分:0)
Swift4 AES128解密和JWT
注意:如果在加密纯文本时将iv与密钥一起使用,则在解密时不使用iv,您的问题将得到解决。 密钥和iv 的长度为16位
以下用于解密的代码可以帮助您: 在这里,用于解密的加密字符串是 base64Encoded ,而我们得到的解密字符串是JWT(Json Web令牌)。
要配置CommonCrypto,请参考链接: How is CommonCrypto used in SWIFT3?
https://www.devglan.com/online-tools/aes-encryption-decryption https://jwt.io/
导入UIKit 导入CommonCrypto
ViewController类:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
testAES()
}
func testAES() {
let testMessSr = "74oIlwieBbxGvHjibQoSxWWAL0zNfy7yaQboYizPc+ouMsAkXbvMNb0RagXklA2zOlo29J7Zr7zFiOalBfKSvV3pzw7KWCtTMw16SNeOIRWYpSWNcNXxgoQR7Jy33s0JP8elQCo/6G+inivE2hm3kl7QTr/Jz5bx/ho0LmWrirn/L4WAJlDFHue23vjhrKGIfEvwIdWHPNh1qd+hCY4pQA==:NjkzQUU1MkM5RTZERjNFMA=="
//Here I'm separating iv from base64encoded string as while decrypting theres no need of iv
let splitStr = testMessSr.components(separatedBy: ":")
print("base64EncodedString: \(splitStr[0])")
print("iv: \(splitStr[1])")
let base64EncodedString = splitStr[0]
let message = Data(base64Encoded: base64EncodedString ,options : Data.Base64DecodingOptions.ignoreUnknownCharacters)
let key = "EE99C7A159003D36"
let ivString = "693AE52C9E6DF3E0" // 16 bytes for AES128
// let messageData = message.data(using:String.Encoding.utf8)!
let keyData = key.data(using: .utf8)!
let ivData = ivString.data(using: .utf8)!
let decryptedData = message?.aesEncrypt( keyData:keyData, ivData:ivData, operation:kCCDecrypt)
print("decryptedData: \(decryptedData)")
let decryptedString = String(data: decryptedData as! Data, encoding: String.Encoding.utf8)
print("decryptedString: \(decryptedString)") //JWT token
}
}
扩展数据{
func aesEncrypt( keyData: Data, ivData: Data, operation: Int) -> Data {
let dataLength = self.count
let cryptLength = size_t(dataLength + kCCBlockSizeAES128)
var cryptData = Data(count:cryptLength)
let keyLength = size_t(kCCKeySizeAES128)
let options = CCOptions(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
self.withUnsafeBytes {dataBytes in
ivData.withUnsafeBytes {ivBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(operation),
CCAlgorithm(kCCAlgorithmAES),
options,
keyBytes, keyLength,
ivBytes,
dataBytes, dataLength,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
} else {
print("Error: \(cryptStatus)")
}
return cryptData;
}
}