DES Plain Text decryption - Android java.security

Android examples for java.security:DES

Description

DES Plain Text decryption

Demo Code


//package com.java2s;
import java.net.URLDecoder;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import android.util.Base64;

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

    public static String decryption(String secretData) throws Exception {
        return decryption(secretData, DES_PASSWORD);
    }//  w w w.jav a 2  s. c  om

    public static String decryption(String secretData, String secretKey)
            throws Exception {

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(DES_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new Exception("NoSuchAlgorithmException", e);
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            throw new Exception("NoSuchPaddingException", e);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new Exception("InvalidKeyException", e);

        }

        try {

            byte[] buf = cipher
                    .doFinal(Base64.decode(
                            URLDecoder.decode(secretData, "UTF-8"),
                            Base64.DEFAULT));

            return new String(buf);

        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new Exception("IllegalBlockSizeException", e);
        } catch (BadPaddingException e) {
            e.printStackTrace();
            throw new Exception("BadPaddingException", e);
        }
    }

    private static Key generateKey(String secretKey) throws Exception {
        byte[] DESkey = new String(secretKey).getBytes();// 
        DESKeySpec keySpec = new DESKeySpec(DESkey);// 
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 
        return keyFactory.generateSecret(keySpec);// 

    }
}

Related Tutorials