des Encrypt byte array key and byte array data - Android java.security

Android examples for java.security:DES

Description

des Encrypt byte array key and byte array data

Demo Code


//package com.java2s;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;

import java.security.*;
import java.security.spec.InvalidKeySpecException;

public class Main {
    public static byte[] desEncrypt(byte[] data, byte[] keyData) {
        return des(Cipher.ENCRYPT_MODE, data, keyData);
    }/*ww  w  .  jav a  2s.  c  o  m*/

    private static byte[] des(int mode, byte[] data, byte[] keyData) {
        byte[] ret = null;

        if (data != null && data.length > 0 && keyData != null
                && keyData.length == 8) {

            try {
                Cipher cipher = Cipher.getInstance("DES");
                DESKeySpec keySpec = new DESKeySpec(keyData);
                SecretKeyFactory keyFactory = SecretKeyFactory
                        .getInstance("DES");

                SecretKey key = keyFactory.generateSecret(keySpec);
                cipher.init(mode, key);

                ret = cipher.doFinal(data);

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

        return ret;
    }
}

Related Tutorials