Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.util.Base64;

import java.security.SecureRandom;
import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class Main {

    public static String TripleDES_Transformation = "DESede/ECB/NoPadding";
    private static final String TripleDES_Algorithm = "DESede";

    public static byte[] encrypt3DES2Base64(byte[] data, byte[] key) {
        return base64Encode(encrypt3DES(data, key));
    }

    private static byte[] base64Encode(byte[] input) {
        return Base64.encode(input, Base64.NO_WRAP);
    }

    public static byte[] encrypt3DES(byte[] data, byte[] key) {
        return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, true);
    }

    public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, String transformation,
            boolean isEncrypt) {
        if (data == null || data.length == 0 || key == null || key.length == 0)
            return null;
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
            Cipher cipher = Cipher.getInstance(transformation);
            SecureRandom random = new SecureRandom();
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random);
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}