文章目录
RSA加密算法直接上代码工具类:测试类:测试结果:RSA加密算法
一种非对称加密算法,所谓非对称,就是指该算法加密和解密使用不同的密钥,即使用斜体样式加密密钥进行加密、解密密钥进行解密
直接上代码
工具类:
import javax.crypto.Cipher;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Arrays;import java.util.Base64;public class RSAUtil {//将Base64编码后的公钥转换成PublicKey对象public static PublicKey string2PublicKey(String pubStr) throws Exception{byte[] keyBytes = base642Byte(pubStr);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}//将Base64编码后的私钥转换成PrivateKey对象public static PrivateKey string2PrivateKey(String priStr) throws Exception{byte[] keyBytes = base642Byte(priStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}//Base64编码转字节数组public static byte[] base642Byte(String base64Key) throws IOException{Base64.Decoder decoder = Base64.getDecoder();return decoder.decode(base64Key);}/*** 解密方法* @param byte2Base64* @return*/public static String RsaDecrypt(String byte2Base64,String privateKeyStr){byte[] decryptedData=null;try {//将Base64编码后的私钥转换成PrivateKey对象PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());cipher.init(2, privateKey);byte[] encryptedData = RSAUtil.base642Byte(byte2Base64);int inputLen = encryptedData.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;for(int i = 0; inputLen - offSet > 0; offSet = i * 256) {byte[] cache;if(inputLen - offSet > 256) {cache = cipher.doFinal(encryptedData, offSet, 256);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);++i;}decryptedData = out.toByteArray();out.close();}catch (Exception e){e.printStackTrace();}return new String(decryptedData);}/*** 分断加密* @param byte2Base642* @return*/public static String rsaEncrypt(String byte2Base642,String publicKeyStr) {String result = "";try {// 将Base64编码后的公钥转换成PublicKey对象PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);// 加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] inputArray = byte2Base642.getBytes();int inputLength = inputArray.length;// 最大加密字节数,超出最大字节数需要分组加密int MAX_ENCRYPT_BLOCK = 117;// 标识int offSet = 0;byte[] resultBytes = {};byte[] cache = {};while (inputLength - offSet > 0) {if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);offSet += MAX_ENCRYPT_BLOCK;} else {cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);offSet = inputLength;}resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);}Base64.Encoder encoder = Base64.getEncoder();result = encoder.encodeToString(resultBytes);} catch (Exception e) {System.out.println(e.toString());System.out.println("rsaEncrypt error:" + e.getMessage());}return result;}}
测试类:
public class Test {public static void main(String[] args) {//公钥String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg0doe1LOyn+ha+Hl12/EcwoLpXq30dmVcPTuPHqmBPtSJ6bN5jnaKR8JiGJANPhRkW0BYoI1Xj1hmHAtPEO+Hh/370MKpU2+xddMQJEmE79zONdrKCMxGm3oZWTGQylQLAWEf8SY32nz0hmh2SQ68oKSGxc8L2XIV9DaSsAc3EaRYPawHtThyWV28hUtmRQmKQ/wf5q346Urmu11ZjEZZUyO9NbzpKdxJRdScg8cbFJ8kRpHS+qbIYyGJkit9xqjuJ/g3L9WvgW8LFF5WUxz93a98LYnI90ESKx2ZD+64p4oyeEgJ52PLkpb//tbLapIA47P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YCggLQ+DwWQ8PLSckiB5fberv0CPTH15qP8tn6YwKBgQDJQzX6/5ZdOIVEcGW2Pj6g0mIke2Jz+3kGVgodJnCXCtRxfWR0WMybY+JC2cwWNdm6I7vWn/eYXl5nWDWjvZOrzypDrtqMN0+CUGMRNZqfbQVsLAT/m6C5+hwYUQfCzl/ZAbQOujpFyp0RN9AtrhmadhNWLYZE3topt6mwAxeQmQKBgQCfp/52ixJunvZTC3++uV5PAwqrCJerM5vEn/5UyK41d2q5aPkMiaTXW2D23e7zpZMe1V7tbEk5SiGa80Oa5cGWl2MhQ1v+l/DfZ7+Iy/RQ1lWUF8T2KCABhz+i/D/hvwIImc2ynjmgpUK25ESFIx5m1v7AJUR+KOJOWkWhPikyjwKBgEShIr/u7GnImcLL5Dd2H4HqUHBVBQv7Ceb8j3oar/milgBtmSow+bZj0fuX1Mu7Xjw9cswgI0npC7Wd1w79wcWVWDeZF+eg2aqME0Uovd3U2HYhZHSTc2r2U59uLkqsl3jm9xI5+dkQi6FX1v067P8TA6R6ZCc6YSNtkb+z/6nP";String string="{\"returnId\":\"9\",\"isRelief\":\"成功\"}";System.out.println("加密内容 : "+string);String encryptRes = RSAUtil.rsaEncrypt(string,publicKey);System.out.println("res加密后的密文 : "+encryptRes);String decryptRes = RSAUtil.RsaDecrypt(encryptRes,privateKey);System.out.println("res加密密文解密后的内容 : "+decryptRes);}}
测试结果:
加密内容 : {"returnId":"9","isRelief":"成功"}res加密内容后的密文 : Tur0jUO5zQRFb+S7CFX7qN6oyLQG1IrIEIAAS6yHAlOmkP1/s9CfN09h32wQ7qy/oASiIU+4MtcW2to3ZuwBj1/qeSwg7ceQ9IK5nU4+GT8KpdaqZunEhTKz/U7JSIQRSZFpw7GB8V9JVYM+rrx/dBU+3lzGNPwvlJVhGS16Q8TQlaTZdn/B92S1oZ/cJ1RbAccEhbYBb2mDc+ByCwpYHG8tKHSyCvPILVHDq1hmtg6BuMOhCAZSSXBsC39QjnDwWt9yQ6nY+dL5aQlVwyMkZpCTpSfF9pkIYbH5UiQiZ7hUjrvisxkre7SsAjFyPl1ZnryLCSDZO2DwrZ46mj/0rg==res加密密文解密后的内容 : {"returnId":"9","isRelief":"成功"}
如果觉得《RSA加密算法-非对称加密算法的使用》对你有帮助,请点赞、收藏,并留下你的观点哦!