DES Plain text encryption - Android java.security

Android examples for java.security:DES

Description

DES Plain text encryption

Demo Code


//package com.java2s;

import java.net.URLEncoder;
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 encryption(String plainData) throws Exception {
        return encryption(plainData, DES_PASSWORD);
    }// ww w.java 2s.  c  om

    public static String encryption(String plainData, String secretKey)
            throws Exception {

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

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {

        }

        try {
            byte[] buf = cipher.doFinal(plainData.getBytes());

            return URLEncoder.encode(new String(Base64.encode(buf,
                    Base64.DEFAULT)));

        } 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