怎样用java工具类加密数据库
时间: 2024-04-23 22:21:44 浏览: 97
要加密数据库,可以使用Java的加密工具类和数据库连接工具类来实现。以下是一个大致的步骤:
1. 导入Java加密库,如Bouncy Castle。
2. 编写一个Java的加密工具类,用于对数据进行加密和解密。这个工具类可以使用对称加密算法,如AES,或非对称加密算法,如RSA。
3. 在数据库连接工具类中,将密码进行加密。这样,在连接数据库时,需要解密密码才能够成功连接。
下面是一个简单的示例代码:
```java
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class EncryptionUtil {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encrypt(String key, String iv, String data) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
byte[] dataBytes = data.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(dataBytes);
}
public static String decrypt(String key, String iv, byte[] encryptedData) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedDataBytes = cipher.doFinal(encryptedData);
return new String(decryptedDataBytes, "UTF-8");
}
}
```
在数据库连接工具类中,可以这样来加密密码:
```java
public class DBUtil {
private static final String KEY = "1234567890123456";
private static final String IV = "1234567890123456";
public static Connection getConnection(String url, String username, String password) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, EncryptionUtil.decrypt(KEY, IV, Base64.getDecoder().decode(password)));
return conn;
}
public static String encryptPassword(String password) throws Exception {
byte[] encryptedData = EncryptionUtil.encrypt(KEY, IV, password);
return Base64.getEncoder().encodeToString(encryptedData);
}
}
```
注意,这个示例代码中使用了AES算法和Base64编码,需要根据实际情况进行修改。同时,要注意安全性问题,加密算法和密钥等需要保密,以免被攻击者破解。
阅读全文