DES decode String Value - Android java.security

Android examples for java.security:DES

Description

DES decode String Value

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

public class Main {
    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    public static String decodeValue(String key, String data) {
        byte[] datas;
        String value = null;//from  w  ww .  j av a  2 s.  c  om
        try {

            datas = decode(key,
                    Base64.decode(data.getBytes(), Base64.DEFAULT));

            value = new String(datas);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }

    public static byte[] decode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("DES");

            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}

Related Tutorials