Pads an array of bytes inline with the given padding scheme - Java java.lang

Java examples for java.lang:byte Array

Description

Pads an array of bytes inline with the given padding scheme

Demo Code


import java.util.zip.DataFormatException;

public class Main{
    /**//from w w  w  .ja v a 2  s  .co  m
     * Pads an array of bytes inline with the given padding scheme
     * Currently only supports PKCS5
     * 
     * @param bytes - Array of bytes to pad
     * @param k - KeySize
     * @param p - Padding type
     * @return bytes - Padding array of bytes
     * @throws DataFormatException
     */
    public static byte[] pad(byte[] bytes, KeySize k)
            throws DataFormatException {
        // PKCS#5 Padding
        // See RFC 2898

        // Figure out how many bytes to append by working out:
        //   Block Size - (bytes length mod block size) 
        byte[] new_plaintext = new byte[bytes.length
                + (16 - (bytes.length % 16))];
        System.arraycopy(bytes, 0, new_plaintext, 0, bytes.length);

        // As defined in PKCS#5
        // Each of the padding bytes are set to the value of the number of padding bytes
        // rather than the usual 0, so that when we unpad we can figure out how many
        // bytes to remove
        for (int i = bytes.length; i < new_plaintext.length; i++)
            new_plaintext[i] = (byte) (16 - (bytes.length % 16));

        return new_plaintext;
    }
}

Related Tutorials