Issue
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!!!
Solution
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)
Answered By - sujit amin
Answer Checked By - Pedro (JavaFixing Volunteer)