Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private final static String HEX = "0123456789ABCDEF";

    public static String encode(String key, String cleartext) throws Exception {
        SecretKeySpec secretKeySpec = createKey(key);
        IvParameterSpec ivSpec = new IvParameterSpec(HEX.getBytes());
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
        String result = parseByte2HexStr(c.doFinal(cleartext.getBytes("UTF-8")));

        return result;
    }

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

    private static String parseByte2HexStr(byte[] buf) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0XFF);
            if (hex.length() == 1) {
                //            hex = '0' + hex;
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }
}