1. import com.google.common.base.Preconditions;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. import lombok.SneakyThrows;
  5. import org.apache.commons.codec.binary.Base64;
  6. import org.apache.commons.codec.binary.StringUtils;
  7. import org.apache.commons.codec.digest.DigestUtils;
  8. import org.apache.shardingsphere.encrypt.strategy.spi.Encryptor;
  9. import javax.crypto.Cipher;
  10. import javax.crypto.NoSuchPaddingException;
  11. import javax.crypto.spec.SecretKeySpec;
  12. import java.nio.charset.StandardCharsets;
  13. import java.security.InvalidKeyException;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.util.Arrays;
  16. import java.util.Properties;
  17. /**
  18. * AES encryptor.
  19. */
  20. @Getter
  21. @Setter
  22. public final class AESEncryptor implements Encryptor {
  23. private static final String AES_KEY = "aes.key.value";
  24. private Properties properties = new Properties();
  25. @Override
  26. public String getType() {
  27. return "AES";
  28. }
  29. @Override
  30. public void init() {
  31. }
  32. @Override
  33. @SneakyThrows
  34. public String encrypt(final Object plaintext) {
  35. if (null == plaintext) {
  36. return null;
  37. }
  38. byte[] result = getCipher(Cipher.ENCRYPT_MODE).doFinal(StringUtils.getBytesUtf8(String.valueOf(plaintext)));
  39. return Base64.encodeBase64String(result);
  40. }
  41. @Override
  42. @SneakyThrows
  43. public Object decrypt(final String ciphertext) {
  44. if (null == ciphertext) {
  45. return null;
  46. }
  47. byte[] result = getCipher(Cipher.DECRYPT_MODE).doFinal(Base64.decodeBase64(ciphertext));
  48. return new String(result, StandardCharsets.UTF_8);
  49. }
  50. private Cipher getCipher(final int decryptMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
  51. Preconditions.checkArgument(properties.containsKey(AES_KEY), "No available secret key for `%s`.", AESEncryptor.class.getName());
  52. Cipher result = Cipher.getInstance(getType());
  53. result.init(decryptMode, new SecretKeySpec(createSecretKey(), getType()));
  54. return result;
  55. }
  56. private byte[] createSecretKey() {
  57. Preconditions.checkArgument(null != properties.get(AES_KEY), String.format("%s can not be null.", AES_KEY));
  58. return Arrays.copyOf(DigestUtils.sha1(properties.get(AES_KEY).toString()), 16);
  59. }
  60. }

我自己的

  1. <dependency>
  2. <groupId>org.apache.directory.studio</groupId>
  3. <artifactId>org.apache.commons.codec</artifactId>
  4. <version>1.8</version>
  5. </dependency>
  1. import lombok.experimental.UtilityClass;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.KeyGenerator;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.nio.charset.StandardCharsets;
  6. import java.security.MessageDigest;
  7. import java.security.NoSuchAlgorithmException;
  8. import org.apache.commons.codec.binary.Base64;
  9. import org.apache.commons.lang3.StringUtils;
  10. import sun.misc.BASE64Decoder;
  11. /**
  12. * @author zhouzhenyong
  13. * @since 2019/2/22 下午11:20
  14. */
  15. @UtilityClass
  16. public class EncryptUtil {
  17. /**
  18. * 算法
  19. */
  20. public final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
  21. /**
  22. * 传入文本内容,返回 encrypt-256 串
  23. *
  24. * @param strText 待加密文本
  25. * @return 加密之后的文本
  26. */
  27. public String sha256(final String strText) {
  28. return encrypt(strText, "SHA-256");
  29. }
  30. /**
  31. * 传入文本内容,返回 encrypt-512 串
  32. * @param strText 待加密文本
  33. * @return 加密之后的文本
  34. */
  35. public String sha512(final String strText) {
  36. return encrypt(strText, "SHA-512");
  37. }
  38. /**
  39. * 传入文本内容,返回 MD5 串
  40. * @param strText 待加密文本
  41. * @return 加密之后的文本
  42. */
  43. public String md5(final String strText){
  44. return encrypt(strText, "MD5");
  45. }
  46. /**
  47. * base 64 encode
  48. * @param bytes 待编码的byte[]
  49. * @return 编码后的base 64 code
  50. */
  51. public String base64Encode(byte[] bytes){
  52. return Base64.encodeBase64String(bytes);
  53. }
  54. /**
  55. * base 64 decode
  56. * @param base64Code 待解码的base 64 code
  57. * @return 解码后的byte[]
  58. * @throws Exception 抛出异常
  59. */
  60. public byte[] base64Decode(String base64Code) throws Exception{
  61. return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
  62. }
  63. /**
  64. * AES加密
  65. * @param content 待加密的内容
  66. * @param key 加密密钥
  67. * @return 加密后的byte[]
  68. */
  69. public byte[] aesEncryptToBytes(String content, String key) throws Exception {
  70. KeyGenerator generator = KeyGenerator.getInstance("AES");
  71. generator.init(128);
  72. Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
  73. cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
  74. return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
  75. }
  76. /**
  77. * AES加密为base 64 code
  78. *
  79. * @param content 待加密的内容
  80. * @param encryptKey 加密密钥
  81. * @return 加密后的base 64 code
  82. */
  83. public String aesEncrypt(String content, String encryptKey) throws Exception {
  84. return base64Encode(aesEncryptToBytes(content, encryptKey));
  85. }
  86. /**
  87. * AES解密
  88. *
  89. * @param encryptBytes 待解密的byte[]
  90. * @param key 解密密钥
  91. * @return 解密后的String
  92. */
  93. public String aesDecryptFromBytes(byte[] encryptBytes, String key) throws Exception {
  94. KeyGenerator generator = KeyGenerator.getInstance("AES");
  95. generator.init(128);
  96. Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
  97. cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
  98. byte[] decryptBytes = cipher.doFinal(encryptBytes);
  99. return new String(decryptBytes);
  100. }
  101. /**
  102. * 将base 64 code AES解密
  103. *
  104. * @param encryptStr 待解密的base 64 code
  105. * @param key 解密密钥
  106. * @return 解密后的string
  107. */
  108. public String aesDecrypt(String encryptStr, String key) throws Exception {
  109. return StringUtils.isEmpty(encryptStr) ? null : aesDecryptFromBytes(base64Decode(encryptStr), key);
  110. }
  111. /**
  112. * 字符串 encrypt 加密
  113. * @param str 待加密文本
  114. * @param strType 加密类型
  115. * @return 加密之后的文本
  116. */
  117. private String encrypt(final String str, final String strType) {
  118. MessageDigest messageDigest;
  119. String encodeStr = "";
  120. if (null == str || str.length() == 0) {
  121. return encodeStr;
  122. }
  123. try {
  124. messageDigest = MessageDigest.getInstance(strType);
  125. messageDigest.update(str.getBytes());
  126. // 将byte 转换为字符展示出来
  127. StringBuilder stringBuffer = new StringBuilder();
  128. String temp;
  129. for (byte aByte : messageDigest.digest()) {
  130. temp = Integer.toHexString(aByte & 0xFF);
  131. if (temp.length() == 1) {
  132. //1得到一位的进行补0操作
  133. stringBuffer.append("0");
  134. }
  135. stringBuffer.append(temp);
  136. }
  137. encodeStr = stringBuffer.toString();
  138. } catch (NoSuchAlgorithmException e) {
  139. throw new RuntimeException(e);
  140. }
  141. return encodeStr;
  142. }
  143. }

DesUtil

  1. import lombok.experimental.UtilityClass;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.SecretKeyFactory;
  4. import javax.crypto.spec.DESKeySpec;
  5. import javax.crypto.spec.IvParameterSpec;
  6. import java.security.Key;
  7. import java.util.Base64;
  8. /**
  9. * @author shizi
  10. * @since 2021-11-22 17:00:24
  11. */
  12. @UtilityClass
  13. public class DESUtil {
  14. /**
  15. * 偏移变量,固定占8位字节
  16. */
  17. private final static String IV_PARAMETER = "12345678";
  18. /**
  19. * 密钥算法
  20. */
  21. private static final String ALGORITHM = "DES";
  22. /**
  23. * 加密/解密算法-工作模式-填充模式
  24. */
  25. private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
  26. /**
  27. * 默认编码
  28. */
  29. private static final String CHARSET = "utf-8";
  30. /**
  31. * 生成key
  32. *
  33. * @param password
  34. * @return
  35. * @throws Exception
  36. */
  37. private static Key generateKey(String password) throws Exception {
  38. DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
  39. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
  40. return keyFactory.generateSecret(dks);
  41. }
  42. /**
  43. * DES加密字符串
  44. *
  45. * @param password 加密密码,长度不能够小于8位
  46. * @param data 待加密字符串
  47. * @return 加密后内容
  48. */
  49. public static String encrypt(String password, String data) {
  50. if (password== null || password.length() < 8) {
  51. throw new RuntimeException("加密失败,key不能小于8位");
  52. }
  53. if (data == null)
  54. return null;
  55. try {
  56. Key secretKey = generateKey(password);
  57. Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
  58. IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
  59. cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
  60. byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
  61. //JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder
  62. //Android平台可以使用android.util.Base64
  63. return new String(Base64.getEncoder().encode(bytes));
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. return data;
  67. }
  68. }
  69. /**
  70. * DES解密字符串
  71. *
  72. * @param password 解密密码,长度不能够小于8位
  73. * @param data 待解密字符串
  74. * @return 解密后内容
  75. */
  76. public static String decrypt(String password, String data) {
  77. if (password== null || password.length() < 8) {
  78. throw new RuntimeException("加密失败,key不能小于8位");
  79. }
  80. if (data == null)
  81. return null;
  82. try {
  83. Key secretKey = generateKey(password);
  84. Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
  85. IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
  86. cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
  87. return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
  88. } catch (Exception e) {
  89. e.printStackTrace();
  90. return data;
  91. }
  92. }
  93. }