# 各种安全相关

back2 专题

# 配置文件敏感信息处理

back

dbc.properties 中的数据库密码配置是这样写的:
jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388

# AES 的 Java 实现

AES(高级加密标准)是美国联邦政府采用的一种区块加密标准,其替代原先的 DES 加密算法,成为对称密钥加密中最流行的算法之一。

package com.demo.project.monitor.util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AESEncryption {
 private String password = "Password";
 public AESEncryption(){
 }
 public AESEncryption(String password){
 this.password = password;
 }
 /**
 * 加密
 * @param content 加密内容
 * @return
 */
 public String encrypt(String content) {
 try {
 KeyGenerator kgen = KeyGenerator.getInstance("AES");
 kgen.init(128, new SecureRandom(password.getBytes()));
 SecretKey secretKey = kgen.generateKey();
 byte[] enCodeFormat = secretKey.getEncoded();
 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
 Cipher cipher = Cipher.getInstance("AES");// 创建密码器
 byte[] byteContent = content.getBytes("utf-8");
 cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
 byte[] result = cipher.doFinal(byteContent);
 return parseByte2HexStr(result); // 加密
 } catch (NoSuchAlgorithmException e) {
 e.printStackTrace();
 } catch (NoSuchPaddingException e) {
 e.printStackTrace();
 } catch (InvalidKeyException e) {
 e.printStackTrace();
 } catch (UnsupportedEncodingException e) {
 e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
 e.printStackTrace();
 } catch (BadPaddingException e) {
 e.printStackTrace();
 }
 return null;
 }
 /**解密
 * @param content 解密内容
 * @return
 */
 public String decrypt(String content) {
 try {
 KeyGenerator kgen = KeyGenerator.getInstance("AES");
 kgen.init(128, new SecureRandom(password.getBytes()));
 SecretKey secretKey = kgen.generateKey();
 byte[] enCodeFormat = secretKey.getEncoded();
 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
 Cipher cipher = Cipher.getInstance("AES");// 创建密码器
 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
 byte[] result = cipher.doFinal(parseHexStr2Byte(content));
 return new String(result); // 解密
 } catch (NoSuchAlgorithmException e) {
 e.printStackTrace();
 } catch (NoSuchPaddingException e) {
 e.printStackTrace();
 } catch (InvalidKeyException e) {
 e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
 e.printStackTrace();
 } catch (BadPaddingException e) {
 e.printStackTrace();
 }
 return null;
 }
 /**
 * 将二进制转换成16进制
 * @param buf
 * @return
 */
 private String parseByte2HexStr(byte buf[]) {
 StringBuffer sb = new StringBuffer();
 for (int i = 0; i < buf.length; i++) {
 String hex = Integer.toHexString(buf[i] & 0xFF);
 if (hex.length() == 1) {
 hex = '0' + hex;
 }
 sb.append(hex.toUpperCase());
 }
 return sb.toString();
 }
 /**
 * 将16进制转换为二进制
 * @param hexStr
 * @return
 */
 private byte[] parseHexStr2Byte(String hexStr) {
 if (hexStr.length() < 1)
 return null;
 byte[] result = new byte[hexStr.length()/2];
 for (int i = 0;i< hexStr.length()/2; i++) {
 int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
 int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
 result[i] = (byte) (high * 16 + low);
 }
 return result;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

# 解密配置文件

back

# md5

import org.apache.tomcat.util.security.MD5Encoder;
import java.security.MessageDigest;

private static String md5String(String source) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(source.getBytes());
//        byte[] bytes = messageDigest.digest();
//        System.out.println(bytes);
//        System.out.println(new BigInteger(1, messageDigest.digest()).toString(16));
        return MD5Encoder.encode(messageDigest.digest());
//        return new String(bytes);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return StringUtils.EMPTY;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# HmacSHA1 再 base64

back

private static String macString(String key, String baseString) {
    try {
        byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);
        SecretKey secretKey = new SecretKeySpec(keyByte, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] result = mac.doFinal(baseString.getBytes(StandardCharsets.UTF_8));
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(result);
//            System.out.println(byte2hex(result));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
    return StringUtils.EMPTY;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Java SHA1 签名

back

# 原生 SHA1

private static final char[] HEX = {'0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

private static String getFormattedText(byte[] bytes) {
    int len = bytes.length;
    StringBuilder buf = new StringBuilder(len * 2);
    // 把密文转换成十六进制的字符串形式
    for (int j = 0; j < len; j++) {
        buf.append(HEX[(bytes[j] >> 4) & 0x0f]);
        buf.append(HEX[bytes[j] & 0x0f]);
    }
    return buf.toString();
}
public static String encode(String str) {
    if (str == null) {
        return null;
    }
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        messageDigest.update(str.getBytes());
        return getFormattedText(messageDigest.digest());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# Apache 公共包commons-codec

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>
1
2
3
4
5
import org.apache.commons.codec.digest.DigestUtils;
//使用这个方法
String sha1 = DigestUtils.sha1Hex(bytes);
1
2
3