当前位置:   article > 正文

java项目中,如何加密配置文件中的敏感信息

java配置信息怎么不让别人知道

在日常开发中,我们常常会把一些敏感信息写进*.properties配置文件中,比如数据库密码、redis密码、admin用户的密码甚至系统用户的密码等。

我在某银行做运维时,经常会遇到这样的情况:

银行的系统都是通过堡垒机管理的,应用管理人员理论上不应该知道任何系统用户的密码,只需通过堡垒机,使用只读key或可写key即可登录相应的用户。但在一次偶尔查看应用的配置文件时,我发现应用在调用CD时需要登录系统用户,而用户名和密码均使用明文写在了配置文件中。知道了用户名密码,就可以使用su命令随意切换用户了。诸如此类的还有数据库密码等,均可在配置文件中找到,这在信息安全和权限控制等方面有很大的隐患。

所以出于安全考虑,对配置文件中敏感信息的加密就很有必要了。

不多说了,直接上方法:

  1. 重写PropertyPlaceholderConfigurer 
    1. import java.io.IOException;
    2. import java.util.HashMap;
    3. import java.util.List;
    4. import java.util.Map;
    5. import java.util.MissingResourceException;
    6. import java.util.Properties;
    7. import org.apache.commons.lang3.StringUtils;
    8. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
    9. public final class PropertiesUtil extends PropertyPlaceholderConfigurer {
    10. private static final byte[] KEY = {9, -1, 0, 5, 39, 8, 6, 19};
    11. private static Map<String, String> ctxPropertiesMap;
    12. private List<String> decryptProperties;
    13. @Override
    14. protected void loadProperties(Properties props) throws IOException {
    15. super.loadProperties(props);
    16. ctxPropertiesMap = new HashMap<String, String>();
    17. for (Object key : props.keySet()) {
    18. String keyStr = key.toString();
    19. String value = props.getProperty(keyStr);
    20. if (decryptProperties != null && decryptProperties.contains(keyStr)) {
    21. value = SecurityUtil.decryptDes(value, KEY);
    22. props.setProperty(keyStr, value);
    23. }
    24. ctxPropertiesMap.put(keyStr, value);
    25. }
    26. }
    27. /**
    28. * @param decryptPropertiesMap the decryptPropertiesMap to set
    29. */
    30. public void setDecryptProperties(List<String> decryptProperties) {
    31. this.decryptProperties = decryptProperties;
    32. }
    33. /**
    34. * Get a value based on key , if key does not exist , null is returned
    35. *
    36. * @param key
    37. * @return
    38. */
    39. public static String getString(String key) {
    40. try {
    41. return ctxPropertiesMap.get(key);
    42. } catch (MissingResourceException e) {
    43. return null;
    44. }
    45. }
    46. /**
    47. * 根据key获取值
    48. *
    49. * @param key
    50. * @return
    51. */
    52. public static int getInt(String key) {
    53. return Integer.parseInt(ctxPropertiesMap.get(key));
    54. }
    55. /**
    56. * 根据key获取值
    57. *
    58. * @param key
    59. * @param defaultValue
    60. * @return
    61. */
    62. public static int getInt(String key, int defaultValue) {
    63. String value = ctxPropertiesMap.get(key);
    64. if (StringUtils.isBlank(value)) {
    65. return defaultValue;
    66. }
    67. return Integer.parseInt(value);
    68. }
    69. /**
    70. * 根据key获取值
    71. * @param key
    72. * @param defaultValue
    73. * @return
    74. */
    75. public static boolean getBoolean(String key, boolean defaultValue) {
    76. String value = ctxPropertiesMap.get(key);
    77. if (StringUtils.isBlank(value)) {
    78. return defaultValue;
    79. }
    80. return new Boolean(value);
    81. }
    82. public static void main(String[] args) {
    83. String encrypt = SecurityUtil.encryptDes("ROOT", KEY);
    84. System.out.println(encrypt);
    85. System.out.println(SecurityUtil.decryptDes(encrypt, KEY));
    86. }
    87. }
     
    1. public final class SecurityUtil {
    2. private SecurityUtil() {
    3. }
    4. public static final String CHARSET = "UTF-8";
    5. /**
    6. * BASE64解码
    7. *
    8. * @param key
    9. * @return
    10. * @throws Exception
    11. */
    12. public static final byte[] decryptBASE64(String key) {
    13. try {
    14. return new BASE64Encoder().decode(key);
    15. } catch (Exception e) {
    16. throw new RuntimeException("解密错误,错误信息:", e);
    17. }
    18. }
    19. /**
    20. * BASE64编码
    21. *
    22. * @param key
    23. * @return
    24. * @throws Exception
    25. */
    26. public static final String encryptBASE64(byte[] key) {
    27. try {
    28. return new BASE64Encoder().encode(key);
    29. } catch (Exception e) {
    30. throw new RuntimeException("加密错误,错误信息:", e);
    31. }
    32. }
    33. /**
    34. * 数据解密,算法(DES)
    35. *
    36. * @param cryptData
    37. * 加密数据
    38. * @return 解密后的数据
    39. */
    40. public static final String decryptDes(String cryptData, byte[] key) {
    41. String decryptedData = null;
    42. try {
    43. // 把字符串解码为字节数组,并解密
    44. decryptedData = new String(DESCoder.decrypt(decryptBASE64(cryptData), key));
    45. } catch (Exception e) {
    46. throw new RuntimeException("解密错误,错误信息:", e);
    47. }
    48. return decryptedData;
    49. }
    50. /**
    51. * 数据加密,算法(DES)
    52. *
    53. * @param data
    54. * 要进行加密的数据
    55. * @return 加密后的数据
    56. */
    57. public static final String encryptDes(String data, byte[] key) {
    58. String encryptedData = null;
    59. try {
    60. // 加密,并把字节数组编码成字符串
    61. encryptedData = encryptBASE64(DESCoder.encrypt(data.getBytes(), key));
    62. } catch (Exception e) {
    63. throw new RuntimeException("加密错误,错误信息:", e);
    64. }
    65. return encryptedData;
    66. }
    67. }
     
    1. import java.io.UnsupportedEncodingException;
    2. /**
    3. * Hex encoder and decoder. The charset used for certain operation can be set,
    4. * the default is set in
    5. *
    6. * @author ShenHuaJie
    7. * @version $Id: Hex.java, v 0.1 2014年3月25日 上午9:39:07 ShenHuaJie Exp $
    8. */
    9. public class Hex {
    10. /***
    11. * Default charset name is {@link CharEncoding#UTF_8}
    12. */
    13. public static final String DEFAULT_CHARSET_NAME = "UTF-8";
    14. /***
    15. * Used to build output as Hex
    16. */
    17. private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
    18. 'e', 'f' };
    19. /***
    20. * Used to build output as Hex
    21. */
    22. private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
    23. 'E', 'F' };
    24. /***
    25. * Converts an array of characters representing hexadecimal values into an
    26. * array of bytes of those same values. The returned array will be half the
    27. * length of the passed array, as it takes two characters to represent any
    28. * given byte. An exception is thrown if the passed char array has an odd
    29. * number of elements.
    30. *
    31. * @param data An array of characters containing hexadecimal digits
    32. * @return A byte array containing binary data decoded from the supplied
    33. * char array.
    34. * @throws Exception Thrown if an odd number or illegal of characters is
    35. * supplied
    36. */
    37. public static byte[] decodeHex(char[] data) throws Exception {
    38. int len = data.length;
    39. if ((len & 0x01) != 0) {
    40. throw new Exception("Odd number of characters.");
    41. }
    42. byte[] out = new byte[len >> 1];
    43. // two characters form the hex value.
    44. for (int i = 0, j = 0; j < len; i++) {
    45. int f = toDigit(data[j], j) << 4;
    46. j++;
    47. f = f | toDigit(data[j], j);
    48. j++;
    49. out[i] = (byte) (f & 0xFF);
    50. }
    51. return out;
    52. }
    53. /***
    54. * Converts an array of bytes into an array of characters representing the
    55. * hexadecimal values of each byte in order. The returned array will be
    56. * double the length of the passed array, as it takes two characters to
    57. * represent any given byte.
    58. *
    59. * @param data a byte[] to convert to Hex characters
    60. * @return A char[] containing hexadecimal characters
    61. */
    62. public static char[] encodeHex(byte[] data) {
    63. return encodeHex(data, true);
    64. }
    65. /***
    66. * Converts an array of bytes into an array of characters representing the
    67. * hexadecimal values of each byte in order. The returned array will be
    68. * double the length of the passed array, as it takes two characters to
    69. * represent any given byte.
    70. *
    71. * @param data a byte[] to convert to Hex characters
    72. * @param toLowerCase <code>true</code> converts to lowercase,
    73. * <code>false</code> to uppercase
    74. * @return A char[] containing hexadecimal characters
    75. * @since 1.4
    76. */
    77. public static char[] encodeHex(byte[] data, boolean toLowerCase) {
    78. return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    79. }
    80. /***
    81. * Converts an array of bytes into an array of characters representing the
    82. * hexadecimal values of each byte in order. The returned array will be
    83. * double the length of the passed array, as it takes two characters to
    84. * represent any given byte.
    85. *
    86. * @param data a byte[] to convert to Hex characters
    87. * @param toDigits the output alphabet
    88. * @return A char[] containing hexadecimal characters
    89. * @since 1.4
    90. */
    91. protected static char[] encodeHex(byte[] data, char[] toDigits) {
    92. int l = data.length;
    93. char[] out = new char[l << 1];
    94. // two characters form the hex value.
    95. for (int i = 0, j = 0; i < l; i++) {
    96. out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
    97. out[j++] = toDigits[0x0F & data[i]];
    98. }
    99. return out;
    100. }
    101. /***
    102. * Converts an array of bytes into a String representing the hexadecimal
    103. * values of each byte in order. The returned String will be double the
    104. * length of the passed array, as it takes two characters to represent any
    105. * given byte.
    106. *
    107. * @param data a byte[] to convert to Hex characters
    108. * @return A String containing hexadecimal characters
    109. * @since 1.4
    110. */
    111. public static String encodeHexString(byte[] data) {
    112. return new String(encodeHex(data));
    113. }
    114. /***
    115. * Converts a hexadecimal character to an integer.
    116. *
    117. * @param ch A character to convert to an integer digit
    118. * @param index The index of the character in the source
    119. * @return An integer
    120. * @throws Exception Thrown if ch is an illegal hex character
    121. */
    122. protected static int toDigit(char ch, int index) throws Exception {
    123. int digit = Character.digit(ch, 16);
    124. if (digit == -1) {
    125. throw new Exception("Illegal hexadecimal charcter " + ch + " at index " + index);
    126. }
    127. return digit;
    128. }
    129. private static String charsetName = DEFAULT_CHARSET_NAME;
    130. /***
    131. * Creates a new codec with the default charset name
    132. * {@link #DEFAULT_CHARSET_NAME}
    133. */
    134. public Hex() {
    135. }
    136. /***
    137. * Creates a new codec with the given charset name.
    138. *
    139. * @param csName the charset name.
    140. * @since 1.4
    141. */
    142. public Hex(String csName) {
    143. charsetName = csName;
    144. }
    145. /***
    146. * Converts an array of character bytes representing hexadecimal values into
    147. * an array of bytes of those same values. The returned array will be half
    148. * the length of the passed array, as it takes two characters to represent
    149. * any given byte. An exception is thrown if the passed char array has an
    150. * odd number of elements.
    151. *
    152. * @param array An array of character bytes containing hexadecimal digits
    153. * @return A byte array containing binary data decoded from the supplied
    154. * byte array (representing characters).
    155. * @throws Exception Thrown if an odd number of characters is supplied to
    156. * this function
    157. * @see #decodeHex(char[])
    158. */
    159. public byte[] decode(byte[] array) throws Exception {
    160. try {
    161. return decodeHex(new String(array, getCharsetName()).toCharArray());
    162. } catch (Exception e) {
    163. throw new Exception(e.getMessage(), e);
    164. }
    165. }
    166. /***
    167. * Converts a String or an array of character bytes representing hexadecimal
    168. * values into an array of bytes of those same values. The returned array
    169. * will be half the length of the passed String or array, as it takes two
    170. * characters to represent any given byte. An exception is thrown if the
    171. * passed char array has an odd number of elements.
    172. *
    173. * @param object A String or, an array of character bytes containing
    174. * hexadecimal digits
    175. * @return A byte array containing binary data decoded from the supplied
    176. * byte array (representing characters).
    177. * @throws Exception Thrown if an odd number of characters is supplied to
    178. * this function or the object is not a String or char[]
    179. * @see #decodeHex(char[])
    180. */
    181. public Object decode(Object object) throws Exception {
    182. try {
    183. char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object;
    184. return decodeHex(charArray);
    185. } catch (ClassCastException e) {
    186. throw new Exception(e.getMessage(), e);
    187. }
    188. }
    189. /***
    190. * Converts an array of bytes into an array of bytes for the characters
    191. * representing the hexadecimal values of each byte in order. The returned
    192. * array will be double the length of the passed array, as it takes two
    193. * characters to represent any given byte.
    194. * <p>
    195. * The conversion from hexadecimal characters to the returned bytes is
    196. * performed with the charset named by {@link #getCharsetName()}.
    197. * </p>
    198. *
    199. * @param array a byte[] to convert to Hex characters
    200. * @return A byte[] containing the bytes of the hexadecimal characters
    201. * @throws IllegalStateException if the charsetName is invalid. This API
    202. * throws {@link IllegalStateException} instead of
    203. * {@link Exception} for backward compatibility.
    204. * @see #encodeHex(byte[])
    205. */
    206. public static byte[] encode(byte[] array) throws UnsupportedEncodingException {
    207. String string = encodeHexString(array);
    208. if (string == null) {
    209. return null;
    210. }
    211. return string.getBytes(charsetName);
    212. }
    213. /***
    214. * Converts a String or an array of bytes into an array of characters
    215. * representing the hexadecimal values of each byte in order. The returned
    216. * array will be double the length of the passed String or array, as it
    217. * takes two characters to represent any given byte.
    218. * <p>
    219. * The conversion from hexadecimal characters to bytes to be encoded to
    220. * performed with the charset named by {@link #getCharsetName()}.
    221. * </p>
    222. *
    223. * @param object a String, or byte[] to convert to Hex characters
    224. * @return A char[] containing hexadecimal characters
    225. * @throws Exception Thrown if the given object is not a String or byte[]
    226. * @see #encodeHex(byte[])
    227. */
    228. public Object encode(Object object) throws Exception {
    229. try {
    230. byte[] byteArray = object instanceof String ? ((String) object).getBytes(getCharsetName())
    231. : (byte[]) object;
    232. return encodeHex(byteArray);
    233. } catch (ClassCastException e) {
    234. throw new Exception(e.getMessage(), e);
    235. } catch (Exception e) {
    236. throw new Exception(e.getMessage(), e);
    237. }
    238. }
    239. /***
    240. * Gets the charset name.
    241. *
    242. * @return the charset name.
    243. * @since 1.4
    244. */
    245. public String getCharsetName() {
    246. return charsetName;
    247. }
    248. /***
    249. * Returns a string representation of the object, which includes the charset
    250. * name.
    251. *
    252. * @return a string representation of the object.
    253. */
    254. @Override
    255. public String toString() {
    256. return super.toString() + "[charsetName=" + charsetName + "]";
    257. }
    258. }
     
    1. import java.security.MessageDigest;
    2. /**
    3. * MD加密组件
    4. *
    5. * @author du
    6. * @version 1.0
    7. * @since 1.0
    8. */
    9. public abstract class MDCoder {
    10. /**
    11. * MD2加密
    12. *
    13. * @param data 待加密数据
    14. * @return byte[] 消息摘要
    15. * @throws Exception
    16. */
    17. public static byte[] encodeMD2(byte[] data) throws Exception {
    18. // 初始化MessageDigest
    19. MessageDigest md = MessageDigest.getInstance("MD2");
    20. // 执行消息摘要
    21. return md.digest(data);
    22. }
    23. /**
    24. * MD4加密
    25. *
    26. * @param data 待加密数据
    27. * @return byte[] 消息摘要
    28. * @throws Exception
    29. */
    30. public static byte[] encodeMD4(byte[] data) throws Exception {
    31. // 初始化MessageDigest
    32. MessageDigest md = MessageDigest.getInstance("MD4");
    33. // 执行消息摘要
    34. return md.digest(data);
    35. }
    36. /**
    37. * MD5加密
    38. *
    39. * @param data 待加密数据
    40. * @return byte[] 消息摘要
    41. * @throws Exception
    42. */
    43. public static byte[] encodeMD5(byte[] data) throws Exception {
    44. // 初始化MessageDigest
    45. MessageDigest md = MessageDigest.getInstance("MD5");
    46. // 执行消息摘要
    47. return md.digest(data);
    48. }
    49. /**
    50. * Tiger加密
    51. *
    52. * @param data 待加密数据
    53. * @return byte[] 消息摘要
    54. * @throws Exception
    55. */
    56. public static byte[] encodeTiger(byte[] data) throws Exception {
    57. // 初始化MessageDigest
    58. MessageDigest md = MessageDigest.getInstance("Tiger");
    59. // 执行消息摘要
    60. return md.digest(data);
    61. }
    62. /**
    63. * TigerHex加密
    64. *
    65. * @param data 待加密数据
    66. * @return byte[] 消息摘要
    67. * @throws Exception
    68. */
    69. public static String encodeTigerHex(byte[] data) throws Exception {
    70. // 执行消息摘要
    71. byte[] b = encodeTiger(data);
    72. // 做十六进制编码处理
    73. return new String(Hex.encode(b));
    74. }
    75. /**
    76. * Whirlpool加密
    77. *
    78. * @param data 待加密数据
    79. * @return byte[] 消息摘要
    80. * @throws Exception
    81. */
    82. public static byte[] encodeWhirlpool(byte[] data) throws Exception {
    83. // 初始化MessageDigest
    84. MessageDigest md = MessageDigest.getInstance("Whirlpool");
    85. // 执行消息摘要
    86. return md.digest(data);
    87. }
    88. /**
    89. * WhirlpoolHex加密
    90. *
    91. * @param data 待加密数据
    92. * @return byte[] 消息摘要
    93. * @throws Exception
    94. */
    95. public static String encodeWhirlpoolHex(byte[] data) throws Exception {
    96. // 执行消息摘要
    97. byte[] b = encodeWhirlpool(data);
    98. // 做十六进制编码处理
    99. return new String(Hex.encode(b));
    100. }
    101. /**
    102. * GOST3411加密
    103. *
    104. * @param data 待加密数据
    105. * @return byte[] 消息摘要
    106. * @throws Exception
    107. */
    108. public static byte[] encodeGOST3411(byte[] data) throws Exception {
    109. // 初始化MessageDigest
    110. MessageDigest md = MessageDigest.getInstance("GOST3411");
    111. // 执行消息摘要
    112. return md.digest(data);
    113. }
    114. /**
    115. * GOST3411Hex加密
    116. *
    117. * @param data 待加密数据
    118. * @return byte[] 消息摘要
    119. * @throws Exception
    120. */
    121. public static String encodeGOST3411Hex(byte[] data) throws Exception {
    122. // 执行消息摘要
    123. byte[] b = encodeGOST3411(data);
    124. // 做十六进制编码处理
    125. return new String(Hex.encode(b));
    126. }
    127. }
     
    1. import java.security.InvalidKeyException;
    2. import java.security.Key;
    3. import java.security.NoSuchAlgorithmException;
    4. import java.security.SecureRandom;
    5. import java.security.spec.InvalidKeySpecException;
    6. import javax.crypto.BadPaddingException;
    7. import javax.crypto.Cipher;
    8. import javax.crypto.IllegalBlockSizeException;
    9. import javax.crypto.KeyGenerator;
    10. import javax.crypto.NoSuchPaddingException;
    11. import javax.crypto.SecretKey;
    12. import javax.crypto.SecretKeyFactory;
    13. import javax.crypto.spec.DESKeySpec;
    14. /**
    15. * DES安全编码组件
    16. *
    17. * @author du
    18. * @version 1.0
    19. * @since 1.0
    20. */
    21. public abstract class DESCoder {
    22. /**
    23. * 密钥算法 <br>
    24. * Java 6 只支持56bit密钥 <br>
    25. * Bouncy Castle 支持64bit密钥
    26. */
    27. public static final String KEY_ALGORITHM = "DES";
    28. /**
    29. * 加密/解密算法 / 工作模式 / 填充方式
    30. */
    31. public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
    32. /**
    33. * 转换密钥
    34. *
    35. * @param key 二进制密钥
    36. * @return Key 密钥
    37. * @throws InvalidKeyException
    38. * @throws NoSuchAlgorithmException
    39. * @throws InvalidKeySpecException
    40. * @throws Exception
    41. */
    42. private static Key toKey(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
    43. // 实例化DES密钥材料
    44. DESKeySpec dks = new DESKeySpec(key);
    45. // 实例化秘密密钥工厂
    46. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
    47. // 生成秘密密钥
    48. SecretKey secretKey = keyFactory.generateSecret(dks);
    49. return secretKey;
    50. }
    51. /**
    52. * 解密
    53. *
    54. * @param data 待解密数据
    55. * @param key 密钥
    56. * @return byte[] 解密数据
    57. * @throws InvalidKeySpecException
    58. * @throws NoSuchAlgorithmException
    59. * @throws InvalidKeyException
    60. * @throws NoSuchPaddingException
    61. * @throws BadPaddingException
    62. * @throws IllegalBlockSizeException
    63. * @throws Exception
    64. */
    65. public static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
    66. InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    67. // 还原密钥
    68. Key k = toKey(key);
    69. // 实例化
    70. Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    71. // 初始化,设置为解密模式
    72. cipher.init(Cipher.DECRYPT_MODE, k);
    73. // 执行操作
    74. return cipher.doFinal(data);
    75. }
    76. /**
    77. * 加密
    78. *
    79. * @param data 待加密数据
    80. * @param key 密钥
    81. * @return byte[] 加密数据
    82. * @throws NoSuchPaddingException
    83. * @throws NoSuchAlgorithmException
    84. * @throws InvalidKeyException
    85. * @throws BadPaddingException
    86. * @throws IllegalBlockSizeException
    87. * @throws InvalidKeySpecException
    88. * @throws Exception
    89. */
    90. public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,
    91. InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
    92. // 还原密钥
    93. Key k = toKey(key);
    94. // 实例化
    95. Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    96. // 初始化,设置为加密模式
    97. cipher.init(Cipher.ENCRYPT_MODE, k);
    98. // 执行操作
    99. return cipher.doFinal(data);
    100. }
    101. /**
    102. * 生成密钥 <br>
    103. * Java 6 只支持56bit密钥 <br>
    104. * Bouncy Castle 支持64bit密钥 <br>
    105. *
    106. * @return byte[] 二进制密钥
    107. * @throws NoSuchAlgorithmException
    108. * @throws Exception
    109. */
    110. public static byte[] initKey() throws NoSuchAlgorithmException {
    111. /*
    112. * 实例化密钥生成器
    113. *
    114. * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
    115. * 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
    116. */
    117. KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
    118. /*
    119. * 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
    120. */
    121. kg.init(56, new SecureRandom());
    122. // 生成秘密密钥
    123. SecretKey secretKey = kg.generateKey();
    124. // 获得密钥的二进制编码形式
    125. return secretKey.getEncoded();
    126. }
    127. }
     
    1. import java.io.ByteArrayInputStream;
    2. import java.io.ByteArrayOutputStream;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.io.OutputStream;
    6. import java.io.PushbackInputStream;
    7. /**
    8. * 密码器类
    9. *
    10. * @author du
    11. * @since 2017-11-19
    12. */
    13. public class BASE64Encoder {
    14. /**
    15. * 译码数据源
    16. */
    17. private static final char[] PEM_ARRAY = {
    18. // 0 1 2 3 4 5 6 7
    19. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', // 0
    20. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', // 1
    21. 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', // 2
    22. 'y', 'z', '1', '2', '3', '4', '5', '6', // 3
    23. '7', '8', '9', '0', 'A', 'B', 'C', 'D', // 4
    24. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', // 5
    25. 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', // 6
    26. 'U', 'V', 'W', 'X', 'Y', 'Z', '+', '/' // 7
    27. };
    28. private static final byte[] pem_convert_array = new byte[256];
    29. private byte[] decode_buffer = new byte[4];
    30. public BASE64Encoder() {
    31. }
    32. /**
    33. * 编码
    34. */
    35. public String encode(byte[] bt) {
    36. int totalBits = bt.length * 8;
    37. int nn = totalBits % 6;
    38. int curPos = 0;// process bits
    39. StringBuilder toReturn = new StringBuilder(32);
    40. while (curPos < totalBits) {
    41. int bytePos = curPos / 8;
    42. switch (curPos % 8) {
    43. case 0:
    44. toReturn.append(PEM_ARRAY[(bt[bytePos] & 0xfc) >> 2]);
    45. break;
    46. case 2:
    47. toReturn.append(PEM_ARRAY[(bt[bytePos] & 0x3f)]);
    48. break;
    49. case 4:
    50. if (bytePos == bt.length - 1) {
    51. toReturn.append(PEM_ARRAY[((bt[bytePos] & 0x0f) << 2) & 0x3f]);
    52. } else {
    53. int pos = (((bt[bytePos] & 0x0f) << 2) | ((bt[bytePos + 1] & 0xc0) >> 6)) & 0x3f;
    54. toReturn.append(PEM_ARRAY[pos]);
    55. }
    56. break;
    57. case 6:
    58. if (bytePos == bt.length - 1) {
    59. toReturn.append(PEM_ARRAY[((bt[bytePos] & 0x03) << 4) & 0x3f]);
    60. } else {
    61. int pos = (((bt[bytePos] & 0x03) << 4) | ((bt[bytePos + 1] & 0xf0) >> 4)) & 0x3f;
    62. toReturn.append(PEM_ARRAY[pos]);
    63. }
    64. break;
    65. default:
    66. break;
    67. }
    68. curPos += 6;
    69. }
    70. if (nn == 2) {
    71. toReturn.append("==");
    72. } else if (nn == 4) {
    73. toReturn.append("=");
    74. }
    75. return toReturn.toString();
    76. }
    77. /**
    78. * 解码
    79. */
    80. public byte[] decode(String str) throws IOException {
    81. byte[] arrayOfByte = str.getBytes();
    82. ByteArrayInputStream inputStream = new ByteArrayInputStream(arrayOfByte);
    83. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    84. decodeBuffer(inputStream, outputStream);
    85. return outputStream.toByteArray();
    86. }
    87. private void decodeBuffer(InputStream paramInputStream, OutputStream paramOutputStream) throws IOException {
    88. PushbackInputStream localPushbackInputStream = new PushbackInputStream(paramInputStream);
    89. int j = 0;
    90. while (true) {
    91. try {
    92. int k = bytesPerLine();
    93. int i = 0;
    94. if (i + bytesPerAtom() < k) {
    95. decodeAtom(localPushbackInputStream, paramOutputStream, bytesPerAtom());
    96. j += bytesPerAtom();
    97. i += bytesPerAtom();
    98. continue;
    99. }
    100. if (i + bytesPerAtom() == k) {
    101. decodeAtom(localPushbackInputStream, paramOutputStream, bytesPerAtom());
    102. j += bytesPerAtom();
    103. } else {
    104. decodeAtom(localPushbackInputStream, paramOutputStream, k - i);
    105. j += k - i;
    106. }
    107. } catch (RuntimeException e) {
    108. String.valueOf(j);
    109. break;
    110. }
    111. }
    112. }
    113. private int bytesPerAtom() {
    114. return 4;
    115. }
    116. private int bytesPerLine() {
    117. return 72;
    118. }
    119. private void decodeAtom(PushbackInputStream paramPushbackInputStream, OutputStream paramOutputStream, int paramInt)
    120. throws IOException {
    121. int i;
    122. int j = -1;
    123. int k = -1;
    124. int m = -1;
    125. int n = -1;
    126. if (paramInt < 2) {
    127. throw new java.lang.ArrayStoreException("BASE64Decoder: Not enough bytes for an atom.");
    128. }
    129. do {
    130. i = paramPushbackInputStream.read();
    131. if (i == -1) {
    132. throw new RuntimeException();
    133. }
    134. } while ((i == 10) || (i == 13));
    135. this.decode_buffer[0] = (byte)i;
    136. i = readFully(paramPushbackInputStream, this.decode_buffer, 1, paramInt - 1);
    137. if (i == -1) {
    138. throw new RuntimeException();
    139. }
    140. if ((paramInt > 3) && (this.decode_buffer[3] == 61)) {
    141. paramInt = 3;
    142. }
    143. if ((paramInt > 2) && (this.decode_buffer[2] == 61)) {
    144. paramInt = 2;
    145. }
    146. switch (paramInt) {
    147. case 4:
    148. n = pem_convert_array[(this.decode_buffer[3] & 0xFF)];
    149. case 3:
    150. m = pem_convert_array[(this.decode_buffer[2] & 0xFF)];
    151. case 2:
    152. k = pem_convert_array[(this.decode_buffer[1] & 0xFF)];
    153. j = pem_convert_array[(this.decode_buffer[0] & 0xFF)];
    154. }
    155. switch (paramInt) {
    156. case 2:
    157. paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));
    158. break;
    159. case 3:
    160. paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));
    161. paramOutputStream.write((byte)(k << 4 & 0xF0 | m >>> 2 & 0xF));
    162. break;
    163. case 4:
    164. paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));
    165. paramOutputStream.write((byte)(k << 4 & 0xF0 | m >>> 2 & 0xF));
    166. paramOutputStream.write((byte)(m << 6 & 0xC0 | n & 0x3F));
    167. }
    168. }
    169. private int readFully(InputStream paramInputStream, byte[] paramArrayOfByte, int paramInt1, int paramInt2)
    170. throws IOException {
    171. for (int i = 0; i < paramInt2; i++) {
    172. int j = paramInputStream.read();
    173. if (j == -1) {
    174. return i == 0 ? -1 : i;
    175. }
    176. paramArrayOfByte[(i + paramInt1)] = (byte)j;
    177. }
    178. return paramInt2;
    179. }
    180. static {
    181. for (int i = 0; i < 255; i++) {
    182. pem_convert_array[i] = -1;
    183. }
    184. for (int i = 0; i < PEM_ARRAY.length; i++)
    185. pem_convert_array[PEM_ARRAY[i]] = (byte)i;
    186. }
    187. }
     
  2. 加密敏感信息:

    执行PropertiesUtil类中的main方法:

    1. public static void main(String[] args) {//ROOT为要加密的明文
    2. String encrypt = SecurityUtil.encryptDes("ROOT", KEY);
    3. System.out.println(encrypt);
    4. System.out.println(SecurityUtil.decryptDes(encrypt, KEY));
    5. }
     此处加密数据库密码,假设数据库密码为ROOT

     

  3. 配置文件中该明文为密文:
    1. db.writer.username=root
    2. db.writer.password=9u7x63ZJmcy=
     
  4. 在spring配置文件中引入配置:
    1. <!-- 引入属性文件 -->
    2. <bean class="com.ds.core.util.PropertiesUtil">
    3. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    4. <property name="ignoreResourceNotFound" value="true" />
    5. <property name="locations">
    6. <list>
    7. <value>classpath:config/jdbc.properties</value>
    8. </list>
    9. </property>
    10. <property name="decryptProperties">
    11. <array>
    12. <!-- 需要解密的配置 -->
    13. <value>db.writer.password</value>
    14. </array>
    15. </property>
    16. </bean>
     

 搞定!酷

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/691419
推荐阅读
相关标签
  

闽ICP备14008679号