encode ECB As Hex String - Java Security

Java examples for Security:Key

Description

encode ECB As Hex String

Demo Code


//package com.java2s;

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

public class Main {
    private final static String xform = "DES/ECB/NoPadding";
    private final static byte[] hex = "0123456789ABCDEF".getBytes();

    public static String encodeECBAsHexString(String key, String plainText)
            throws Exception {
        return Bytes2HexString(encodeECBBytes(key, plainText));
        //return ecodeBase64(encodeECBBytes(key, plainText));
    }/* ww  w .  ja va 2 s.c  o m*/

    public static String Bytes2HexString(byte[] b) {
        byte[] buff = new byte[2 * b.length];
        for (int i = 0; i < b.length; i++) {
            buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
            buff[2 * i + 1] = hex[b[i] & 0x0f];
        }
        return new String(buff);
    }

    public static byte[] encodeECBBytes(String key, String plainText)
            throws Exception {
        SecretKey secretkey = new SecretKeySpec(key.getBytes(), "DES");
        return encrypt(plainText.getBytes(), secretkey);
    }

    static byte[] encrypt(byte[] inpBytes, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(xform);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 2010/6/22 added by peter, must multiple of 8 bytes
        return cipher.doFinal(padbyte(inpBytes));
    }

    static byte[] padbyte(byte[] b) {
        int pad = b.length % 8;
        if (pad > 0)
            pad = 8 - pad;
        byte[] newbytes = new byte[b.length + pad];
        for (int i = 0; i < b.length; i++)
            newbytes[i] = b[i];
        for (int i = 0; i < pad; i++)
            newbytes[b.length + i] = 0;
        return newbytes;
    }
}

Related Tutorials