Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Main {
    public static byte[] encrypt(byte[] byteArray, PrivateKey privateKey) {
        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            /*
               (define cipher (javax.crypto.Cipher.getInstance "RSA/ECB/NoPadding"))
             */
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        ByteArrayInputStream input = new ByteArrayInputStream(byteArray);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {

            while (input.available() != 0) {
                byte[] t0 = new byte[100];
                input.read(t0);
                output.write(cipher.doFinal(t0));
            }
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return output.toByteArray();
    }
}