我在node.js中有此代码,它使用Crypto创建密钥。我可以使用Java创建相同的密钥吗?
diffieHellmanConfig': {
'group': 'modp14',
'encoding': 'base64'
}
const clientDHInstance = crypto.getDiffieHellman(config.userCardCrypto.diffieHellmanConfig.group);
clientDHInstance.generateKeys();
const clientPublicKey = clientDHInstance.getPublicKey(config.userCardCrypto.diffieHellmanConfig.encoding);
我尝试使用
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
keyGen.initialize(2048);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
byte[] encoded = publicKey.getEncoded();
String s = Base64.getEncoder().encodeToString(encoded);
System.out.println(s);
但是键是错误的
节点键为t2EBMu8wCShfu8Dm45i9nNQ + TXyG5Oz1 / izjTwRD0dchUK2400R9cP + NjLlOqjLstXnTbG5 / aa0WaCoP187J90piiebGOjZUlF / BU / xkkrYncQHAJ403J8 + R2V5eHYCSQXbS6CSO7x + eEhNz8QTMgwkOR9w1R3gvbibaqL7qyQARPFak6 + VIKFLUakSzMvdAIjLNPu2dva1QdJixid + EYiZE / DxA7lqpje74I7wynZj7kmUZXtiIWu46suf5CaVONtjEVZilvErJNpVlPX5TXoMVNrWkl9g5Aa6moXg4K0M6Gc4taumnDr9gh4PEuw + / QVauEld27 / 5TQlfAlalvzg ==
Java键是MIICKTCCARsGCSqGSIb3DQEDATCCAQwCggEBAP ////////// YQ / aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu + pjsTmyJRSgh5jjQE3e + VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL / 1y29Aa37e44a /塔伊兹+ lrp8kEXxLH + ZJKGZR7ORbPcIAfLihY78FmNpINhxV05ppFj + O / STPX4NlXSPco62WHGLzViCFUrue1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO + OedywYDoYDmyeDouwHoo + 1xV3wb0xSyd4ry / aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKrKpo ////////// 8CAQICAgQAA4IBBgACggEBAI + NYSvMh0bfh1ptt62vHEHENz6ZAYvnnrwmRhQRdYMBZiqu60AvJ4F6qL99EfesxvH3n8YaC + cG7bKAqkw74rRHJXkMF5xOy / kpTVvmQGAPjvTi5o4BJtHLOBgiwFKy7CYFKFksCJzkqNdAuPri / mfMm6GNG5MBYtQIurWkgOnnrVl3Nra2CSVUixQ5zCANOSnnNYNFPanr01bI6KZXsiRZRqfA4oYxBPySy4Sp1dx2IvSQe8EjNWTicTQQj / HP7hl1yf3uiYlM4h3dMbmfqv6Y10hW8kvoD88 / mh09pdz + HxxDz + mVSMe + 3 + N7VIYUEGRHhrAvjbXmwh5zyCMIJiI =
在您的示例密钥中,由节点创建的DH密钥的大小是预期的2048
位,但是,Java DH密钥正在压入〜4k
位。
因此,我认为在Java上初始化DH密钥的方式存在问题。
查看您的代码,我认为提供整数文字以指定DH循环组的大小是不合适的。
而不是像这样尝试实例化Java DH密钥:
final DHParameterSpec keySpec=new DHParameterSpec(DH_MODULUS,DH_BASE);
final KeyPair keyPair;
try {
KeyPairGenerator keyGen=KeyPairGenerator.getInstance("DH");
keyGen.initialize(keySpec);
keyPair=keyGen.generateKeyPair();
keyAgreement=KeyAgreement.getInstance("DH");
keyAgreement.init(keyPair.getPrivate());
}
您需要在Java中创建一个DHParameterSpec
对象,以提供模数和基数,类似于node中提供的值。