Swift에서 RSA 암호화 해보기

JiSNG·2023년 7월 27일
0
post-custom-banner

RSA

publicKey와 privateKey가 존재
pulicKey로 암호화, privateKey로 복호화

import Security

예제 코드

1. String to Data

let secreatData = "SECREAT".data(using: .utf8)

2. publicKey / privateKey 만들기 (SecKey 만들기)

(A) 앱에서 직접 만들기

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)

(B) publickKey, privateKey를 String으로 받았을 때 만들기

  • String to Data
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)
  • Public SecKey
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
)
  • Private SecKey
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
)

3. 암호화 / 복호화

  • 암호화
    (RSA 암호화는 무작위성을 강화하기 위해 Padding Scheme과 함께 사용되는데, 이로 인해 매번 다른 암호문(Ciphertext)이 생성된다)
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

profile
JiSNG+iOS
post-custom-banner

0개의 댓글