Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static String desAlgorithm = "DESede/CBC/PKCS7Padding";
    private static byte defaultIV[] = { 50, 51, 52, 53, 54, 55, 56, 57 };

    private static byte[] encryptBy3Des(byte input[], byte key[]) throws Exception {

        try {
            return cryptBy3Des(input, key, 1, null);
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
    }

    private static byte[] cryptBy3Des(byte input[], byte key[], int cryptModel, byte iv[]) throws Exception {
        try {
            Key k = KeyGenerator(key);
            IvParameterSpec IVSpec = iv != null ? IvGenerator(iv) : IvGenerator(defaultIV);
            Cipher c = Cipher.getInstance(desAlgorithm);
            c.init(cryptModel, k, ((java.security.spec.AlgorithmParameterSpec) (IVSpec)));
            return c.doFinal(input);
        } catch (Exception e) {
            throw e;
        }
    }

    private static Key KeyGenerator(byte input[])
            throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {

        Key key = new SecretKeySpec(input, desAlgorithm);
        return key;
    }

    private static IvParameterSpec IvGenerator(byte[] b) {
        IvParameterSpec IV = new IvParameterSpec(b);
        return IV;
    }
}