iOS- swift-为secp224k1曲线生成密钥对(ECDH)

问题描述 投票:1回答:1

我一直在尝试为iOS中的secp224k1曲线生成公钥和私钥。我们正在使用ECDH方法在移动端和后端之间进行api握手。在Java中,使用以下代码即可完成。

public static KeyPair getECKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp224k1");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", "SC");
    kpg.initialize(ecSpec);
    return kpg.generateKeyPair();
}

是否可以快速生成具有特定曲线(secp224k1)类型的关键点?我尝试使用苹果提供的EC算法通过以下代码进行握手。

    //Generates public and private key with EC algorithm
public static func getKey() -> [String: SecKey]? {

    let attributes: [String: Any] =
        [kSecAttrKeySizeInBits as String: 256,
         kSecAttrKeyType as String: kSecAttrKeyTypeEC,
         kSecPrivateKeyAttrs as String:
            [kSecAttrIsPermanent as String:    false]
    ]
    var error: Unmanaged<CFError>?
        guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
            let err = error!.takeRetainedValue() as Error
            print(err.localizedDescription)
            return nil
        }
        guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
            print("Error occured while creating public key")
            return nil
        }
        return ["publicKey": publicKey, "privateKey": privateKey]
}

当我发送通过上述方法生成的公共密钥时,我从服务器收到一条错误消息:

"error":"java.security.InvalidKeyException: ECDH key agreement requires ECPublicKey for doPhase","exception":"InvalidAuthException"

我尝试过VirgilCrypto来迅速解决问题。但是它在我需要的库中没有特定的曲线类型。它仅支持secp256r1。另外,我尝试但未解决的以下帖子的答案。

Elliptic Curve Diffie Hellman in ios/swift

任何建议或帮助都很好,谢谢。

ios swift cryptography ecdh
1个回答
0
投票

iOS不支持Koblitz 224位曲线。一种解决方案可能是使用其他曲线类型或具有secp224k1支持的第三方库。

根据您的评论可以得出结论,secp224k1曲线类型是必需的。

可能使用的第三方库是Virgil Crypto,可通过github https://github.com/VirgilSecurity/virgil-crypto获得。这是一个C ++库。 (Virgil Security还提供了一个称为virgil-crypto-x的Swift包装库,但在当前版本中该库不再支持secp224k1)。

C ++库可以通过创建具有定义接口的Objective-C ++包装器而在Swift中间接使用。

Build VSCCrypto.framework

在命令行上输入:

git clone https://github.com/VirgilSecurity/virgil-crypto
cd virgil-crypto
utils/build.sh --target=ios

这将构建iOS框架。

将VSCCrypto.framework添加到Xcode项目

  • 在项目导航器中选择根节点
  • 在Xcode中创建“新组”
  • 将其命名为“框架”
  • 在Finder中将vircc-crypto / build / ios / lib文件夹中的VSCCrypto.framework拖放到'Frameworks'组中

  • 在右侧的XCode中,“ Embedded Binaries”点击加号

  • 选择VSCCrypto.framework

Objective-C ++包装器

  • 创建ECDHCrypto Objective-C文件
  • 当询问'是否要配置Objective-C桥接头'时,请点击'创建桥接头'
  • 在项目导航器中,将文件后缀从.m更改为.mm(以允许存在C ++代码)
  • #import "ECDHCrypto.h"添加到桥接头中

ECDHCrypto.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface ECDHCrypto : NSObject

@property(nonatomic, strong) NSString *ownPrivateKey;
@property(nonatomic, strong) NSString *ownPublicKey;

- (void)generateKeyPair;
- (NSString *)shared:(NSString *)otherPublicKey;

@end

NS_ASSUME_NONNULL_END

ECDHCrypto.mm

#import "ECDHCrypto.h"
#import <VSCCrypto/VirgilCrypto.h>

using virgil::crypto::VirgilKeyPair;
using virgil::crypto::VirgilByteArray;
using virgil::crypto::VirgilCipherBase;
using virgil::crypto::str2bytes;
using virgil::crypto::bytes2str;
using virgil::crypto::bytes2hex;


@implementation ECDHCrypto

- (void)generateKeyPair {
    VirgilKeyPair keyPair = VirgilKeyPair::generate(VirgilKeyPair::Type::EC_SECP224K1);

    VirgilByteArray ownPublicKeyBates = keyPair.publicKey();
    self.ownPublicKey = [NSString stringWithCString:bytes2str(ownPublicKeyBates).c_str()
                                           encoding:[NSString defaultCStringEncoding]];

    VirgilByteArray ownPrivateKeyBytes = keyPair.privateKey();
    self.ownPrivateKey = [NSString stringWithCString:bytes2str(ownPrivateKeyBytes).c_str()
                                            encoding:[NSString defaultCStringEncoding]];
}

- (NSString *)shared:(NSString *)otherPublicKey {
    NSAssert(self.ownPrivateKey, @"private key must be set, e.g. use generateKeyPair");
    std::string otherPKString([otherPublicKey cStringUsingEncoding:NSASCIIStringEncoding]);
    VirgilByteArray pubKey = str2bytes(otherPKString);

    std::string ownPrivateKeyString([self.ownPrivateKey cStringUsingEncoding:NSASCIIStringEncoding]);
    VirgilByteArray ownPrivateKeyBytes = str2bytes(ownPrivateKeyString);

    VirgilByteArray shared_ba = VirgilCipherBase::computeShared(pubKey, ownPrivateKeyBytes);

    std::string hex = bytes2hex(shared_ba);
    NSString *shared = [NSString stringWithCString:hex.c_str()
                                          encoding:[NSString defaultCStringEncoding]];

    return shared;
}

@end

在Swift中的用法

let otherPK = """
    -----BEGIN PUBLIC KEY-----
    ME4wEAYHKoZIzj0CAQYFK4EEACADOgAEgeW/foqxCDOd1y6lnXONkRThS6xhjLHP
    SEXs7jHSpoaPQH4vArcGmIb1cAZcepEh7WDQxCyfQXg=
    -----END PUBLIC KEY-----
    """

let ecdhCrypto = ECDHCrypto()
ecdhCrypto.generateKeyPair();
print("ecdhCrypto.ownPublicKey: \n" + ecdhCrypto.ownPublicKey);
print("shared secret: " + ecdhCrypto.shared(otherPK));

使用Java对方测试

要测试密钥交换是否成功,可以执行以下测试:

  1. 在Java中,将生成secp224k1密钥对,并将公共密钥输出到控制台。

  2. 使用复制/粘贴将公钥复制到iOS应用程序的Swift代码中。然后,该应用程序会生成一个密钥对,并将其自己的公共密钥以及计算出的共享密钥写入控制台。然后将iOS公钥作为输入插入Java程序(显示为​​绿色)。

  3. 最后,可以比较iOS应用程序和Java程序的共享密钥。此处是相同的,因此密钥交换成功。

在上部,您会看到带有iOS源代码的Xcode,在下部,您会看到Java程序的输出:

same shared secret

© www.soinside.com 2019 - 2024. All rights reserved.