create AES Key from password - Java Security

Java examples for Security:AES

Description

create AES Key from password

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] argv) throws Exception {
        String password = "java2s.com";
        System.out.println(createKey(password));
    }/*from ww w .j  av  a  2s . com*/

    public static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer(16);
        sb.append(password);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }
}

Related Tutorials