decrypt DES - Java Security

Java examples for Security:DES

Description

decrypt DES

Demo Code


//package com.java2s;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

    public static String decryptDES(String decryptString, String decryptKey)
            throws Exception {
        //            byte[] byteMi = new Base64().decode(decryptString);
        byte[] byteMi = String2Byte(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);

        return new String(decryptedData);
    }/*  w ww . j  av a2  s  .c  o m*/

    public static byte[] String2Byte(String hexString) {
        if (hexString.length() % 2 == 1)
            return null;
        byte[] ret = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            ret[i / 2] = Integer.decode(
                    "0x" + hexString.substring(i, i + 2)).byteValue();
        }
        return ret;
    }
}

Related Tutorials