des3 Decrypt byte array data with string key and charset setting - Java Security

Java examples for Security:DES

Description

des3 Decrypt byte array data with string key and charset setting

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] cipherText = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        String key = "java2s.com";
        String charset = "java2s.com";
        System.out.println(des3Decrypt(cipherText, key, charset));
    }//  www .  j  a  v  a2  s. c  om

    public static String des3Decrypt(byte[] cipherText, String key,
            String charset) {
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(charset),
                    "DESede");

            /*
             KeyGenerator kg = KeyGenerator.getInstance("DESede");
             // kg.init(56);
             kg.init(new SecureRandom(key.getBytes(charset)));
             SecretKey secretKey = kg.generateKey();
             */

            Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            c1.init(Cipher.DECRYPT_MODE, secretKey); //??????????
            byte[] bytes = c1.doFinal(cipherText);
            return new String(bytes, charset);

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related Tutorials