11

有没有在 iOS 中使用 ECC 的示例?

我注意到 Apple Developer Documents 中的 kSecAttrKeyTypeEC ,但我不能将它用于通用密钥对。

下面的代码是从示例 CryptoExercise 修改的

// Container dictionaries.
NSMutableDictionary * privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * keyPairAttr = [[NSMutableDictionary alloc] init];

// Set top level dictionary for the keypair.
[keyPairAttr setObject:(id)kSecAttrKeyTypeEC forKey:(id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithUnsignedInteger:keySize] forKey:(id)kSecAttrKeySizeInBits];

// Set the private key dictionary.
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.

// Set the public key dictionary.
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.

// Set attributes to top level dictionary.
[keyPairAttr setObject:privateKeyAttr forKey:(id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(id)kSecPublicKeyAttrs];

// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
sanityCheck = SecKeyGeneratePair((CFDictionaryRef)keyPairAttr, &publicKeyRef, &privateKeyRef);
LOGGING_FACILITY( sanityCheck == noErr && publicKeyRef != NULL && privateKeyRef != NULL, @"Something really bad went wrong with generating the key pair." );

sanityCheck 总是返回 -50,这意味着 'errSecParam'。

我真的不知道如何使用它,感谢您阅读本文。

4

2 回答 2

1
NSDictionary *parameters = @{
                             (__bridge id)kSecAttrKeyType: (__bridge id)kSecAttrKeyTypeEC,
                             (__bridge id)kSecAttrKeySizeInBits: @256,
                             (__bridge id)kSecPrivateKeyAttrs: @{
                                     (__bridge id)kSecAttrIsPermanent: @YES,
                                     (__bridge id)kSecAttrApplicationTag: [@"my.key.tag" dataUsingEncoding:NSUTF8StringEncoding],
                                     },
                             (__bridge id)kSecPublicKeyAttrs: @{
                                     (__bridge id)kSecAttrIsPermanent: @YES,
                                     (__bridge id)kSecAttrApplicationTag: [@"my.key.pubtag" dataUsingEncoding:NSUTF8StringEncoding],
                                     }
                             };

SecKeyRef publicKey, privateKey;
OSStatus status = SecKeyGeneratePair((__bridge CFDictionaryRef)parameters, &publicKey, &privateKey);

这有效,请仔细检查您的密钥大小参数。

请注意,目前 EC 密钥只能用于签名/验证数据。加密/解密返回errSecUnimplemented = -4.

于 2015-12-08T13:53:17.190 回答
0

CryptoKit 现在在 iOS13+ 中支持 Ed25519

https://developer.apple.com/documentation/cryptokit/curve25519/signing

于 2020-09-10T06:58:25.987 回答