DES decrypt String data with key - Android java.security

Android examples for java.security:DES

Description

DES decrypt String data with key

Demo Code


//package com.java2s;
import android.util.Base64;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Main {
    private final static String DES = "DES";

    public static String decrypt(String key, String data)
            throws IOException, Exception {
        if (data == null)
            return null;
        byte[] buf = Base64.decode(data.getBytes(), Base64.DEFAULT);
        byte[] bt = decrypt(buf, key.getBytes());
        return new String(bt);
    }/*from  w  ww. java2s  . c o m*/

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();

        DESKeySpec dks = new DESKeySpec(key);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance(DES);

        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }
}

Related Tutorials