我在Swift中从事AES加密工作。
public static String encrypt1(String plaintext, String key, String IV) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF-8"));
byte[] iv = cipher.getIV();
String asd = Base64.encodeToString(ciphertext, Base64.NO_WRAP);
return asd;
}
我没有找到iOS 13及以下版本的AES CBC PKCS 5 Padding加密。iOS 13有CryptoKit,这不是我所需要的。
我尝试过的快速转换://这里的操作是kCCEncrypt的默认值,即0
public func encrypt1(plainText : String, key: String, iv : String, operation : Int) -> String {
let data = Data(plainText.utf8)
let ivData = Data(iv.utf8)
let keyData = Data(key.utf8)
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)")
}
print("My Encrypted Value: \(String(decoding: cryptData, as: UTF8.self))")
return String(decoding: cryptData, as: UTF8.self);
}
我从快速输出中得到的是:
我不明白我在做什么错误,我只遵循AES加密算法,仍然我得到垃圾输出。请帮助!!!
2条答案
按热度按时间lp0sw83n1#
最后编写了解决方案:
要获取字符串形式的加密值,请执行以下操作:
wswtfjt72#
我使用的是CryptoSwift(https://cryptoswift.io)。