java 中DH的方式实现非对称加密的实例
java中DH的方式实现非对称加密的实例
实现代码:
packagecom.sahadev; importjava.security.KeyFactory; importjava.security.KeyPair; importjava.security.KeyPairGenerator; importjava.security.PrivateKey; importjava.security.PublicKey; importjava.security.spec.X509EncodedKeySpec; importjava.util.Objects; importjavax.crypto.Cipher; importjavax.crypto.KeyAgreement; importjavax.crypto.SecretKey; importjavax.crypto.interfaces.DHPublicKey; importjavax.crypto.spec.DHParameterSpec; importorg.apache.commons.codec.binary.Hex; publicclassDH{ publicstaticStringsrc="Hello,sahadev!"; publicstaticvoidmain(String[]args){ JDKDH(); } publicstaticvoidJDKDH(){ try{ //初始化发送方密钥 KeyPairGeneratorsenderKeyPairGenerator=KeyPairGenerator.getInstance("DH"); senderKeyPairGenerator.initialize(512); KeyPairsenderKeyPair=senderKeyPairGenerator.generateKeyPair(); byte[]senderPublicKey=senderKeyPair.getPublic().getEncoded(); //初始化接收方的密钥 KeyFactoryinstance=KeyFactory.getInstance("DH"); X509EncodedKeySpecx509EncodedKeySpec=newX509EncodedKeySpec(senderPublicKey); PublicKeysendPublicKeyTemp=instance.generatePublic(x509EncodedKeySpec); DHParameterSpecdhParameterSpec=((DHPublicKey)sendPublicKeyTemp).getParams(); KeyPairGeneratorkeyPairGenerator=KeyPairGenerator.getInstance("DH"); keyPairGenerator.initialize(dhParameterSpec); //接收方生成密钥 KeyPairgenerateKeyPair=keyPairGenerator.generateKeyPair(); byte[]receiverPublicKey=generateKeyPair.getPublic().getEncoded(); PrivateKeyreceiverPrivateKey=generateKeyPair.getPrivate(); //接收方密钥构建 KeyAgreementreceiverKeyAgreement=KeyAgreement.getInstance("DH"); receiverKeyAgreement.init(receiverPrivateKey); receiverKeyAgreement.doPhase(senderKeyPair.getPublic(),true); //使用我的密钥和你的公钥生成密钥 SecretKeyreceiverDesKey=receiverKeyAgreement.generateSecret("DES"); //发送方密钥构建 KeyFactorykeyFactory=KeyFactory.getInstance("DH"); X509EncodedKeySpecx509EncodedKeySpec2=newX509EncodedKeySpec(receiverPublicKey); PublicKeyreceiverPublicKeyTemp=keyFactory.generatePublic(x509EncodedKeySpec2); //发送方拿到接收方返回的公钥做本地密钥 KeyAgreementsenderKeyAgreement=KeyAgreement.getInstance("DH"); senderKeyAgreement.init(senderKeyPair.getPrivate()); senderKeyAgreement.doPhase(receiverPublicKeyTemp,true); //使用你的密钥我的公钥进行构建 SecretKeysenderDesKey=senderKeyAgreement.generateSecret("DES"); //判断双方的本地密钥是否相同 if(Objects.equals(receiverDesKey,senderDesKey)){ System.out.println("双方密钥相同"); } //加密 Ciphercipher=Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE,senderDesKey); byte[]result=cipher.doFinal(src.getBytes()); System.out.println("加密结果为:"+Hex.encodeHexString(result)); //解密 cipher.init(Cipher.DECRYPT_MODE,senderDesKey); result=cipher.doFinal(result); System.out.println("解密结果为:"+newString(result)); }catch(Exceptione){ e.printStackTrace(); } } }
附上结果:
双方密钥相同 DES:da1cc13d388423e82a110539414b1ec0 解密结果为:Hello,sahadev!
以上就是DH实现非对称加密的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!