encrypt Triple DES - Android java.security

Android examples for java.security:DES

Description

encrypt Triple DES

Demo Code


//package com.java2s;

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

import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main {
    public static byte[] encryptTripleDES(byte[] key, byte[] data, byte[] iv) {
        if (key.length < 24) {
            byte[] master = key;
            key = new byte[24];
            System.arraycopy(master, 0, key, 0, master.length);
            System.arraycopy(master, 0, key, master.length, key.length
                    - master.length);//from w  w  w . ja v  a2s . c  o m
            // DLog.d("SecureSession.encryptData KEY: "+convertBytesToHexString(key));
        }
        if (iv == null) {
            iv = new byte[8];
        }
        try {
            DESedeKeySpec keySpec = new DESedeKeySpec(key);
            SecretKey secret = SecretKeyFactory.getInstance("DESede")
                    .generateSecret(keySpec);

            Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, secret,
                    new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials