Java加密与安全 (5)

运行结果如下:

Java加密与安全


如果在运行过程中出现: Unsupported secret key algorithm: AES 异常信息,这是由于密钥所用的算法不被支持,这个是由于JDK8 update 161之后,DH的密钥长度至少为512位,但AES算法密钥不能达到这样的长度,长度不一致所以导致报错。
解决办法:将 -Djdk.crypto.KeyAgreement.legacyKDF=true 写入JVM系统变量中。可以在IEDA中的Run - Edit Configurations -> VM options中配置,如下图:

Java加密与安全

  但DH算法不能避免中间人攻击,如果黑客假冒乙和甲交换密钥,同时又假冒甲和乙交换密钥,这样就可以成功地进行工具。DH算法是一种安全的密钥交换协议,通信双方通过不安全的信道协商密钥,然后进行对称加密传输。

非对称加密算法

非对称加密就是加密和解密使用不同的密钥,非对称加密的典型算法就是RSA算法,

加密:用对方的公钥加密,然后发送给对方 encrypt(publicKeyB,message) -> encrypted

解密:对方用自己私钥解密 decrypt(privateKeyB,encrypted) -> message

import javax.crypto.Cipher; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class RSAKeyPair { //私钥 private PrivateKey sk; //公钥 private PublicKey pk; //生成公钥/私钥对 public RSAKeyPair() throws GeneralSecurityException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair kp = keyGen.generateKeyPair(); this.sk = kp.getPrivate(); this.pk = kp.getPublic(); } //从已保存的字节中(例如读取文件)恢复公钥/密钥 public RSAKeyPair(byte[] pk, byte[] sk) throws GeneralSecurityException { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pk); this.pk = keyFactory.generatePublic(keySpec); PKCS8EncodedKeySpec skSpec = new PKCS8EncodedKeySpec(sk); this.sk = keyFactory.generatePrivate(skSpec); } //把私钥到处为字节 public byte[] getPrivateKey(){ return this.sk.getEncoded(); } //把公钥导出为字节 public byte[] getPublicKey(){ return this.pk.getEncoded(); } //用公钥加密 public byte[] encrypt(byte[] message) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE,this.pk); return cipher.doFinal(message); } //用私钥解密 public byte[] decrypt(byte[] input) throws GeneralSecurityException{ Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, this.sk); return cipher.doFinal(input); } public static void main(String[] args) throws Exception { //明文 byte[] plain = "Hello,使用RSA非对称加密算法对数据进行加密".getBytes(); //创建公钥/私钥 对 RSAKeyPair rsa = new RSAKeyPair(); //加密 byte[] encrypt = rsa.encrypt(plain); System.out.println("encrypted: " + Base64.getEncoder().encodeToString(encrypt)); //解密 byte[] decrypt = rsa.decrypt(encrypt); System.out.println("decrypted: " + new String(decrypt,"UTF-8")); //保存公钥/私钥 对 byte[] sk = rsa.getPrivateKey(); byte[] pk = rsa.getPublicKey(); System.out.println("sk: " + Base64.getEncoder().encodeToString(sk)); System.out.println("pk: " + Base64.getEncoder().encodeToString(pk)); //重新恢复公钥/私钥 RSAKeyPair rsaKeyPair = new RSAKeyPair(pk, sk); //加密 byte[] encrypted = rsaKeyPair.encrypt(plain); System.out.println("encrypted: " + Base64.getEncoder().encodeToString(encrypted)); //解密 byte[] decrypted = rsa.decrypt(encrypted); System.out.println("decrypted: " + new String(decrypted,"UTF-8")); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpypfg.html