https://blog.csdn.net/u013871100/article/details/80100992

AES-128位-无向量-ECB/PKCS7Padding


  1. package com.debug.steadyjack.springbootMQ.server.util;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.security.Security;
  6. /**
  7. * AES加密算法util
  8. * Created by steadyjack on 2018/4/21.
  9. */
  10. public class AESUtil {
  11. private static final String EncryptAlg ="AES";
  12. private static final String Cipher_Mode="AES/ECB/PKCS7Padding";
  13. private static final String Encode="UTF-8";
  14. private static final int Secret_Key_Size=32;
  15. private static final String Key_Encode="UTF-8";
  16. /**
  17. * AES/ECB/PKCS7Padding 加密
  18. * @param content
  19. * @param key 密钥
  20. * @return aes加密后 转base64
  21. * @throws Exception
  22. */
  23. public static String aesPKCS7PaddingEncrypt(String content, String key) throws Exception {
  24. try {
  25. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  26. Cipher cipher = Cipher.getInstance(Cipher_Mode);
  27. byte[] realKey=getSecretKey(key);
  28. cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
  29. byte[] data=cipher.doFinal(content.getBytes(Encode));
  30. String result=new Base64().encodeToString(data);
  31. return result;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. throw new Exception("AES加密失败:content=" +content +" key="+key);
  35. }
  36. }
  37. /**
  38. * AES/ECB/PKCS7Padding 解密
  39. * @param content
  40. * @param key 密钥
  41. * @return 先转base64 再解密
  42. * @throws Exception
  43. */
  44. public static String aesPKCS7PaddingDecrypt(String content, String key) throws Exception {
  45. try {
  46. //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  47. byte[] decodeBytes=Base64.decodeBase64(content);
  48. Cipher cipher = Cipher.getInstance(Cipher_Mode);
  49. byte[] realKey=getSecretKey(key);
  50. cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
  51. byte[] realBytes=cipher.doFinal(decodeBytes);
  52. return new String(realBytes, Encode);
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. throw new Exception("AES解密失败:Aescontent = " +e.fillInStackTrace(),e);
  56. }
  57. }
  58. /**
  59. * 对密钥key进行处理:如密钥长度不够位数的则 以指定paddingChar 进行填充;
  60. * 此处用空格字符填充,也可以 0 填充,具体可根据实际项目需求做变更
  61. * @param key
  62. * @return
  63. * @throws Exception
  64. */
  65. public static byte[] getSecretKey(String key) throws Exception{
  66. final byte paddingChar=' ';
  67. byte[] realKey = new byte[Secret_Key_Size];
  68. byte[] byteKey = key.getBytes(Key_Encode);
  69. for (int i =0;i<realKey.length;i++){
  70. if (i<byteKey.length){
  71. realKey[i] = byteKey[i];
  72. }else {
  73. realKey[i] = paddingChar;
  74. }
  75. }
  76. return realKey;
  77. }
  78. }
  79. ————————————————
  80. public static void main(String[] args) throws Exception{
  81. //密钥 加密内容(对象序列化后的内容-json格式字符串)
  82. String key="debug";
  83. String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
  84. String encryptRes=aesPKCS7PaddingEncrypt(content,key);
  85. System.out.println(String.format("加密结果:%s ",encryptRes));
  86. String decryptRes=aesPKCS7PaddingDecrypt(encryptRes,key);
  87. System.out.println(String.format("解密结果:%s ",decryptRes));
  88. }

AES-128位-有向量-CBC/PKCS5Padding

  1. package com.debug.steadyjack.springbootMQ.server.util;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.io.UnsupportedEncodingException;
  7. /**
  8. * AES加解密工具
  9. * Created by steadyjack on 2018/2/9.
  10. */
  11. public class EncryptUtil {
  12. private static final String CipherMode="AES/CBC/PKCS5Padding";
  13. private static final String SecretKey="debug";
  14. private static final Integer IVSize=16;
  15. private static final String EncryptAlg ="AES";
  16. private static final String Encode="UTF-8";
  17. private static final int SecretKeySize=32;
  18. private static final String Key_Encode="UTF-8";
  19. /**
  20. * 创建密钥
  21. * @return
  22. */
  23. private static SecretKeySpec createKey(){
  24. StringBuilder sb=new StringBuilder(SecretKeySize);
  25. sb.append(SecretKey);
  26. if (sb.length()>SecretKeySize){
  27. sb.setLength(SecretKeySize);
  28. }
  29. if (sb.length()<SecretKeySize){
  30. while (sb.length()<SecretKeySize){
  31. sb.append(" ");
  32. }
  33. }
  34. try {
  35. byte[] data=sb.toString().getBytes(Encode);
  36. return new SecretKeySpec(data, EncryptAlg);
  37. }catch (Exception e){
  38. e.printStackTrace();
  39. }
  40. return null;
  41. }
  42. /**
  43. * 创建16位向量: 不够则用0填充
  44. * @return
  45. */
  46. private static IvParameterSpec createIV() {
  47. StringBuffer sb = new StringBuffer(IVSize);
  48. sb.append(SecretKey);
  49. if (sb.length()>IVSize){
  50. sb.setLength(IVSize);
  51. }
  52. if (sb.length()<IVSize){
  53. while (sb.length()<IVSize){
  54. sb.append("0");
  55. }
  56. }
  57. byte[] data=null;
  58. try {
  59. data=sb.toString().getBytes(Encode);
  60. } catch (UnsupportedEncodingException e) {
  61. e.printStackTrace();
  62. }
  63. return new IvParameterSpec(data);
  64. }
  65. /**
  66. * 加密:有向量16位,结果转base64
  67. * @param context
  68. * @return
  69. */
  70. public static String encrypt(String context) {
  71. try {
  72. byte[] content=context.getBytes(Encode);
  73. SecretKeySpec key = createKey();
  74. Cipher cipher = Cipher.getInstance(CipherMode);
  75. cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
  76. byte[] data = cipher.doFinal(content);
  77. String result=Base64.encodeBase64String(data);
  78. return result;
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. }
  82. return null;
  83. }
  84. /**
  85. * 解密
  86. * @param context
  87. * @return
  88. */
  89. public static String decrypt(String context) {
  90. try {
  91. byte[] data=Base64.decodeBase64(context);
  92. SecretKeySpec key = createKey();
  93. Cipher cipher = Cipher.getInstance(CipherMode);
  94. cipher.init(Cipher.DECRYPT_MODE, key, createIV());
  95. byte[] content = cipher.doFinal(data);
  96. String result=new String(content,Encode);
  97. return result;
  98. } catch (Exception e) {
  99. e.printStackTrace();
  100. }
  101. return null;
  102. }
  103. public static void main(String[] args) throws Exception{
  104. //密钥 加密内容(对象序列化后的内容-json格式字符串)
  105. String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
  106. String encryptText=encrypt(content);
  107. String decryptText=decrypt(encryptText);
  108. System.out.println(String.format("明文:%s \n加密结果:%s \n解密结果:%s ",content,encryptText,decryptText));
  109. }
  110. }

java实现多种加密模式的AES算法-总有一种你用的着的更多相关文章

  1. Java数据结构之字符串模式匹配算法---Brute-Force算法

    模式匹配 在字符串匹配问题中,我们期待察看源串 " S串 " 中是否含有目标串 " 串T " (也叫模式串).其中 串S被称为主串,串T被称为子串. 1.如果在 ...

  2. Java数据结构之字符串模式匹配算法---KMP算法2

    直接接上篇上代码: //KMP算法 public class KMP { // 获取next数组的方法,根据给定的字符串求 public static int[] getNext(String sub ...

  3. Java数据结构之字符串模式匹配算法---KMP算法

    本文主要的思路都是参考http://kb.cnblogs.com/page/176818/ 如有冒犯请告知,多谢. 一.KMP算法 KMP算法可以在O(n+m)的时间数量级上完成串的模式匹配操作,其基 ...

  4. java.. C# 使用AES加密互解 采用AES-128-ECB加密模式

    java需要下载外部包, commons codec.jar 1.6  較新的JAVA版本把Base64的方法改成靜態方法,可能會寫成Base64.encodeToString(encrypted, ...

  5. AES Java加密 C#解密 (128-ECB加密模式)

    在项目中遇到这么一个问题: java端需要把一些数据AES加密后传给C#端,找了好多资料,算是解决了,分享一下: import sun.misc.BASE64Decoder; import sun.m ...

  6. AES算法加密java实现

    package cn.itcast.coderUtils; import java.security.Key; import javax.crypto.Cipher; import javax.cry ...

  7. C#与Java互通AES算法加密解密

    /// <summary>AES加密</summary> /// <param name="text">明文</param> /// ...

  8. .NET与Java互通AES算法加密解密

    /// <summary>AES加密</summary> /// <param name="text">明文</param> /// ...

  9. 无线路由器的加密模式WEP,WPA-PSK(TKIP),WPA2-PSK(AES) WPA-PSK(TKIP)+WPA2-PSK(AES)。

    目前无线路由器里带有的加密模式主要有:WEP,WPA-PSK(TKIP),WPA2-PSK(AES)和WPA-PSK(TKIP)+WPA2-PSK(AES). WEP(有线等效加密)WEP是Wired ...

随机推荐

  1. B/S,C/S架构的区别

    B/S架构:browser/server,采用的是浏览器服务器模式. C/S架构:client/server,采用的是客户端服务器模式. B/S架构,客户端是浏览器基本不需要维护,只需要维护升级服务器 ...

  2. Ant Design -- 图片可拖拽效果,图片跟随鼠标移动

    Ant Design 图片可拖拽效果,图片跟随鼠标移动,需计算鼠标在图片中与图片左上角的X轴的距离和鼠标在图片中与图片左上角的Y轴的距离. constructor(props) { super(pro ...

  3. VB程序设计中Combobox的取值问题

    Private a As Double   Private Sub Combo1_Click()    '1位小数,系数用10    a = Combo1.ItemData(Combo1.ListIn ...

  4. 03python面向对象编程5

    5.1 继承机制及其使用 继承是面向对象的三大特征之一,也是实现软件复用的重要手段.Python 的继承是多继承机制,即一个子类可以同时有多个直接父类. Python 子类继承父类的语法是在定义子类时 ...

  5. ffmpeg使用分析视频

    https://www.cnblogs.com/Finley/p/8646711.html 先存下

  6. 计蒜客 蓝桥模拟 F. 结果填空:数独

    代码: #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream& ...

  7. 【学习】022 ActiveMQ

    一.消息中间件概述 1.1消息中间件产生的背景 在客户端与服务器进行通讯时.客户端调用后,必须等待服务对象完成处理返回结果才能继续执行.  客户与服务器对象的生命周期紧密耦合,客户进程和服务对象进程都 ...

  8. python3-使用__slots__

    正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性.先定义class: class Student(object): pa ...

  9. AGC007题解

    发现自己思维能力又跟不上了...做题有点吃力...所以回归AGC刷题计划... AGC040506都写了一部分题然后懒得补全了,所以从07开始做吧.大概是从C开始. C 这也太人类智慧了吧... 我先 ...

  10. Keras MAE和MSE source code

    def mean_squared_error(y_true, y_pred): if not K.is_tensor(y_pred): y_pred = K.constant(y_pred) y_tr ...