SHA256.hash(data: bytes)
CryptoKit 사용 => keychain 저장 안됨. 수동으로 구현
SymmetricKey(data: data)
SymmetricKey(size: .bits256)
// encrypt
let sealedBox = try AES.GCM.seal(self, using: key)
return sealedBox.ciphertext + sealedBox.nonce
// decrypt
let sealedBox = try AES.GCM.seal(self, using: key)
guard let decryptedData = sealedBox.combined else {
return nil
}
return decryptedData
Security 사용
비대칭 키 는 public 키로 암호화를 하고 private 키로 복호화를 해서 데이터를 보호함
SecKeyCreateRandomKey(query:CFDictionary) 사용하면 됨.
query 필수 값은
optional 값
/// SecKeyCreateRandomKey API를 활용한 rsa 키 만드는 예시
let attributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits: keySize,
kSecPrivateKeyAttrs: [
kSecAttrIsPermanent: true,
kSecAttrApplicationTag: tag
]
]
var error: Unmanaged<CFError>?
guard let keyPair = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
// encrypt 15 이상 => SecKeyCreateEncryptedData
var error: Unmanaged<CFError>?
guard let cipherText = SecKeyCreateEncryptedData(publicKey,
algorithm,
plainText as CFData,
&error) as Data? else {
throw error!.takeRetainedValue() as Error
}
// encrypt 15 미만 => SecKeyEncrypt
let chunk = data.subdata(in: index..<index+length)
var encryptedChunk = [UInt8](repeating: 0, count: blockSize)
var encryptedLength = encryptedChunk.count
let status = SecKeyEncrypt(publicKey, .PKCS1, chunk.bytes, length, &encryptedChunk, &encryptedLength)
guard status == errSecSuccess else {
debugPrint("\(status)")
hrow RSAError.decryptionFailed
}
// decrypt 15 이상, 미만은 SecKeyDecrypt
var error: Unmanaged<CFError>?
guard let clearText = SecKeyCreateDecryptedData(privateKey,
algorithm,
cipherText as CFData,
&error) as Data? else {
throw error!.takeRetainedValue() as Error
}
참고 Apple Archive
https://developer.apple.com/documentation/applearchive/encrypting_and_decrypting_a_single_file