SecKeyGeneratePair in Swift
Swiftで公開鍵と暗号鍵を作成してみました.
Crypto.swift
Crypto.swift
import Foundation
import CoreFoundation
import Security
class Crypto {
func test() {
// generating key pair
let keyPair: (publicKey: SecKey?, privateKey: SecKey?) = generateKeyPair()
// calculate blocksize
let blockSize: Int = SecKeyGetBlockSize(keyPair.publicKey!)
// preparing for encryption
let plainText: String = "sample text to be encrypted and decrypted"
let plainTextData: [UInt8] = [UInt8](plainText.utf8)
let plainTextDataLength: Int = plainText.characters.count
var encryptedData: [UInt8] = [UInt8](count: Int(blockSize), repeatedValue: 0)
var encryptedDataLength: Int = blockSize
// encrypting
let encryptOsStatus: OSStatus = SecKeyEncrypt(keyPair.publicKey!, SecPadding.PKCS1, plainTextData, plainTextDataLength, &encryptedData, &encryptedDataLength)
if encryptOsStatus != noErr {
print("Encryption Error")
return;
}
// preparing for decryption
var decryptedData: [UInt8] = [UInt8](count: Int(blockSize), repeatedValue: 0)
var decryptedDataLength: Int = blockSize
// decrypting
let decryptOsStatus: OSStatus = SecKeyDecrypt(keyPair.privateKey!, SecPadding.PKCS1, encryptedData, encryptedDataLength, &decryptedData, &decryptedDataLength)
if decryptOsStatus != noErr {
print("Decryption Error")
return;
}
// checking
let text: NSString = NSString(bytes: &decryptedData, length: decryptedDataLength, encoding: NSUTF8StringEncoding)!
if text.compare(plainText) == NSComparisonResult.OrderedSame {
print("success")
} else {
print("failure")
}
}
func generateKeyPair () -> (publicKey: SecKey?, privateKey: SecKey?) {
let parameters: [String: AnyObject] = [
kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits as String: 2048
]
var publicKey: SecKey?
var privateKey: SecKey?
let osStatus: OSStatus = SecKeyGeneratePair(parameters, &publicKey, &privateKey)
switch osStatus {
case noErr:
return (publicKey, privateKey)
default:
// TODO: error handling
return (nil, nil)
}
}
}
let crypto = Crypto()
crypto.test()
使い方
XCode Playground で動くはずです.