AES decrypt String with password - Java Security

Java examples for Security:AES

Description

AES decrypt String with password

Demo Code


//package com.java2s;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

public class Main {
    public static void main(String[] argv) throws Exception {
        String message = "java2s.com";
        String pwd = "java2s.com";
        System.out.println(decrypt(message, pwd));
    }//w w w  .  j  av  a 2  s . c om

    private static final String KEY_ALGORITHM = "AES";
    private static Cipher cipher = null;

    public static String decrypt(String message, String pwd) {

        try {
            cipher.init(Cipher.DECRYPT_MODE, generateKey(pwd)); 
            byte[] resultBytes = cipher.doFinal(Base64.getDecoder().decode(
                    message));
            return new String(resultBytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static SecretKey generateKey(String pwd)
            throws NoSuchAlgorithmException {
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
        kgen.init(128, new SecureRandom(pwd.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        return secretKey;
    }
}

Related Tutorials