decrypt Des String - Android java.security

Android examples for java.security:DES

Description

decrypt Des String

Demo Code


//package com.java2s;
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class Main {

    public static String decryptDesString(String key, String str) {
        return new String(getDesCode(key, hex2byte(str.getBytes())));
    }//  w w w .  j ava2s.co  m

    private static byte[] getDesCode(String key, byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, newDesInstance(key));
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    private static Key newDesInstance(String strKey) {
        Key key = null;
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(new SecureRandom(strKey.getBytes()));
            key = keyGenerator.generateKey();
            keyGenerator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }
}

Related Tutorials