那里。我在java应用程序和php服务器之间实现Diffie Hellman密钥交换协议。当我从php服务器获取密钥时,我有一些问题,密钥是String格式,我想将它转换为PublicKey执行协议。 代码是下一个:
public static PublicKey getPublicKey(String publicKey) throws Exception {
byte[] byteKey =publicKey.getBytes();
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(byteKey);
KeyFactory keyFact = KeyFactory.getInstance("DH");
PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
DHPublicKey dhPublicKey;
return pubKey;
}
当我运行此功能时,我有这个例外:
Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification
at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DHKeyFactory.java:87)
at java.security.KeyFactory.generatePublic(Unknown Source)
at main2.getPublicKey(main2.java:47)
at main2.main(main2.java:108)
键是一个大整数类型,如:" 2730833911517276610828829348409530515930034154987099616280024338836450623403836102419905982575105923164305996145622906355021487887788144551871008554848191" 我该如何纠正这个问题? 谢谢你的时间
答案 0 :(得分:0)
我已经解决了这个问题,感谢用户3062946。这是代码:
public static PublicKey getPublicKey(BigInteger publicKey, BigInteger p, BigInteger g) throws Exception {
DHPublicKeySpec dhspec=new DHPublicKeySpec(publicKey,p,g);
KeyFactory keyFact = KeyFactory.getInstance("DH");
PublicKey pubKey = keyFact.generatePublic(dhspec);
return pubKey;
}