我有这种解码方法:
-(NSString *)decrypt:(NSString *)encryptedTextValue withSecret:(NSString*)secret
{
NSData *encryptedData = [NSData base64DataFromString:encryptedTextValue];
NSData *decryptedData = [encryptedData decryptedAES256DataUsingKey:[[secret dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];
NSString *plainText = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
return plainText;
}
和decryptedAES256DataUsingKey方法是这样的:
- (NSData *) AES256EncryptedDataUsingKey: (id) key error: (NSError **) error
{
CCCryptorStatus status = kCCSuccess;
NSData * result = [self dataEncryptedUsingAlgorithm: kCCAlgorithmAES128
key: key
options: kCCOptionPKCS7Padding
error: &status];
if ( result != nil )
return ( result );
if ( error != NULL )
*error = [NSError errorWithCCCryptorStatus: status];
return ( nil );
}
我也有哈希,这是:
wnXGfwFQr4463RLAczVJGw ==
有人能告诉我如何将其解码为原始字符串? 我也有秘密密钥,但我不明白我应该如何ecnode它,解码散列。
答案 0 :(得分:1)
请参阅使用Common Crypto的Swift AES加密示例,它有助于您的转换。
func testCrypt(data:Data, keyData:Data, ivData:Data, operation:Int) -> Data {
let cryptLength = size_t(data.count + 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
data.withUnsafeBytes {dataBytes in
ivData.withUnsafeBytes {ivBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(operation),
CCAlgorithm(kCCAlgorithmAES),
options,
keyBytes, keyLength,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
} else {
print("Error: \(cryptStatus)")
}
return cryptData;
}
您可以使用哈希并根据所需的密钥大小选择字节。但是为了安全起见,使用PBKDF2(基于密码的密钥推导2),其迭代次数使得它需要大约100ms。这是Swift Implementation。
另一种选择就是使用RNCryptor,其中包括PBKDDF2,身份验证和版本控制。