Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

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

import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;

public class Main {
    /**
     * Encrypts message string using a given symmetric key.
     * @param msg Message string to encrypt.
     * @param key Key to encrypt message with.
     * @return Byte array of encrypted and encoded message.
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws InvalidAlgorithmParameterException
     */
    public static byte[] encryptMessage(String msg, SecretKey key)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance("AES");
        byte[] init = new byte[128 / 8];
        //SecureRandom secureRandom = new SecureRandom();
        //secureRandom.nextBytes(init);
        for (int i = 0; i < 16; i++)
            init[i] = 0;
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(init));
        byte[] msgBytes = msg.getBytes();
        //System.out.println(android.util.Base64.encode(msgBytes, Base64.DEFAULT));
        byte[] msgCipherBytes = cipher.doFinal(msgBytes);
        return msgCipherBytes;
    }
}