Help us understand the problem. What is going on with this article?

SecKeyGeneratePairs in Swift

More than 5 years have passed since last update.

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 で動くはずです.

xshirade
学んだことを他の人に理解してもらえる記事にすることが,自分の力になると思って書き出しています.内容の間違いやコードの改善点などありましたらコメントを頂ければ助かります.
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away