1

我一直在尝试使用 Diffie Hellman 密钥交换和椭圆曲线加密快速加密和解密字符串。

以下是我遵循的代码。

SWIFT代码 :

 let attributes: [String: Any] = [kSecAttrKeySizeInBits as String: 256,
                                     kSecAttrKeyType as String: kSecAttrKeyTypeEC,
                                     kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: false]]
 var error: Unmanaged<CFError>?
 if #available(iOS 10.0, *) {
 **// Step 1:  Generating the Public & Private Key**
        guard let privateKey1 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return false}

        let publicKey1 = SecKeyCopyPublicKey(privateKey1)
        guard let privateKey2 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return false}

        let publicKey2 = SecKeyCopyPublicKey(privateKey2)

        let dict: [String: Any] = [:]
 **// Step 2:  Generating Shared Key**   
        guard let shared1 = SecKeyCopyKeyExchangeResult(privateKey1, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey2!, dict as CFDictionary, &error) else {return false}

**// Step 3:  Encrypt string using Sharedkey**
        let options: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeEC,
                                      kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
                                      kSecAttrKeySizeInBits as String : 256]
        // Stuck from this line on
        guard let key = SecKeyCreateWithData(shared1 ,
                                             options as CFDictionary,
                                             &error) else {return false}
        print(key)


        let str = "Hello"
        let byteStr: [UInt8] = Array(str.utf8)
        let cfData = CFDataCreate(nil, byteStr, byteStr.count)


        guard let encrypted = SecKeyCreateEncryptedData(publicKey1!,
                                                        SecKeyAlgorithm.ecdsaSignatureDigestX962SHA256,
                                                        cfData!,
                                                        &error) else {return false}
        print(encrypted)

    } else {
        print("unsupported")
    }

JAVA代码:

public static Map<String, Object> ecEncrypt(String deviceData, String serverPubKey, String dsTranID)
throws DataEncryptionException {
provider = new BouncyCastleProvider();
HashMap<String, Object> result = null;
JWEObject jweObject = null;
JWK jwk = null;
SecretKey Z = null;
JWEHeader header = null;
ECPublicKey ecpubkey = null;
byte[] byte_pubkey = null;

try {

result = new HashMap<String, Object>();
/*
 * Generate Ephemeral keypair for SDk which constitute Public and
 * Private key of SDK
 */
STEP 1:
sdkKeyPair = Crypto.generateEphemeralKeyPair();

/*
 * Compute Secrete Key Z from SDKs Private Key(pSDK),DS Public
 * key(serverPubKey) and DS ID
 */
//converting string to Bytes
STEP 2:
byte_pubkey = Base64.decode(serverPubKey, android.util.Base64.DEFAULT);

//converting it back to EC public key
STEP 3:
KeyFactory factory = KeyFactory.getInstance("ECDSA", provider);
ecpubkey = (ECPublicKey) factory.generatePublic(new X509EncodedKeySpec(byte_pubkey));
System.out.println("FINAL OUTPUT" + ecpubkey);

STEP 4:
Z = Crypto.generateECDHSecret(ecpubkey,
(ECPrivateKey) sdkKeyPair.getPrivate(), dsTranID,
"A128CBC_HS256");

System.out.println("****Secrete key Z for SDK Computed succesfully *****");
/*
 * Build JWK to construct header
 */
STEP 5:
jwk = new ECKey.Builder(Curve.P_256,
(ECPublicKey) sdkKeyPair.getPublic()).build();

STEP 6:
header = new JWEHeader.Builder(JWEAlgorithm.ECDH_ES,
EncryptionMethod.A128CBC_HS256).ephemeralPublicKey(
ECKey.parse(jwk.toJSONString())).build();

System.out.println("****Header for SDK Computed  succesfully*****");

/*
 * Add Header and payload before encrypting payload using secret key
 * Z
 */

STEP 7:
jweObject = new JWEObject(header, new Payload(deviceData));
jweObject.encrypt(new DirectEncrypter(Z));
/*
 * serialize JWEobject which contains
 * [header-base64url].[encryptedKey
 * -base64url].[iv-base64url].[cipherText
 * -base64url].[authTag-base64url]
 */
System.out
.println("****Payload of SDK encrypted succesfully *****");

return result;
} catch (Exception e) {
e.printStackTrace();
throw new DataEncryptionException();
} finally {
sdkKeyPair = null;
jweObject = null;
jwk = null;
Z = null;
header = null;
}
}

我也包含了 Java 代码。我必须在 Swift 中做同样的事情。如何使用共享密钥(Shared1)对字符串进行 EC 加密?我需要做第 3 步。有人请帮忙吗?

4

1 回答 1

1

首先,您正在尝试实施 ECIES。如果您想查找有关该方案的信息,了解实际名称很重要。

因此,假设密钥对 1 来自密文的发送者,而密钥对 2 则来自密文的接收者。在这种情况下,密钥对 1 应该是临时的(当场创建,绑定到一条加密消息),而密钥对 2 是静态的(预先创建并保留)。此外,公钥 2 被信任为来自接收方。从您的简化代码中,这一切都不清楚,在您的代码中,您仍然可以切换发送者和接收者。

因此,使用接收者的公钥 (2),发送者可以使用他们的私钥创建一个共享秘密,shared1在您的代码中调用。您现在可以使用shared1来执行数据的对称加密。然后,您只需将发送者的临时公钥和密文发送给接收者。接收方使用发送方的公钥 (1) 和他们的静态私钥 (2) 创建shared2. 这与解密数据相同,shared1因此可以用作解密数据的密钥。

就是这样,除了要注意的是,由于发送者的私钥 (1) 与数据相关联,因此一旦shared1计算就不再需要它,甚至在消息加密之前就可能被丢弃。


如果您阅读了上面的内容,那么您会发现在一种方法中拥有所有这些并不是一个好主意:

  1. 创建接收者的静态密钥对;
  2. 将接收方的公钥发送给发送方,并确保发送方可以相信公钥来自接收方(例如使用证书基础设施);

现在进行加密和发送:

  1. 创建发送方的密钥对;
  2. 导出对称密钥;
  3. 扔掉私钥;
  4. 加密数据;
  5. 发送公钥和数据;

对于接收:

  1. 使用私钥导出对称密钥;
  2. 解密数据。

就是这样。您可能希望在代码中明确说明这些步骤。

于 2019-09-25T00:56:25.333 回答