Marcio
Marcio

Reputation: 9

How to encrypt and decrypt with hash using Base64 in Java

Dears, I’m need to encrypt and decrypt a password using Base64 in Java with hash. With this code beneath I can store my password and to access my system:

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);
        }

}

}

Password stored in my database:

password64: pmWkWSBCL51Bfkhn79xPuKBKHz//H6B+mY6G9/eieuM=

planText: 123

However, I need add a salt in my password and use a code like this:

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;
    }

In my console was printed:

11:04:25,766 INFO [stdout] (default task-1) Cipher: pd7suE4qmcdfWTvfNCNad7RRxUMUJahm0OXM0vSrpHY=

11:04:25,995 INFO [stdout] (default task-1) Decrypted: M0993000353

11:04:25,995 INFO [stdout] (default task-1) secretKey: 123

This was password stored in database: pd7suE4qmcdfWTvfNCNad7RRxUMUJahm0OXM0vSrpHY=

However, I don't access my system with this password. Please, Can everyone help me with this question?

Upvotes: 0

Views: 1831

Answers (1)

Antaaaa
Antaaaa

Reputation: 233

Since Java 8 we have a beautiful class Base64.

So you can use Base64.Encoder and Base64.Decoder to perform your tasks

More info: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

Upvotes: 1

Related Questions