使用现有的外部 public 密钥从 ECDH 派生共享密钥

Derive Shared Secret From ECDH with existing foreign public key

我正在将一个方法从 nodeSJ 转换为 Java,但我无法让它工作。我一直在尝试计算派生的共享秘密。

希望有人能发现我在将 nodeJS 移植到 Java 时做错了什么。

NodeJS 代码:

 //the public_key param here is from a different device. 
 sign: function(public_key)
    {
        //dummy values 
        var PRE_SALT_VALUE = 'f0f0f0f0f0';
        var POST_SALT_VALUE = '0101010101';

        const crypto = require('crypto');
        var sha512 = crypto.createHash("sha512");

        var EC = require('elliptic').ec;
        var ec = new EC('p256');

        // Generate keys
        var key1 = ec.genKeyPair(); //key1 is gen before pub key
        var key2 = ec.keyFromPublic(public_key, 'hex') //pub key gen from saved cert

        var derived_secret = key1.derive(key2.getPublic()); 
        var derived_secret = Buffer.from(derived_secret.toString(16), 'hex')

        var public_key_client = key1.getPublic('hex') 

        var pre_salt = Buffer.from(PRE_SALT_VALUE, 'hex')
        var post_salt = Buffer.from(POST_SALT_VALUE, 'hex')

        derived_secret = Buffer.from(pre_salt.toString('hex')+derived_secret.toString('hex')+post_salt.toString('hex'), 'hex') // finalyze shared secret 
        // Hash shared secret
        var sha = sha512.update(derived_secret);
        derived_secret = sha.digest();

        return {
            public_key: public_key_client.toString('hex').slice(2), //anyone know why we drop the first byte here?
            secret: derived_secret.toString('hex')  
        }
    }

进行中Java代码:

        //load cert from pem string (passed in from file), foreign cert
        ByteArrayInputStream input = new ByteArrayInputStream(pem);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(input);
        X509Certificate x509Cert = (X509Certificate) cert;

        // get pub key from cert
        PublicKey publicKeyForSignature = x509Cert.getPublicKey();

        // Generate ephemeral ECDH keypair KEY1
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(256);
        KeyPair kp1 = kpg.generateKeyPair();
        byte[] ourPk = kp1.getPublic().getEncoded(); //use this later

        //load KEY2 from others public key
        KeyFactory kf = KeyFactory.getInstance("EC");
        X509EncodedKeySpec pkSpec = new X509EncodedKeySpec(publicKeyForSignature.getEncoded());
        PublicKey otherPublicKey = kf.generatePublic(pkSpec);

        // Perform key agreement
        KeyAgreement ka = KeyAgreement.getInstance("ECDH");
        ka.init(kp1.getPrivate());
        ka.doPhase(otherPublicKey, true);

        // Read shared secret
        byte[] sharedSecret = ka.generateSecret();

        // Derive a key from the shared secret and both salt keys
        MessageDigest hash = MessageDigest.getInstance("SHA-512");
        hash.update(Util.PRE_SALT_VALUE);
        hash.update(sharedSecret);
        hash.update(Util.POST_SALT_VALUE);

        byte[] derivedKey = hash.digest();

        ... etc, derivedKey = secret returned in JS method, ourPk = public_key returned in JS method. 

我注意到的一件事是从 nodejs 生成的 public/private 键与 java 的大小不同?节点中的 65 个字节和 java 中的 91 个字节。不知道为什么会这样。

这里有什么突出的问题?

谢谢

编辑:

所以基本上,我只需要知道如何在 Java

中执行此操作
 var EC = require('elliptic').ec;
 var ec = new EC('p256');
 // Generate keys
 var key1 = ec.genKeyPair();
 var key2 = ec.keyFromPublic(public_key, 'hex') //pub key from foreign device     
 var derived_secret = key1.derive(key2.getPublic());  

就像评论中已经提到的那样,为了能够在 Java 和 Node 之间使用共享密钥,您需要相应地转换密钥。

对于来自这两个很好的 Whosebug 答案的关键转换代码,可以使用:

测试

要获得完整的测试用例,可以编写一个 Java 程序生成 DER public 密钥,将其转换为未压缩的 EC 密钥(65 字节)并将其输出到控制台.然后它从控制台读取另一个 PK,将其转换为 public 密钥,并打印出共享密钥。

Node 代码使用来自 Java 程序的 PK,确定共享秘密和 public 密钥。然后可以通过 copy/paste 将此 public 密钥传递给 Java 程序,该程序仍在等待输入。

Java程序最终确定共享密钥并打印出来。

如果两个共享密钥具有相同的值,我们就知道它有效。

Java

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.ECPointUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;

import javax.crypto.KeyAgreement;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.*;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;

public class Main {

    public static byte[] ecKeyBytesFromDERKey(byte[] ourPk) {
        ASN1Sequence sequence = DERSequence.getInstance(ourPk);
        DERBitString subjectPublicKey = (DERBitString) sequence.getObjectAt(1);
        return subjectPublicKey.getBytes();
    }

    private static PublicKey publicKeyFromEC(byte[] ecKeyByteArray) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory kf = KeyFactory.getInstance("EC", "BC");
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256r1");
        ECNamedCurveSpec params = new ECNamedCurveSpec("secp256r1", spec.getCurve(), spec.getG(), spec.getN());
        ECPoint publicPoint = ECPointUtil.decodePoint(params.getCurve(), ecKeyByteArray);
        ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(publicPoint, params);
        return kf.generatePublic(pubKeySpec);
    }

    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");
        kpg.initialize(256);
        KeyPair kp = kpg.generateKeyPair();
        byte[] ourPk = kp.getPublic().getEncoded();
        byte[] ecPublicKey = ecKeyBytesFromDERKey(ourPk);
        System.out.println("our ec public key (65 bytes): " + Hex.encodeHexString(ecPublicKey));

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("other public key (65 bytes): ");
        String input = br.readLine();
        br.close();

        byte[] otherPk = Hex.decodeHex(input);
        PublicKey otherPublicKey = publicKeyFromEC(otherPk);

        KeyAgreement ka = KeyAgreement.getInstance("ECDH");
        ka.init(kp.getPrivate());
        ka.doPhase(otherPublicKey, true);

        byte[] sharedSecret = ka.generateSecret();
        System.out.println("Shared secret: " + Hex.encodeHexString(sharedSecret));
    }
}

节点

您的节点程序需要进行一项更改:

在行

public_key: public_key_client.toString('hex').slice(2), //anyone know why we drop the first byte here?

需要删除的 .slice(2):

public_key: public_key_client.toString('hex'),

因为它删除了指示它是未压缩密钥所需的第一个字节(十六进制 04)。

因此,只需使用 Java 程序中的 public 键(每个 运行 都会有所不同),节点部分可能如下所示:

var publickey = Buffer.from("<public key from java>", 'hex');
var derived = sign(publickey);
console.log(derived);

测试

在上部区域您可以看到 Java 程序,在下部区域可以看到 Node 程序的输出。共享密钥相同。