使用现有的外部公钥从ECDH导出共享秘密

时间:2019-07-28 07:34:05

标签: java node.js public-key-encryption ecdh

我将一个方法从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 vs java生成的公钥/私钥大小不同?节点中65字节,Java中91字节。不知道为什么会这样。

在这里什么地方出了错?

感谢

1 个答案:

答案 0 :(得分:1)

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

对于这两个优良的stackoverflow答案中的密钥转换代码,可以使用:

https://stackoverflow.com/a/57209308/2331445

https://stackoverflow.com/a/36033552

测试

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

Node代码使用Java程序中的PK,确定共享密钥和公共密钥。然后可以通过仍在等待输入的复制/粘贴将该公钥传递给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程序中的公钥(每次运行都会有所不同),Node部分可能看起来像这样:

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

测试

shared secret test

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