• 首先了解下,什么是堆成加密,什么是非对称加密?

  对称加密:加密与解密的密钥是相同的,加解密速度很快,比如AES

  非对称加密:加密与解密的秘钥是不同的,速度较慢,比如RSA

  • 先看代码(先会用在研究)

  相关依赖:

  1.   <dependency>
  2. <groupId>org.bouncycastle</groupId>
  3. <artifactId>bcprov-jdk15on</artifactId>
  4. <version>1.58</version>
  5. </dependency>

  

1,RSA工具类:

  1. package cn.wangtao.utils;
  2.  
  3. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6.  
  7. import javax.crypto.Cipher;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.ObjectOutputStream;
  12. import java.security.*;
  13. import java.security.interfaces.RSAPrivateKey;
  14. import java.security.interfaces.RSAPublicKey;
  15.  
  16. /**
  17. * @ClassName RSAUtils
  18. * @Auth 桃子
  19. * @Date 2019-6-25 15:15
  20. * @Version 1.0
  21. * @Description
  22. **/
  23. public class RSAUtils {
  24.  
  25. private static final String RSA = "RSA"; // 加密方式
  26. private static final Logger logger= LoggerFactory.getLogger(RSAUtils.class);
  27.  
  28. //获取密钥
  29. public static KeyPair getKey() throws Exception {
  30. try {
  31. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, new BouncyCastleProvider());
  32. keyPairGenerator.initialize(2048); // 初始化密钥长度
  33. KeyPair keyPair = keyPairGenerator.generateKeyPair();// 生成密钥对
  34. return keyPair;
  35. } catch (Exception e) {
  36. logger.error("获取RSA秘钥对异常",e);
  37. throw new Exception("获取RSA秘钥对异常",e);
  38. }
  39. }
  40.  
  41. //利用公钥进行加密
  42. public static String encryptStr(RSAPublicKey publicKey, String str) throws Exception {
  43. try {
  44. Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());
  45. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  46. //加密
  47. byte[] bytes = getBytes(str.getBytes(), cipher);
  48. //2进行转换成16进制
  49. String result = CommonUtils.parseByte2HexStr(bytes);
  50. return result;
  51. } catch (Exception e) {
  52. logger.error("使用RSA公钥进行加密异常",e);
  53. throw new Exception("使用RSA公钥进行加密异常",e);
  54. }
  55. }
  56.  
  57. //利用私钥进行解密
  58. public static String decryptStr(RSAPrivateKey privateKey, String str) throws Exception {
  59. try {
  60. Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());
  61. cipher.init(Cipher.DECRYPT_MODE, privateKey); // 用密钥初始化此Cipher对象
  62. //16进制转换成2进制
  63. byte[] bytes = CommonUtils.parseHexStr2Byte(str);
  64. //解密
  65. byte[] bs = getBytes(bytes, cipher);
  66. String content=new String(bs,"utf-8");
  67. return content;
  68. } catch (Exception e) {
  69. logger.error("使用RSA私钥进行解密异常",e);
  70. throw new Exception("使用RSA私钥进行解密异常",e);
  71. }
  72. }
  73.  
  74. //通过cipher获取字节数组
  75. public static byte[] getBytes(byte[] bytes,Cipher cipher) throws Exception {
  76. int blockSize = cipher.getBlockSize(); // 返回块的大小
  77. int j = 0;
  78. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  79. while (bytes.length - j * blockSize > 0) { // 将二进制数据分块写入ByteArrayOutputStream中
  80. if(bytes.length-j*blockSize>blockSize){
  81. baos.write(cipher.doFinal(bytes, j * blockSize, blockSize));
  82. }else{
  83. baos.write(cipher.doFinal(bytes, j * blockSize,bytes.length-j*blockSize));
  84. }
  85. j++;
  86. }
  87. baos.close();
  88. byte[] byteArray = baos.toByteArray();
  89. return byteArray;
  90. }
  91.  
  92. //保存秘钥对到文件
  93. public void saveRSAKey(String fileName) throws Exception {
  94. FileOutputStream fos=null;
  95. ObjectOutputStream oos=null;
  96. try {
  97. KeyPair keyPair = getKey();
  98. fos=new FileOutputStream(fileName);
  99. oos=new ObjectOutputStream(fos); //对象序列号
  100. oos.writeObject(keyPair);
  101. } catch (Exception e) {
  102. logger.error("RSA秘钥对保存到文件异常[{}]",fileName,e);
  103. throw new Exception("RSA秘钥对保存到文件异常",e);
  104. }finally {
  105. if(oos!=null){
  106. try {
  107. oos.close();
  108. } catch (IOException e1) {
  109. e1.printStackTrace();
  110. }
  111. }
  112. if(fos!=null){
  113. try {
  114. fos.close();
  115. } catch (IOException e1) {
  116. e1.printStackTrace();
  117. }
  118. }
  119. }
  120. }
  121.  
  122. }

 

  1. /**
  2. * @ClassName RSAUtils
  3. * @Version 1.0
  4. * @Description RSA工具类
  5. **/
  6. public class RSAUtils {
  7.  
  8. private static final String RSA = "RSA";
  9.  
  10. public static final String MD5WITHRSA="MD5withRSA";
  11.  
  12. public static final String SHA1WITHRSA="SHA1withRSA";
  13.  
  14. private static Logger logger= LoggerFactory.getLogger(RSAUtils.class);
  15.  
  16. /**
  17. * @desc 读取秘钥文本内容
  18. * @createTime 2019年7月2日 下午5:20:38
  19. * @param keyFile 秘钥文件
  20. * @return 秘钥文本内容
  21. * @throws Exception
  22. */
  23. private static String initKeyByFile(File keyFile) throws Exception {
  24.  
  25. if(keyFile.exists() && keyFile.isFile()) {
  26. BufferedReader bufferedReader = null;
  27. try {
  28. bufferedReader = new BufferedReader(new FileReader(keyFile));
  29. StringBuilder stringBuilder = new StringBuilder();
  30.  
  31. String line = null;
  32. while ((line = bufferedReader.readLine()) != null) {
  33. if (line.length() == 0 || line.charAt(0) == '-') {
  34. continue;
  35. }
  36. stringBuilder.append(line).append(System.getProperty("line.separator"));
  37. }
  38. return stringBuilder.toString();
  39. }catch (Exception e) {
  40. logger.error("读取秘钥文本内容异常",e);
  41. throw new Exception("读取秘钥文本内容异常",e);
  42. }finally {
  43. CommonUtils.closeReaderandWriter(bufferedReader, null);
  44. }
  45. }
  46. return null;
  47. }
  48.  
  49. /**
  50. * @desc 获取公钥
  51. * @author Liuweian
  52. * @createTime 2019年7月2日 下午5:19:34
  53. * @param pubKeyFileName 公钥文件地址
  54. * @return PublicKey
  55. * @throws Exception
  56. */
  57. public static PublicKey getPublicKeyByFile(File pubKeyFile) throws Exception {
  58. String keyContent = initKeyByFile(pubKeyFile);
  59. byte[] keyByte = Base64.decode(keyContent);
  60. KeyFactory kf = KeyFactory.getInstance(RSA);
  61. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByte);
  62. return kf.generatePublic(keySpec);
  63. }
  64.  
  65. /**
  66. * @desc 获取私钥
  67. * @createTime 2019年7月2日 下午5:19:16
  68. * @param priKeyFileName 私钥文件地址
  69. * @return PrivateKey
  70. * @throws Exception
  71. */
  72. public static PrivateKey getPrivateKeyByFile(File priKeyFile) throws Exception {
  73. String keyContent = initKeyByFile(priKeyFile);
  74. byte[] keyByte = Base64.decode(keyContent);
  75. KeyFactory kf = KeyFactory.getInstance(RSA);
  76. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByte);
  77. return kf.generatePrivate(keySpec);
  78. }
  79.  
  80. /**
  81. * @desc 使用RSA中的私钥对数据签名
  82. * @createTime 2019年7月2日 下午5:24:30
  83. * @param privateKey 秘钥对中的私钥
  84. * @param data 待加签字节数组
  85. * @param signType 加签类型
  86. * @return 加签后的签名
  87. * @throws Exception
  88. */
  89. public static String sign(byte[] data, PrivateKey privateKey, String signType) throws Exception {
  90. Signature signature = Signature.getInstance(signType);
  91. signature.initSign(privateKey);
  92. signature.update(data);
  93. byte[] signByte = signature.sign();
  94. //Base64加密
  95. return new String(Base64.encode(signByte));
  96. }
  97.  
  98. /**
  99. * @desc 使用RSA中的公钥对签名验签
  100. * @createTime 2019年7月2日 下午5:24:30
  101. * @param data 待验签字节数组
  102. * @param sign 签名
  103. * @param publicKey 秘钥对中的公钥
  104. * @param signType 加签类型
  105. * @return 验签是否成功
  106. * @throws Exception
  107. */
  108. public static boolean verify(byte[] data, byte[] sign, PublicKey publicKey, String signType) {
  109. try {
  110. Signature signature = Signature.getInstance(signType);
  111. signature.initVerify(publicKey);
  112. signature.update(data);
  113. //Base64解密
  114. byte[] keyByte = Base64.decode(sign);
  115. return signature.verify(keyByte);
  116. } catch (Exception e) {
  117. logger.error("验签出现异常", e);
  118. return false;
  119. }
  120. }
  121.  
  122. /**
  123. * @desc 使用RSA中的私钥对数据签名 加签方式 MD5withRSA
  124. * @createTime 2019年7月2日 下午5:24:30
  125. * @param privateKey 秘钥对中的私钥
  126. * @param data 待加签字节数组
  127. * @return 加签后的签名
  128. * @throws Exception
  129. */
  130. public static String signMD5withRSA(byte[] data, PrivateKey privateKey) throws Exception {
  131. return sign(data, privateKey, MD5WITHRSA);
  132. }
  133.  
  134. /**
  135. * @desc 使用RSA中的公钥对签名验签 验签方式 MD5withRSA
  136. * @createTime 2019年7月2日 下午5:24:30
  137. * @param sign 签名
  138. * @param publicKey 秘钥对中的公钥
  139. * @param signType 加签类型
  140. * @return 验签是否成功,失败则异常抛出
  141. * @throws Exception
  142. */
  143. public static void verifyMD5withRSA(byte[] data, byte[] sign, PublicKey publicKey) throws Exception {
  144. if(!verify(data, sign, publicKey, MD5WITHRSA)) {
  145. throw new Exception("验签失败");
  146. }
  147. }
  148.  
  149. /**
  150. * @desc 通过cipher获取字节数组 分块
  151. * @createTime 2019年7月2日 下午5:21:33
  152. * @param data 待加密的字节数组
  153. * @param cipher
  154. * @return
  155. * @throws Exception
  156. */
  157. public static byte[] getBytes(byte[] data, Cipher cipher) throws Exception {
  158. int blockSize = cipher.getBlockSize(); // 返回块的大小
  159. int j = 0;
  160. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  161. while (data.length - j * blockSize > 0) { // 将二进制数据分块写入ByteArrayOutputStream中
  162. if(data.length - j * blockSize > blockSize) {
  163. baos.write(cipher.doFinal(data, j * blockSize, blockSize));
  164. }else{
  165. baos.write(cipher.doFinal(data, j * blockSize, data.length - j * blockSize));
  166. }
  167. j++;
  168. }
  169. baos.close();
  170. byte[] byteArray = baos.toByteArray();
  171. return byteArray;
  172. }
  173.  
  174. /**
  175. * @desc 利用公钥进行 加密
  176. * @createTime 2019年7月2日 下午5:24:30
  177. * @param key 密钥对的一个
  178. * @param data 待加密字节数组
  179. * @return 密文
  180. * @throws Exception
  181. */
  182. public static String encrypt(Key key, byte[] data) throws Exception {
  183. try {
  184. Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());
  185. cipher.init(Cipher.ENCRYPT_MODE, key);
  186. //加密
  187. byte[] bytes = getBytes(data, cipher);
  188. //2进行转换成16进制
  189. String result = CommonUtils.parseByte2HexStr(bytes);
  190. return new String(Base64.encode(result.getBytes(CommonUtils.CODE_TYPE)));
  191. } catch (Exception e) {
  192. logger.error("使用RSA公钥进行加密异常",e);
  193. throw new Exception("使用RSA公钥进行加密异常",e);
  194. }
  195. }
  196.  
  197. /**
  198. * @desc 利用私钥进行 解密
  199. * @createTime 2019年7月2日 下午5:23:10
  200. * @param key 密钥对的一个
  201. * @param data 待解密的字节数组
  202. * @return 明文
  203. * @throws Exception
  204. */
  205. public static String decrypt(Key key, byte[] data) throws Exception {
  206. try {
  207. Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());
  208. cipher.init(Cipher.DECRYPT_MODE, key); // 用密钥初始化此Cipher对象
  209. //16进制转换成2进制
  210. byte[] bytes = CommonUtils.parseHexStr2Byte(Base64.decode(data));
  211. //解密
  212. byte[] bs = getBytes(bytes, cipher);
  213. String content=new String(bs,CommonUtils.CODE_TYPE);
  214. return content;
  215. } catch (Exception e) {
  216. logger.error("使用RSA私钥进行解密异常",e);
  217. throw new Exception("使用RSA私钥进行解密异常",e);
  218. }
  219. }
  220.  
  221. }

  

 2,CommonUtils通用工具类:

  1. package cn.wangtao.utils;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5.  
  6. import java.io.IOException;
  7. import java.io.Reader;
  8. import java.io.Writer;
  9.  
  10. /**
  11. * @ClassName CommonUtils
  12. * @Auth 桃子
  13. * @Date 2019-6-27 12:51
  14. * @Version 1.0
  15. * @Description
  16. **/
  17. public class CommonUtils {
  18.  
  19. private static final Logger logger= LoggerFactory.getLogger(CommonUtils.class);
  20. //编码方式
  21. public static final String CODE_TYPE = "UTF-8";
  22.  
  23. //字符补全
  24. private static final String[] consult = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G"};
  25.  
  26. //关流
  27. public static void closeReaderandWriter(Reader reader, Writer writer){
  28. if(writer!=null){
  29. try {
  30. writer.close();
  31. } catch (IOException e) {
  32. logger.error("关闭输出流失败",e);
  33. }
  34. }
  35. if(reader!=null){
  36. try {
  37. reader.close();
  38. } catch (IOException e) {
  39. logger.error("关闭输出流失败",e);
  40. }
  41. }
  42. }
  43.  
  44. //将16进制转换为二进制
  45. public static byte[] parseHexStr2Byte(String hexStr) {
  46. if (hexStr.length() < 1)
  47. return null;
  48. byte[] result = new byte[hexStr.length()/2];
  49. for (int i = 0;i< hexStr.length()/2; i++) {
  50. int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
  51. int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
  52. result[i] = (byte) (high * 16 + low);
  53. }
  54. return result;
  55. }
  56.  
  57. //将二进制转换成16进制
  58. public static String parseByte2HexStr(byte buf[]) {
  59. StringBuffer sb = new StringBuffer();
  60. for (int i = 0; i < buf.length; i++) {
  61. String hex = Integer.toHexString(buf[i] & 0xFF);
  62. if (hex.length() == 1) {
  63. hex = '0' + hex;
  64. }
  65. sb.append(hex.toUpperCase());
  66. }
  67. return sb.toString();
  68. }
  69.  
  70. //补全字符
  71. public static String completionCodeFor16Bytes(String str) throws Exception {
  72. try{
  73. int num = str.getBytes(CODE_TYPE).length;
  74. int index = num%16;
  75. //进行加密内容补全操作, 加密内容应该为 16字节的倍数, 当不足16*n字节是进行补全, 差一位时 补全16+1位
  76. //补全字符 以 $ 开始,$后一位代表$后补全字符位数,之后全部以0进行补全;
  77. if(index != 0){
  78. StringBuffer sbBuffer = new StringBuffer(str);
  79. if(16-index == 1){
  80. sbBuffer.append("$" + consult[16-1] + addStr(16-1-1));
  81. }else{
  82. sbBuffer.append("$" + consult[16-index-1] + addStr(16-index-1-1));
  83. }
  84. str = sbBuffer.toString();
  85. }
  86. return str;
  87. }catch (Exception e){
  88. logger.error("使用AES加密前补全字符异常",e);
  89. throw new Exception("使用AES加密前补全字符异常",e);
  90. }
  91. }
  92.  
  93. //追加字符
  94. public static String addStr(int num){
  95. StringBuffer sbBuffer = new StringBuffer("");
  96. for (int i = 0; i < num; i++) {
  97. sbBuffer.append("0");
  98. }
  99. return sbBuffer.toString();
  100. }
  101.  
  102. //还原字符(进行字符判断)
  103. public static String resumeCodeOf16Bytes(String str) throws Exception{
  104. int indexOf = str.lastIndexOf("$");
  105. if(indexOf == -1){
  106. return str;
  107. }
  108. String trim = str.substring(indexOf+1,indexOf+2).trim();
  109. int num = 0;
  110. for (int i = 0; i < consult.length; i++) {
  111. if(trim.equals(consult[i])){
  112. num = i;
  113. }
  114. }
  115. if(num == 0){
  116. return str;
  117. }
  118. return str.substring(0,indexOf).trim();
  119. }
  120.  
  121. }

  

3,AESUtils通用工具类:

  1. package cn.wangtao.utils;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5.  
  6. import javax.crypto.Cipher;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import java.io.*;
  9. import java.security.interfaces.RSAPrivateKey;
  10. import java.util.Map;
  11.  
  12. /**
  13. * @ClassName AESUtils
  14. * @Auth 桃子
  15. * @Date 2019-6-27 12:05
  16. * @Version 1.0
  17. * @Description
  18. **/
  19. public class AESUtils {
  20.  
  21. private static final Logger logger= LoggerFactory.getLogger(AESUtils.class);
  22.  
  23. //填充类型
  24. public static final String AES_TYPE = "AES/ECB/PKCS5Padding";
  25.  
  26. private static final String AES = "AES"; // 加密方式
  27.  
  28. public static final String DES_TYPE = "DES/ECB/PKCS5Padding";
  29.  
  30. private static final String DES = "DES"; // 加密方式
  31.  
  32. private final String defaultDesKey="11112222";//8位
  33.  
  34. //对字符串加密
  35. public static String encryptStr(String content,String aesKey) throws Exception {
  36. try {
  37. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(),AES );
  38. Cipher cipher = Cipher.getInstance(AES_TYPE);
  39. cipher.init(Cipher.ENCRYPT_MODE, key);
  40. //字符补全
  41. String content16Str = CommonUtils.completionCodeFor16Bytes(content);
  42. byte[] encryptedData = cipher.doFinal(content16Str.getBytes(CommonUtils.CODE_TYPE));
  43. //2进制转换成16进制
  44. String hexStr = CommonUtils.parseByte2HexStr(encryptedData);
  45. return hexStr;
  46. } catch (Exception e) {
  47. logger.error("使用AES对字符串加密异常",e);
  48. throw new Exception("使用AES对字符串加密异常",e);
  49. }
  50.  
  51. }
  52. //对字符串解密
  53. public static String decryptStr(String content,String aesKey) throws Exception {
  54. try {
  55. //16进制转换成2进制
  56. byte[] bytes = CommonUtils.parseHexStr2Byte(content);
  57. SecretKeySpec key = new SecretKeySpec(
  58. aesKey.getBytes(), AES);
  59. Cipher cipher = Cipher.getInstance(AES_TYPE);
  60. cipher.init(Cipher.DECRYPT_MODE, key);
  61. byte[] decryptedData = cipher.doFinal(bytes);
  62. String result=new String(decryptedData, CommonUtils.CODE_TYPE);
  63. //还原字符
  64. String orgResult = CommonUtils.resumeCodeOf16Bytes(result);
  65. return orgResult;
  66. } catch (Exception e) {
  67. logger.error("使用AES对字符串解密异常",e);
  68. throw new Exception("使用AES对字符串解密异常",e);
  69. }
  70. }
  71.  
  72. //对文件加密
  73. public static File encryptFile(File orgFile, File encryptFile, Map<String,Object> context) throws Exception {
  74. logger.info("使用AES对文件加密开始,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath());
  75. BufferedReader br=null;
  76. BufferedWriter bw=null;
  77. try{
  78. //获取AESKEY ,如果没有为默认
  79. String aesKey = (String) context.get(Dirt.AES_KEY);
  80. br=new BufferedReader(new FileReader(orgFile));
  81.  
  82. bw=(BufferedWriter)context.get(Dirt.BUFFEREDWRITER);
  83. if(null==bw){
  84. bw=new BufferedWriter(new FileWriter(encryptFile));
  85. }
  86. String len=null;
  87. while (null!=(len=br.readLine())){
  88. String encrypt= encryptStr(len,aesKey);
  89. bw.write(encrypt);
  90. bw.newLine();
  91. bw.flush();
  92. }
  93. logger.info("使用AES对文件加密结束,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath());
  94. return encryptFile;
  95. }catch (Exception e){
  96. logger.error("使用AES对文件加密异常,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath(),e);
  97. throw new Exception("使用AES对文件加密异常",e);
  98. }finally {
  99. CommonUtils.closeReaderandWriter(br,bw);
  100. }
  101. }
  102.  
  103. //对文本解密,返回解密文件后的文件
  104. public static File decryptFile(File decryptfile, File encryptFile,Map<String,Object> context) throws Exception {
  105. logger.info("使用AES对文件解密开始,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath());
  106. BufferedReader br=null;
  107. BufferedWriter bw=null;
  108. try{
  109. if(decryptfile.exists()){
  110. decryptfile.delete();
  111. }
  112. //边读边加密边写
  113. br=new BufferedReader(new FileReader(encryptFile));
  114. bw=new BufferedWriter(new FileWriter(decryptfile));
  115.  
  116. String len=null;
  117. String aesKey=null;
  118. //判断是否加密
  119. RSAPrivateKey privateKey= (RSAPrivateKey) context.get(Dirt.RSAPRIVATEKEY);
  120. if(null!=privateKey){
  121. StringBuffer sb=new StringBuffer();
  122. while ((len=br.readLine())!=null){
  123. sb.append(len);
  124. if(len.equals("\n")||len.equals("")||len.equals("\r\n")||len.equals("\r")){
  125. aesKey=RSAUtils.decryptStr(privateKey,sb.toString());
  126. break;
  127. }
  128. }
  129. }
  130. if(null==aesKey){
  131. aesKey=(String) context.get(Dirt.AES_KEY);
  132. }
  133. logger.info("aesKey[{}]",aesKey);
  134. if(aesKey!=null){
  135. while ((len=br.readLine())!=null){
  136. String decrypt= decryptStr(len,aesKey);
  137. bw.write(decrypt);
  138. bw.flush();
  139. bw.newLine();
  140. }
  141. }
  142. logger.info("使用AES对文件解密结束,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath());
  143. return decryptfile;
  144. }catch (Exception e){
  145. logger.error("使用AES对文件解密异常,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath(),e);
  146. throw new Exception("使用AES对文件解密异常",e);
  147. }finally {
  148. CommonUtils.closeReaderandWriter(br,bw);
  149. }
  150. }
  151. }

  

  1. /**
  2. * @ClassName AESUtils
  3. * @Version 1.0
  4. * @Description AES工具类
  5. **/
  6. public class AESUtils {
  7.  
  8. private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);
  9.  
  10. /** 加密方式 */
  11. public static final String AES = "AES";
  12.  
  13. public static final String AES_Type = "AES/ECB/PKCS5Padding";
  14.  
  15. /**
  16. * @desc 随机生成AES加密秘钥
  17. * @createTime 2019年7月2日 下午5:36:00
  18. * @return 随机的AES的秘钥串 16位
  19. * @throws Exception
  20. */
  21. public static String getAesKey() {
  22. Random random = new Random();
  23. String result = "";
  24. for(int i = 0; i< 16; i++){
  25. String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
  26. // 输出字母还是数字
  27. if( "char".equalsIgnoreCase(charOrNum) ) {
  28. // 输出是大写字母还是小写字母
  29. // int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
  30. result += (char)(random.nextInt(26) + 65);
  31. } else {
  32. result += String.valueOf(random.nextInt(10));
  33. }
  34. }
  35. return result;
  36. }
  37.  
  38. /**
  39. * @desc AES加密操作
  40. * @createTime 2019年7月2日 下午5:30:33
  41. * @param data 待加密字节数组
  42. * @param aesKey 秘钥串
  43. * @return 密文
  44. * @throws Exception
  45. */
  46. public static String encrypt(byte[] data, String aesKey) throws Exception {
  47. try {
  48. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(CommonUtils.CODE_TYPE), AES);
  49. Cipher cipher = Cipher.getInstance(AES);
  50. cipher.init(Cipher.ENCRYPT_MODE, key);
  51. byte[] encryptedData = cipher.doFinal(data);
  52. //2进制转换成16进制并返回密文
  53. String result = CommonUtils.parseByte2HexStr(encryptedData);
  54. return new String(Base64.encode(result.getBytes(CommonUtils.CODE_TYPE)));
  55. } catch (Exception e) {
  56. logger.error("使用AES对字符串加密异常", e);
  57. throw new Exception("使用AES对字符串加密异常", e);
  58. }
  59. }
  60.  
  61. /**
  62. * @desc AES解密操作
  63. * @createTime 2019年7月2日 下午5:31:37
  64. * @param data 待解密字节数组
  65. * @param aesKey 秘钥串
  66. * @return 明文
  67. * @throws Exception
  68. */
  69. public static String decrypt(byte[] data, String aesKey) throws Exception {
  70. try {
  71. // 16进制转换成2进制
  72. byte[] bytes = CommonUtils.parseHexStr2Byte(Base64.decode(data));
  73.  
  74. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(CommonUtils.CODE_TYPE), AES);
  75. Cipher cipher = Cipher.getInstance(AES);
  76. cipher.init(Cipher.DECRYPT_MODE, key);
  77. //执行解密
  78. byte[] decryptedData = cipher.doFinal(bytes);
  79. //还原字符并返回
  80. return new String(decryptedData, CommonUtils.CODE_TYPE);
  81. } catch (Exception e) {
  82. logger.error("使用AES对字符串解密异常", e);
  83. throw new Exception("使用AES对字符串解密异常", e);
  84. }
  85. }
  86.  
  87. }

  

  4,Dirt常量

  1. package cn.wangtao.utils;
  2.  
  3. import java.security.interfaces.RSAPublicKey;
  4.  
  5. /**
  6. * @ClassName Dirt
  7. * @Auth 桃子
  8. * @Date 2019-6-27 14:20
  9. * @Version 1.0
  10. * @Description
  11. **/
  12. public class Dirt {
  13. public static final String UPLOADFILEURL="uploadFileUrl";
  14. public static final String AES_KEY="aesKey";
  15. public static final String RSAPUBLICKEY="rsaPublicKey";
  16. public static final String RSAPRIVATEKEY="rsaPrivateKey";
  17.  
  18. public final static String RETURNCODE="returnCode";
  19. public final static String RETURNMSG="returnMsg";
  20. public final static String FILENAME="fileName";
  21. public final static String ORGFILENAME="orgFileName";
  22. public final static String ENCRYPTFILE="encryptFile";
  23.  
  24. public static final String BUFFEREDWRITER="bufferedWriter"; //是为了在原始文件中进行补充加密
  25.  
  26. //返回码
  27. public final static String SUCCESSCODE="000000";
  28. public final static String FAILEDCODE="999999";
  29.  
  30. //加密文件所放的目录
  31. public final static String BASELOCALDIR="XXX"; //基本目录路径
  32. public final static String ENCRYPTLOCALDIR="encrypt"; //加密文件目录
  33.  
  34. }
  • AES的介绍

   详情请参考:https://blog.csdn.net/qq_28205153/article/details/55798628

  • RSA的介绍

       详情请参考:https://www.cnblogs.com/jiftle/p/7903762.html

java使用RSA与AES加密解密的更多相关文章

  1. RSA、AES加密解密

    RSA #!/usr/bin/env python # -*- coding:utf-8 -*- import rsa import base64 # ######### 1. 生成公钥私钥 #### ...

  2. 【java工具类】AES加密解密

    百度百科一下,AES:高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准 ...

  3. 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密

    你真的了解字典(Dictionary)吗?   从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...

  4. AES加密解密通用版Object-C / C# / JAVA

    1.无向量 128位 /// <summary> /// AES加密(无向量) /// </summary> /// <param name="plainByt ...

  5. C#, Java, PHP, Python和Javascript几种语言的AES加密解密实现[转载]

    原文:http://outofmemory.cn/code-snippet/35524/AES-with-javascript-java-csharp-python-or-php c#里面的AES加密 ...

  6. java使用AES加密解密 AES-128-ECB加密

    java使用AES加密解密 AES-128-ECB加密 import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; impo ...

  7. AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用

    一:前言 在软件开发中,经常要对数据进行传输,数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的.因此就要对需要传输的数据进行在客户端进行加密 ...

  8. php与java通用AES加密解密算法

    AES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的 ...

  9. Java 关于密码处理的工具类[MD5编码][AES加密/解密]

    项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...

随机推荐

  1. Mark about 《美国债务危机 》

    1.债务是有周期的: 2.其周期性与科技进步水平无关: 3.危机的前夕往往是一片祥和:1925-1927年,主流的媒体倾向于报道xxx公司营收超过xx亿元:无线收音机技术得到长足发展:商业银行扩张势头 ...

  2. SpringCloud 微服务中 @Async 注解自定义线程池 引发的aop 问题

    背景 在 使用springCloud 的@Async注解来做异步操作时,想自定义其线程池. 引发问题 自定义完线程池后,发现代码里并没有使用自定义线程池里的线程,于是新建一个demo工程,一样的配置代 ...

  3. 今天使用Jmeter时遇到的几个问题及解决方法

    JDBC Request :Cannot load JDBC driver class 'com.mysql.jdbc.Driver'解决办法 在Jmeter中run JDBC Request时,收到 ...

  4. js 动态加载 jq

    var script=document.createElement("script"); script.type="text/javascript"; scri ...

  5. OpenShift 4.2 Service Mesh

    1.和社区版Istio的区别 OpenShift 4.2的Service Mesh和upstream的Istio项目的增强,除了产品化之外,借用官方文档,区别在于: Red Hat OpenShift ...

  6. Nginx学习之入门

    1. 概念   (1) 什么是nginx?    Nginx (engine x) 是一款轻量级的Web 服务器 .反向代理服务器及电子邮件(IMAP/POP3)代理服务器.   (2) 什么是反向代 ...

  7. Centos7安装部署MongoDB教程

    安装方式: RPM包安装 安装步骤: 一.下载RPM包 下图是需要注意的事项.其一选择MongoDB的社区版本,默认是企业版本.其二,选中版本后,在下方会出现下载地址,直接复制下载即可  二.安装并查 ...

  8. mvn-dependencies-vs-dependencyManagement

    dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显式的声明需要用的依赖. dependencies 相对于dependencyManagement,所有声明在dep ...

  9. ubantu系统安装ssh

    ssh连接ubantu系统 描述:新安装的ubantu系统,ssh连接发现22端口拒绝,登陆服务器发现没有ssh 1.安装ssh服务 apt-get install openssh-server 报错 ...

  10. [数据结构 - 第3章] 线性表之单链表(C++实现)

    一.类定义 单链表类的定义如下: #ifndef SIGNALLIST_H #define SIGNALLIST_H typedef int ElemType; /* "ElemType类型 ...