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 decode(String key, String ciphertext) throws Exception {
        byte[] bs = parseHexStr2Byte(ciphertext);
        IvParameterSpec ivSpec = new IvParameterSpec(HEX.getBytes());
        SecretKeySpec secretKeySpec = createKey(key);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);
        return new String(c.doFinal(bs), "UTF-8");
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr == null || hexStr.length() == 0) {
            return null;
        }
        int len = hexStr.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            // int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1),16);
            // int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 +2),16);
            // result[i] = (byte) (high * 16 + low);
            result[i] = (byte) (Integer.parseInt(hexStr.substring(2 * i, 2 * i + 2), 16) & 0XFF);
        }
        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");
    }
}