publicKey와 privateKey가 존재
pulicKey로 암호화, privateKey로 복호화
let secreatData = "SECREAT".data(using: .utf8)
var error: Unmanaged<CFError>?
let keySize = 2048
let tag = "com.example.keys.mykey".data(using: .utf8)
let attributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits: keySize,
kSecPrivateKeyAttrs: [
kSecAttrIsPermanent: true,
kSecAttrApplicationTag: tag
]
]
let keyPair = SecKeyCreateRandomKey(attributes as CFDictionary, &error)
let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error)
let publicKey = SecKeyCopyPublicKey(privateKey)
var keyString = key
[
"-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----",
"-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----",
"-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----",
"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"
].forEach { keyString = keyString.replacingOccurrences(of: $0, with: "") }
let keyData = Data(base64Encoded: keyString, options: .ignoreUnknownCharacters)
let attributes: [String: Any] = [
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeyClass): kSecAttrKeyClassPublic,
String(kSecAttrKeySizeInBits): keyData.count * 8
]
let publicSecKey = SecKeyCreateWithData(
keyData as CFData,
attributes as CFDictionary,
nil
)
let attributes: [String: Any] = [
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeyClass): kSecAttrKeyClassPrivate,
String(kSecAttrKeySizeInBits): keyData.count * 8
]
let privateSecKey = SecKeyCreateWithData(
privateData as CFData,
attributes as CFDictionary,
nil
)
SecKeyCreateEncryptedData(publickSecKey, .rsaEncryptionPKCS1, secreatData as CFData, nil)
SecKeyCreateDecryptedData(privateSecKey, .rsaEncryptionPKCS1, secreatData as CFData, nil)
참고자료
https://stackoverflow.com/questions/65361511/swift-load-rsa-public-key-from-string-macos
https://cozyu.tistory.com/m/366?category=0