英文:
AES Encryption in Swift?
问题
我正在Swift中进行AES加密。
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加密算法,但我得到了垃圾输出。请帮忙解决!
英文:
I am working AES Encryption in Swift.
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;
}
I dont find Encryption with AES CBC PKCS5Padding for iOS 13 and below . iOS 13 has CryptoKit which is not what I require.
Swift Conversion that I tried:
//here operation is default value of kCCEncrypt that is 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);
}
What I get from swift output is
�4 ��ɚ�-���.�'��kZU����Xm�E��X��S��^������I�WW�>a�bo)K����pS��=�>��he�-�}ͮQrqZha�d�i��
[��
*U�����y���a�m0H������.)˶X�#t�6�C��w5@����Q����V�.w�!��� qyjH$S C�,�u��ܻ��L�ȧ�����_V�ym�R~RG���\o�S&
kdx|�m�L��x�t� �d��<�� _���,/��ͺ9�=��X.��а��ft�3�Ф�G�V�QH=?����:jc�
��Ԫ��������
!�ϝ5}��V�PA
��<jt��,�����e��4E�!I�Pd�x���U�
I am not understanding what error am I doing I followed AES Encryption algorithm only still I get garbage output. Please help!!!
答案1
得分: 1
最终编写出解决方案:
import CommonCrypto
struct AES {
// MARK: - 值
// MARK: 私有
private let key: Data
private let iv: Data
// MARK: - 初始化
init?(key: String, iv: String) {
guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
debugPrint("错误:无法设置密钥。")
return nil
}
guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
debugPrint("错误:无法设置初始向量。")
return nil
}
self.key = keyData
self.iv = ivData
}
// MARK: - 函数
// MARK: 公开
func encrypt(string: String) -> String {
guard let cryptData = crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt)) else { return "" }
return cryptData.base64EncodedString()
}
func decrypt(data: Data?) -> String? {
guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil }
return String(bytes: decryptedData, encoding: .utf8)
}
func crypt(data: Data?, option: CCOperation) -> Data? {
guard let data = data else { return nil }
let cryptLength = data.count + kCCBlockSizeAES128
var cryptData = Data(count: cryptLength)
let keyLength = key.count
let options = CCOptions(kCCOptionPKCS7Padding)
var bytesLength = Int(0)
let status = cryptData.withUnsafeMutableBytes { cryptBytes in
data.withUnsafeBytes { dataBytes in
iv.withUnsafeBytes { ivBytes in
key.withUnsafeBytes { keyBytes in
CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes.baseAddress, keyLength, ivBytes.baseAddress, dataBytes.baseAddress, data.count, cryptBytes.baseAddress, cryptLength, &bytesLength)
}
}
}
}
guard UInt32(status) == UInt32(kCCSuccess) else {
debugPrint("错误:无法加密/解密数据。状态 \(status)")
return nil
}
cryptData.removeSubrange(bytesLength..<cryptData.count)
return cryptData
}
}
要将加密后的值作为字符串获取:
let encryptedPassword128 = aes128?.encrypt(string: response1)
英文:
Finally coded up the solution :
import CommonCrypto
struct AES {
// MARK: - Value
// MARK: Private
private let key: Data
private let iv: Data
// MARK: - Initialzier
init?(key: String, iv: String) {
guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
debugPrint("Error: Failed to set a key.")
return nil
}
guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
debugPrint("Error: Failed to set an initial vector.")
return nil
}
self.key = keyData
self.iv = ivData
}
// MARK: - Function
// MARK: Public
func encrypt(string: String) -> String {
guard let cryptData = crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt)) else { return "" }
return cryptData.base64EncodedString()
}
func decrypt(data: Data?) -> String? {
guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil }
return String(bytes: decryptedData, encoding: .utf8)
}
func crypt(data: Data?, option: CCOperation) -> Data? {
guard let data = data else { return nil }
let cryptLength = data.count + kCCBlockSizeAES128
var cryptData = Data(count: cryptLength)
let keyLength = key.count
let options = CCOptions(kCCOptionPKCS7Padding)
var bytesLength = Int(0)
let status = cryptData.withUnsafeMutableBytes { cryptBytes in
data.withUnsafeBytes { dataBytes in
iv.withUnsafeBytes { ivBytes in
key.withUnsafeBytes { keyBytes in
CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes.baseAddress, keyLength, ivBytes.baseAddress, dataBytes.baseAddress, data.count, cryptBytes.baseAddress, cryptLength, &bytesLength)
}
}
}
}
guard UInt32(status) == UInt32(kCCSuccess) else {
debugPrint("Error: Failed to crypt data. Status \(status)")
return nil
}
cryptData.removeSubrange(bytesLength..<cryptData.count)
return cryptData
}
}
To get the encrypted value as string:
let encryptedPassword128 = aes128?.encrypt(string: response1)
答案2
得分: 0
我使用了 CryptoSwift(https://cryptoswift.io)。
func getEncryptedValue(value: String) -> String {
let key = "someSecretKey"
if let aes = try? AES(key: key.bytes, blockMode: ECB(), padding: .pkcs5),
let aesE = try? aes.encrypt(Array(value.utf8)) {
print("base64: \(Array(aesE).toBase64())")
let result = Array(aesE).toBase64()
return result
}
return ""
}
英文:
I used CryptoSwift (https://cryptoswift.io).
func getEncryptedValue(value: String) -> String {
let key = "someSecretKey"
if let aes = try? AES(key: key.bytes, blockMode: ECB(), padding: .pkcs5),
let aesE = try? aes.encrypt(Array(value.utf8)) {
print("base64: \(Array(aesE).toBase64())")
let result = Array(aesE).toBase64()
return result
}
return ""
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论