Encrypts the given message using the given key with AES-CBC, and writes to the supplied stream. - Java Security

Java examples for Security:AES

Description

Encrypts the given message using the given key with AES-CBC, and writes to the supplied stream.

Demo Code


//package com.java2s;
import java.io.*;

import javax.crypto.*;
import javax.crypto.spec.*;

public class Main {
    /**//from   w  w w. j  a v  a  2 s.  co  m
     * Encrypts the given message using the given key with AES-CBC, and writes to 
     * the supplied stream.
     *
     * @param message  the message (in bytes)
     * @param keySpec  the secret key
     * @param out  the output stream
     * @throws IOException
     */
    public static void encryptAndSend(byte[] message,
            SecretKeySpec keySpec, DataOutputStream out) throws IOException {
        // encrypt the message
        byte[] ciphertext = encrypt(message, keySpec);

        // send the message
        send(ciphertext, out);
    }

    /**
     * Encrypts the given message using the given key with AES-CBC.
     *
     * @param message  the message (in bytes)
     * @param keySpec  the secret key
     * @return encrypted message (with algorithm parameters appended
     */
    public static byte[] encrypt(byte[] message, SecretKeySpec keySpec) {
        byte[] ret = null;

        try {
            // Initialize the cipher with the given key
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            // encrypt the message
            byte[] cipherText = cipher.doFinal(message);
            byte[] params = cipher.getParameters().getEncoded();

            // Combine the ciphertext and cipher parameters into one byte array
            ret = new byte[cipherText.length + params.length];
            System.arraycopy(cipherText, 0, ret, 0, cipherText.length);
            System.arraycopy(params, 0, ret, cipherText.length,
                    params.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * Writes the given message to the supplied stream.
     *
     * @param message  the message (in bytes)
     * @param out  the output stream
     * @throws IOException
     */
    public static void send(byte[] message, DataOutputStream out)
            throws IOException {
        // send the length of the encrypted message
        out.writeInt(message.length);

        // send the encrypted message bytes
        out.write(message);

        // flush the stream
        out.flush();
    }
}

Related Tutorials