前提・実現したいこと
####実現したいこと
Swiftで、任意の文字列を公開鍵で暗号化するプログラムを作成しています。
暗号鍵の作成までは成功しており、最後に文字列を暗号化する部分でエラーが発生しています。
なおビルドには成功しており、関数を実行する際にエラーで処理が止まってしまいます。
####動作環境
- Swift 4.2
- xcode 10.0
発生している問題・エラーメッセージ
関数SecKeyCreateEncryptedData
の実行中に、エラーで処理が停止する。
デバックコンソールに、エラーメッセージは表示されず、
79行目: plainText as! CFData,
の横に、以下のメッセージが表示される。
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x100f512c8)
該当のソースコード
swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 @IBAction func createEncryptedData(_ sender: Any) { 6 do { 7 try createEncryptedData() 8 } catch { 9 print("error") 10 } 11 } 12 13 func createEncryptedData() throws { 14 let idfv = UIDevice.current.identifierForVendor?.uuidString 15 print("IDFV: (idfv!)") 16 17 let tag = "com.example.keys.mykey".data(using: .utf8)! 18 let attributes: [String: Any] = [ 19 kSecAttrKeyType as String: kSecAttrKeyTypeRSA, 20 kSecAttrKeySizeInBits as String: 2048, 21 kSecPrivateKeyAttrs as String: [ 22 kSecAttrIsPermanent as String: true, 23 kSecAttrApplicationTag as String: tag] 24 ] 25 26 var error: Unmanaged<CFError>? 27 28 guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { 29 throw error!.takeRetainedValue() as Error 30 } 31 let publicKey = SecKeyCopyPublicKey(privateKey) 32 33 print("privatekey: (privateKey)") 34 print("publickey : (publicKey! as Any)") 35 36 let algorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA512 37 38 guard SecKeyIsAlgorithmSupported(publicKey!, .encrypt, algorithm) else { 39 throw error!.takeRetainedValue() as Error 40 } 41 42 let plainText = idfv 43 print("plaintext: (plainText!)") 44 print(SecKeyGetBlockSize(publicKey!)) 45 print(plainText!.count) 46 47 guard (plainText!.count < (SecKeyGetBlockSize(publicKey!)-130)) else { 48 throw error!.takeRetainedValue() as Error 49 } 50 51 guard let cipherText = SecKeyCreateEncryptedData(publicKey!, 52 algorithm, 53 plainText as! CFData, 54 &error) as Data? else { 55 throw error!.takeRetainedValue() as Error 56 } 57 58 print("cipherText: (cipherText)") 59 60 } 61 62 override func viewDidLoad() { 63 super.viewDidLoad() 64 // Do any additional setup after loading the view, typically from a nib. 65 } 66}
試したこと
- 文字列を、IDFVではなく、単純なString型の文字列("Hello,World")に置き換えて関数を実行。
- 定数plainTextを強制アンラップして関数を実行。
plainText as! CFData,
->plainText! as! CFData,
いずれを試しても、エラーは解消されませんでした。
###補足
ちなみに、コードは以下のAppleの公式ドキュメントを参考に作成しています。
- Using Keys for Encryption
ご回答いただけると幸いです。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/16 08:40
2018/10/16 08:47