繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM