I would like to generate a cryptographically random key, use that to encrypt the data with a symmetric cypher (AES typically) and then encrypt the random key with RSA.
How can I do it in swift? Is it possible with CryptoKit or CommonCrypto ?
Thanks
Post not yet marked as solved
We have the below Implementation in Android and the same has to be integrated into Swift.
Key :- "d95acd54b4a821ff32c52825q931c194"
IV :- "687b9509c25a34b8ad076346s8353d67"
Here Both the Key and IV are 32 bits and below is the android code.
public class AESEncryption {
private static final String key = "d95acd54c6a821ff32c52825b931c194";
private static final String initVector = "687b9509c25a14b8ad076346d8353d67";
static byte[] bte = hexToBytes(initVector);
public static String encrypt(String strToEncrypt) {
try {
CommonCode.showLog("log", bte.toString());
IvParameterSpec iv = new IvParameterSpec(bte);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
CommonCode.showLog("IV after logs", iv.toString());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(strToEncrypt.getBytes());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return Base64.getEncoder().encodeToString(encrypted).trim();
} else {
return android.util.Base64.encodeToString(encrypted, android.util.Base64.DEFAULT).trim();
}
} catch (Exception e) {
CommonCode.showLog("Error while encrypting: ", e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt) {
try {
IvParameterSpec iv = new IvParameterSpec(bte);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} else {
return new String(cipher.doFinal(android.util.Base64.decode(strToDecrypt, android.util.Base64.DEFAULT)));
}
} catch (Exception e) {
CommonCode.showLog("Error while decrypting: " , e.toString());
}
return null;
}
}
How can we mimic the above in Swift?
Here in Android they are using static byte[] bte = hexToBytes(initVector); to convert the 32bit IV into 16 bit Bytes Array
I Have Tried the same approach on Swift below are the code snippet
[Contents.swift](https://developer.apple.com/forums/content/attachment/60fab4f2-1496-4003-9f37-c195de95e94a)
Post not yet marked as solved
Hi
I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value.
I have used extension as follwoing
To generate string to Symetric key
extension SymmetricKey {
init(string keyString: String, size: SymmetricKeySize = .bits256) throws {
guard var keyData = keyString.data(using: .utf8) else {
print("Could not create base64 encoded Data from String.")
throw CryptoKitError.incorrectParameterSize
}
let keySizeBytes = size.bitCount / 8
keyData = keyData.subdata(in: 0..<keySizeBytes)
guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize }
self.init(data: keyData)
} }
Encryption & Decryption code snipet:
func aesgcmEncryptDecrypt() {
let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY"
var key : SymmetricKey = SymmetricKey(size: .bits256)
do{
key = try SymmetricKey(string: str)
}catch{
}
let plain = "HOW ARE YOU?"
let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!)
let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")!
// Encrypt
let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key,
nonce: nonce, authenticating: tag)
// Decrypt
let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!)
let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key,
authenticating: tag)
Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n")
Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n")
Swift.print("Nonce:\n(nonce.withUnsafeBytes {
Data(Array($0)).base64EncodedString() })\n")
Swift.print("Tag:\n(tag.base64EncodedString())\n")
Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n")
}
Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C.
Post not yet marked as solved
I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value.
I have used extension as follwoing
To generate string to Symetric key
extension SymmetricKey {
init(string keyString: String, size: SymmetricKeySize = .bits256) throws {
guard var keyData = keyString.data(using: .utf8) else {
print("Could not create base64 encoded Data from String.")
throw CryptoKitError.incorrectParameterSize
}
let keySizeBytes = size.bitCount / 8
keyData = keyData.subdata(in: 0..<keySizeBytes)
guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize }
self.init(data: keyData)
} }
Encryption & Decryption code snipet:
func aesgcmEncryptDecrypt() {
let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY"
var key : SymmetricKey = SymmetricKey(size: .bits256)
do{
key = try SymmetricKey(string: str)
}catch{
}
let plain = "HOW ARE YOU?"
let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!)
let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")!
// Encrypt
let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key,
nonce: nonce, authenticating: tag)
// Decrypt
let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!)
let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key,
authenticating: tag)
Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n")
Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n")
Swift.print("Nonce:\n(nonce.withUnsafeBytes {
Data(Array($0)).base64EncodedString() })\n")
Swift.print("Tag:\n(tag.base64EncodedString())\n")
Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n")
}
Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C. Using the AesGcm class
Post not yet marked as solved
I'm having a problem accessing a site where I need to use a certificate for identification, where I used some examples to type the pin but none works, I checked an instruction to register a module in firefox as a security device but it doesn't work, it worked on macos 10.15 , but now when adding the security device , the slot does not appear in Firefox.
Tank's
Post not yet marked as solved
I am trying to add my smart card PIV cert to ssh-agent.
In macOS 10.15 Catalina, it was as simple as:
ssh-add -s /usr/lib/ssh-keychain.dylib
But in macOS 11.1 Big Sur, the ssh-agent debug output says:
failed PKCS#11 add of "/usr/lib/ssh-keychain.dylib": realpath: No such file or directory
I am aware that macOS 11 caches system libraries ... but I believe that /usr/lib/ssh-keychain.dylib is in the cache.
Any help would be greatly appreciated!