encode ECB Bytes - Java Security

Java examples for Security:DES

Description

encode ECB Bytes

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";

    public static byte[] encodeECBBytes(String key, String plainText)
            throws Exception {
        SecretKey secretkey = new SecretKeySpec(key.getBytes(), "DES");
        return encrypt(plainText.getBytes(), secretkey);
    }//from  w w w  .j  a  v  a 2 s. c o  m

    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