【问题标题】:How to encrypt and decrypt with hash using Base64 in Java如何在 Java 中使用 Base64 进行哈希加密和解密
【发布时间】:2020-06-29 15:48:43
【问题描述】:

亲爱的,我需要在 Java 中使用带有哈希的 Base64 加密和解密密码。使用下面的代码,我可以存储我的密码并访问我的系统:

public class SystemUserDao {

    @PersistenceContext
    private EntityManager manager;

    public void save(SystemUser systemUser) {

        encryPassword(systemUser);
        manager.persist(systemUser);

    }

private void encryPassword(SystemUser systemUser) {

         String password64 = generate(systemUser.getPassword());
         systemUser.setPassword(password64);

}

    public String generate(String plainText) {

        try {
        byte[] digest = MessageDigest.getInstance("sha-256").digest(plainText.getBytes());
            return Base64Encoder.encode(digest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

}

}

密码存储在我的数据库中:

密码64:pmWkWSBCL51Bfkhn79xPuKBKHz//H6B+mY6G9/eieuM=

计划文本:123

但是,我需要在密码中添加盐并使用如下代码:

public class SystemUserDao {

    @PersistenceContext
    private EntityManager manager;

    public void save(SystemUser systemUser) {

        encryDecryPasswordWithSalt(systemUser);
        manager.persist(systemUser);

    }


private String encryDecryPasswordWithSalt(SystemUser systemUser) {

        String secretKey = systemUser.getPassword();

        try {
            String fSalt = "anySaltYouCanUseOfOn";
            String plainText = "M0993000353";
            String cipherText = encrypt(secretKey, fSalt, plainText);
            System.out.println("Cipher: " + cipherText);
            String dcrCipherText = decrypt(secretKey, fSalt, cipherText);
            System.out.println("Decrypted: " + dcrCipherText);
            System.out.println("secretKey: " + secretKey);
            systemUser.setPassword(cipherText);
            return plainText;
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
}

public static String encrypt(String secretKey, String salt, String value) throws Exception {
Cipher cipher = initCipher(secretKey, salt, Cipher.ENCRYPT_MODE);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        byte[] cipherWithIv = addIVToCipher(encrypted);
        return Base64.encodeBase64String(cipherWithIv);
    }

public static String decrypt(String secretKey, String salt, String encrypted) throws Exception {
       Cipher cipher = initCipher(secretKey, salt, Cipher.DECRYPT_MODE);
       byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
       byte[] originalWithoutIv = Arrays.copyOfRange(original, 16, original.length);
        return new String(originalWithoutIv);
    }

private static Cipher initCipher(String secretKey, String salt, int mode) throws Exception {
       SecretKeyFactory factory = SecretKeyFactory.getInstance(factoryInstance);
       KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
       SecretKeySpec skeySpec = new SecretKeySpec(tmp.getEncoded(), secretKeyType);
        Cipher cipher = Cipher.getInstance(cipherInstance);
        // Generating random IV
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivCode);

        cipher.init(mode, skeySpec, new IvParameterSpec(ivCode));
        return cipher;
    }

private static byte[] addIVToCipher(byte[] encrypted) {
        byte[] cipherWithIv = new byte[ivCode.length + encrypted.length];
        System.arraycopy(ivCode, 0, cipherWithIv, 0, ivCode.length);
        System.arraycopy(encrypted, 0, cipherWithIv, encrypted.length, encrypted.length);
        return cipherWithIv;
    }

在我的控制台上打印了:

11:04:25,766 INFO [stdout](默认任务 1)密码:pd7suE4qmcdfWTvfNCNad7RRxUMUJahm0OXM0vSrPHY=

11:04:25,995 INFO [stdout](默认任务 1)解密:M0993000353

11:04:25,995 INFO [stdout](默认任务 1)secretKey:123

这是存储在数据库中的密码: pd7suE4qmcdfWTvfNCNad7RRxUMUJahm0OXM0vSrPHY=

但是,我无法使用此密码访问我的系统。 请问大家可以帮我解答这个问题吗?

【问题讨论】:

  • “但是,我无法使用此密码访问我的系统。”甚至是什么意思?在给定的代码中什么不起作用?

标签: java encryption java-8 base64 aes


【解决方案1】:

从 Java 8 开始,我们有了一个漂亮的类 Base64

所以你可以使用Base64.EncoderBase64.Decoder 来执行你的任务

更多信息:https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2014-01-14
    相关资源
    最近更新 更多