0

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

希望有人能抓住我做错了将nodeJS移植到Java的事情。

节点代码:

 //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 与 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());  
4

1 回答 1

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 程序最终确定共享密钥并将其打印出来。

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

爪哇

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);

测试

共享秘密测试

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

于 2019-08-05T22:52:34.253 回答