AES encrypt String with key - Java Security

Java examples for Security:AES

Description

AES encrypt String with key

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 {

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

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

        try {/*  w  w  w .j  av a2 s  .  c o  m*/
            cipher.init(Cipher.ENCRYPT_MODE, generateKey(pwd)); 
            byte[] resultBytes = cipher.doFinal(message.getBytes("UTF-8")); 
            return Base64.getEncoder().encodeToString(resultBytes);
        } 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