[英]Password Encoder/Decoder in Spring Boot
我有一個Spring Boot應用程序,該應用程序存儲某些密碼,該密碼由另一個應用程序(App2)用於獲取與數據庫的連接。
我想對這些密碼進行加密,以便在有密鑰的情況下可以在App2中對其進行解碼。 最好的方法是什么?
BCrypt無法滿足我的目的,因為我還需要解碼數據
就像已經使用Spring一樣,使用TextEncryptor 。 創建密碼時所使用的密碼和鹽代表了您的秘密:
Encryptors.text("password", "salt");
您可以使用AES加密算法,這里是有關Java中加密和解密的示例:
private static final String ALGO = "AES";
private static final byte[] keyValue = new byte[] { 'T', 'E', 'S', 'T' };
/**
* Encrypt a string using AES encryption algorithm.
*
* @param pwd the password to be encrypted
* @return the encrypted string
*/
public static String encrypt(String pwd) {
String encodedPwd = "";
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(pwd.getBytes());
encodedPwd = Base64.getEncoder().encodeToString(encVal);
} catch (Exception e) {
e.printStackTrace();
}
return encodedPwd;
}
/**
* Decrypt a string with AES encryption algorithm.
*
* @param encryptedData the data to be decrypted
* @return the decrypted string
*/
public static String decrypt(String encryptedData) {
String decodedPWD = "";
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = Base64.getDecoder().decode(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
decodedPWD = new String(decValue);
} catch (Exception e) {
}
return decodedPWD;
}
/**
* Generate a new encryption key.
*/
private static Key generateKey() {
SecretKeySpec key = new SecretKeySpec(keyValue, ALGO);
return key;
}
讓我們測試main方法中的示例
public static void main(String[]args) {
System.out.println(encrypt("password"));
System.out.println(decrypt(encrypt("password")));
}
結果 :
LGB7fIm4PtaRA0L0URK4RA==
password
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.