Skip to content

Instantly share code, notes, and snippets.

@MarcoEidinger
Created April 6, 2023 19:03
Show Gist options
  • Save MarcoEidinger/7a1a0affdbdf62dc2482d6a44d3748e6 to your computer and use it in GitHub Desktop.
Save MarcoEidinger/7a1a0affdbdf62dc2482d6a44d3748e6 to your computer and use it in GitHub Desktop.
Using Security.framework on iOS / macOS for cryptographic algorithm RSA/ECB/PKCS1Padding
import Foundation
import Security
// Function to generate RSA key pair
func generateRSAKeyPair() throws -> (privateKey: SecKey, publicKey: SecKey) {
let attributes: [String: Any] = [
kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits as String: 2048
]
var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error?.takeRetainedValue() ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecInternalError), userInfo: nil)
}
guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
throw error?.takeRetainedValue() ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecInternalError), userInfo: nil)
}
return (privateKey, publicKey)
}
// Function to encrypt data using RSA/ECB/PKCS1Padding
func rsaEncrypt(data: Data, publicKey: SecKey) throws -> Data {
var error: Unmanaged<CFError>?
guard let encryptedData = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? else {
throw error?.takeRetainedValue() ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecInternalError), userInfo: nil)
}
return encryptedData
}
// Function to decrypt data using RSA/ECB/PKCS1Padding
func rsaDecrypt(data: Data, privateKey: SecKey) throws -> Data {
var error: Unmanaged<CFError>?
guard let decryptedData = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? else {
throw error?.takeRetainedValue() ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecInternalError), userInfo: nil)
}
return decryptedData
}
do {
let message = "Hello, World!".data(using: .utf8)!
let (privateKey, publicKey) = try generateRSAKeyPair()
let encryptedData = try rsaEncrypt(data: message, publicKey: publicKey)
let decryptedData = try rsaDecrypt(data: encryptedData, privateKey: privateKey)
let encryptedMessage = String(data: decryptedData, encoding: .utf8) ?? ""
print("Original message: \(message)")
print("Encrypted message: \(encryptedData.base64EncodedString())")
print("Decrypted message: \(encryptedMessage)")
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment