DES encrypt ECB Source - Java Security

Java examples for Security:DES

Description

DES encrypt ECB Source

Demo Code


//package com.java2s;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Main {
    public static void main(String[] argv) throws Exception {
        String source = "java2s.com";
        System.out.println(encryptECBSource(source));
    }//from w w w .  jav a  2 s  .  c o  m

    public static final String PUBLIC_KEY = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4";

    public static String encryptECBSource(String source) throws Exception {
        byte[] key = new BASE64Decoder().decodeBuffer(PUBLIC_KEY);
        byte[] sourceBytes = source.getBytes("UTF-8");
        byte[] encryptBytes = des3EncodeECB(key, sourceBytes);
        String encrypt = new BASE64Encoder().encode(encryptBytes);

        return encrypt;
    }

    public static byte[] des3EncodeECB(byte[] key, byte[] data)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory
                .getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
}

Related Tutorials