本文主要是介绍RSA非对称加密算法的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
加密和解密使用的是两个不同的密钥,这种算法叫作非对称加密算法。反之,用相同的密钥去加密和解密就是对称加密算法。
非对称加密算法需要两个密钥:公开密钥(publickey) 和私有密(privatekey)
- 公开密钥和私有密钥是一对
- 如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密。
- 如果用私有密钥对数据进行加密,只有用对应的公开密钥才能解密。
优点:其安全性更好,非对称加密使用一对秘钥,一个用来加密,一个用来解密,而且公钥是公开的,秘钥是自己保存的,而对称加密需要在交互前将密钥告诉对方。
缺点:加密和解密花费时间长、速度慢,只适合对少量数据进行加密。
在非对称加密中使用的主要算法有:RSA、Elgamal、背包算法、Rabin、D-H、ECC(椭圆曲线加密算法)等。
在对称加密中使用的主要算法有:DES(Data Encryption Standard)、3DES(Triple DES)、AES(Advanced Encryption Standard)、Blowfish等。
RSA算法原理(来自百度百科)
RSA公开密钥密码体制的原理是:根据数论,寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。
RSA的应用场景:
在跟银行,税局等金融行业交互过程中经常用到。
下面说一种对称加密和非对称加密配合使用的例子:
客户端采用RSA非对称加密去对对称加密需要的key进行加密处理。再用未加密的密钥key,使用对称加密算法对需要传输的数据进行对称加密。
最终将非对称加密后的key和对称加密后的数据都传输给服务端。
服务端接收到数据后,就可以先采用非对称解密获取到原始的key,再使用这个key对称解密,获取到原始的数据。
其好处有两个:
- 非对称加密解密花费时间长,故只对对称加密需要的key进行加密处理,提升性能;
- 加密需要的key采用非对称加密,可确保key的安全性。
DESEncrypt.java
import com.sun.org.apache.xml.internal.security.utils.Base64;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;public class DESEncrypt {public DESEncrypt() {}public static String getDESKey() {try {KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");keyGenerator.init(56);SecretKey generateKey = keyGenerator.generateKey();byte[] encoded = generateKey.getEncoded();String encodeHexString = toHexString(encoded);return Base64.encode(encodeHexString.getBytes("UTF-8"));} catch (Exception e) {e.printStackTrace();return "密钥生成错误.";}}public static String toHexString(byte[] byteArray) {if (byteArray != null && byteArray.length >= 1) {StringBuilder hexString = new StringBuilder();for(int i = 0; i < byteArray.length; ++i) {if ((byteArray[i] & 255) < 16) {hexString.append("0");}hexString.append(Integer.toHexString(255 & byteArray[i]));}return hexString.toString();} else {throw new IllegalArgumentException("this byteArray must not be null or empty");}}public static String encrypt(String str, String Key) {String encrypt = "";try {DESKeySpec desKey = new DESKeySpec(Base64.decode(Key));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);Cipher cipher = Cipher.getInstance("DES");cipher.init(1, securekey);byte[] bytes = cipher.doFinal(str.getBytes("UTF-8"));encrypt = Base64.encode(bytes);return encrypt;} catch (Exception e) {e.printStackTrace();return "加密错误";}}public static String decrypt(String buff, String Key) {String decrypt = null;try {DESKeySpec desKey = new DESKeySpec(Base64.decode(Key));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);Cipher cipher = Cipher.getInstance("DES");cipher.init(2, securekey);byte[] responseByte = cipher.doFinal(Base64.decode(buff));decrypt = new String(responseByte, "UTF-8");return decrypt;} catch (Exception e) {e.printStackTrace();return "解密错误";}}
}
RSAEncrypt .java
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;public class RSAEncrypt {public static RSAPublicKey getPublicKeyByStr(String publicKeyStr) throws Exception {try {byte[] buffer = Base64.decode(publicKeyStr);KeyFactory keyFactory = KeyFactory.getInstance("RSA");X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);return (RSAPublicKey)keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException var4) {throw new Exception("无此算法");} catch (InvalidKeySpecException var5) {throw new Exception("公钥非法");} catch (NullPointerException var6) {throw new Exception("公钥数据为空");}}public static byte[] publicEncrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {if (publicKey == null) {throw new Exception("加密公钥为空, 请设置");} else {Cipher cipher = null;try {cipher = Cipher.getInstance("RSA");cipher.init(1, publicKey);byte[] output = cipher.doFinal(plainTextData);return output;} catch (NoSuchAlgorithmException var4) {throw new Exception("无此加密算法");} catch (NoSuchPaddingException var5) {var5.printStackTrace();return null;} catch (InvalidKeyException var6) {throw new Exception("加密公钥非法,请检查");} catch (IllegalBlockSizeException var7) {throw new Exception("明文长度非法");} catch (BadPaddingException var8) {throw new Exception("明文数据已损坏");}}}public static String publicEncrypt(String publicKeyStr, String plainText) throws Exception {RSAPublicKey publicKey = getPublicKeyByStr(publicKeyStr);byte[] plainTextData = Base64.decode(plainText);byte[] encrypt = publicEncrypt(publicKey, plainTextData);return Base64.encode(encrypt);}public static byte[] publicDecrypt(RSAPublicKey publicKey, byte[] cipherTextData) throws Exception {if (publicKey == null) {throw new Exception("解密公钥为空, 请设置");} else {Cipher cipher = null;try {cipher = Cipher.getInstance("RSA");cipher.init(2, publicKey);byte[] output = cipher.doFinal(cipherTextData);return output;} catch (NoSuchAlgorithmException var4) {throw new Exception("无此解密算法");} catch (NoSuchPaddingException var5) {var5.printStackTrace();return null;} catch (InvalidKeyException var6) {throw new Exception("解密公钥非法,请检查");} catch (IllegalBlockSizeException var7) {throw new Exception("密文长度非法");} catch (BadPaddingException var8) {throw new Exception("密文数据已损坏");}}}public static String publicDecrypt(String publicKeyStr, String cipherText) throws Exception {RSAPublicKey publicKey = getPublicKeyByStr(publicKeyStr);byte[] cipherTextData = Base64.decode(cipherText);byte[] decrypt = publicDecrypt(publicKey, cipherTextData);return Base64.encode(decrypt);}public static byte[] privateEncrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {if (privateKey == null) {throw new Exception("加密私钥为空, 请设置");} else {Cipher cipher = null;try {cipher = Cipher.getInstance("RSA");cipher.init(1, privateKey);byte[] output = cipher.doFinal(plainTextData);return output;} catch (NoSuchAlgorithmException var4) {throw new Exception("无此加密算法");} catch (NoSuchPaddingException var5) {var5.printStackTrace();return null;} catch (InvalidKeyException var6) {throw new Exception("加密私钥非法,请检查");} catch (IllegalBlockSizeException var7) {throw new Exception("明文长度非法");} catch (BadPaddingException var8) {throw new Exception("明文数据已损坏");}}}public static String privateEncrypt(String privateKeyStr, String plainText) throws Exception {RSAPrivateKey privateKey = getPrivateKeyByStr(privateKeyStr);byte[] plainTextData = Base64.decode(plainText);byte[] encrypt = privateEncrypt(privateKey, plainTextData);return Base64.encode(encrypt);}public static byte[] privateDecrypt(RSAPrivateKey privateKey, byte[] cipherTextData) throws Exception {if (privateKey == null) {throw new Exception("解密私钥为空, 请设置");} else {Cipher cipher = null;try {cipher = Cipher.getInstance("RSA");cipher.init(2, privateKey);byte[] output = cipher.doFinal(cipherTextData);return output;} catch (NoSuchAlgorithmException var4) {throw new Exception("无此解密算法");} catch (NoSuchPaddingException var5) {var5.printStackTrace();return null;} catch (InvalidKeyException var6) {throw new Exception("解密私钥非法,请检查");} catch (IllegalBlockSizeException var7) {throw new Exception("密文长度非法");} catch (BadPaddingException var8) {throw new Exception("密文数据已损坏");}}}public static String privateDecrypt(String privateKeyStr, String cipherText) throws Exception {RSAPrivateKey privateKey = getPrivateKeyByStr(privateKeyStr);byte[] cipherTextData = Base64.decode(cipherText);byte[] decrypt = privateDecrypt(privateKey, cipherTextData);return Base64.encode(decrypt);}public static RSAPrivateKey getPrivateKeyByStr(String privateKeyStr) throws Exception {try {byte[] buffer = Base64.decode(privateKeyStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);KeyFactory keyFactory = KeyFactory.getInstance("RSA");return (RSAPrivateKey)keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException var4) {throw new Exception("无此算法");} catch (InvalidKeySpecException var5) {throw new Exception("私钥非法");} catch (NullPointerException var6) {throw new Exception("私钥数据为空");}}
}
Test.java
public class Test {public static void main(String[] args) throws Exception {String data ="这是明文";String encryptData = encryptData(data);System.out.println(encryptData);String decryptData = decryptData(encryptData);System.out.println(decryptData);}public static String encryptData(String data) throws Exception {JSONObject jsonObject = new JSONObject();final String deskey = DESEncrypt.getDESKey();String publicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqEfIceRcNHAqQ5sPOrsp6XMZt1Ne8T3BmlTL73rv0MOEO2sGruWCcKUlxl7r23aCvhfymOXNCL6TGewdLa2i7+ms/l0lQQ4OpPbTgQYKbb3NPHo2u1KSrv9twwdPgWhoTMs9MBs3kyLfnGSRG9OXxYtCc7DgJgfTTXcg9KPFoZvubwAsE5+jF8ORLQlvfXi8O66yYIeVjNpcZd3Y+vFt1N/zqHvO65l5l81pVRbk64hiVqseowTampLB9ltCDVDFKzNo/RelO8v52kdZ8/tuT8Na4lpDzPmca0b8Y3GXWLWLxw6Jb8OpbbfE+I14eQ7G5a+iwreiyt7jKgxGJYTwJwIDAQAB";final String desmy = RSAEncrypt.publicEncrypt(publicKey, deskey);final String encryptData = DESEncrypt.encrypt(data, deskey);jsonObject.put("data",encryptData);jsonObject.put("key",desmy);return jsonObject.toJSONString();}public static String decryptData(String encryptData) throws Exception {JSONObject jsonObject = JSON.parseObject(encryptData);String desmy = (String)jsonObject.get("key");String data = (String)jsonObject.get("data");final String deskey = DESEncrypt.getDESKey();String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoR8hx5F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McqobyOMF9hekGtuhlsU+8YlqMC+lEOn7Qqbscu4sHLFe6jj1y6xGABZsnmb+zVjzdPMKy2VStMkdW1bZPJyWWh3j4xt+6V2kjJ6gDhKoOM02RDnfuukbnQuDCJfiSLpVFRRjSiJVZwq4C+AQKBgQC+ZW8i82tmgoi8D50hrwEX0hSG/vOWiECv7xYiGBdcHkRDKq2bqbwAc0wdyTFGnsFDEtyGOeNBBNWXm/DuSfAw9E1m42MZYar56uubotE2Pyqz4bXCyG0/Fwv/wYl+gR7kwWgxvUuTQy3wz6a5Rk6Ah314/gLbYDJDs+66NcmHEwKBgGTII8Tdr01h1N4wgXFD8gfjgJT+mcU4u2o0ge7BNZ4utFYh8P9R6JmUzJDLCVn8tjAVWnRHW8YW49U/VK8uwRTm66mMcCp7auZI/2LrPpBVk/0NQV1Sl4vPIEyeinQ37aHzFmukR8btDWhIIybs7rF79w5WaX/DnICFW67n1Csn";String key = RSAEncrypt.privateDecrypt(privateKey, desmy);String decrypt = DESEncrypt.decrypt(data, key);return decrypt;}
}
这篇关于RSA非对称加密算法的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!