Spring Boot中的密码编码器/解码器

问题描述 投票:0回答:2

我有一个spring boot应用程序,它存储某些密码,这些密码被另一个应用程序(App2)用来连接到数据库。

我想加密这些密码,以便在密钥可用时可以在App2中解码它们。什么是最好的方法呢?

BCrypt不能满足我的目的,因为我还需要解码数据

java spring spring-boot
2个回答
1
投票

使用TextEncryptor,因为您已经在使用Spring。您创建密码和盐时使用的密码和盐代表您的秘密:

Encryptors.text("password", "salt");

0
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.