encrypt Triple DES ECB - Android java.security

Android examples for java.security:DES

Description

encrypt Triple DES ECB

Demo Code


//package com.java2s;

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

import javax.crypto.spec.DESedeKeySpec;

public class Main {
    public static byte[] encryptTripleDESECB(byte[] key, byte[] data) {
        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);/*  w  w w .  jav  a  2s. c  o  m*/
            // DLog.d("SecureSession.encryptData KEY: "+convertBytesToHexString(key));
        }
        try {
            DESedeKeySpec keySpec = new DESedeKeySpec(key);
            SecretKey secret = SecretKeyFactory.getInstance("DESede")
                    .generateSecret(keySpec);

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

Related Tutorials