Java Code Examples for javax.crypto.Cipher#getOutputSize()

The following examples show how to use javax.crypto.Cipher#getOutputSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Encrypt.java    From jdk8u-jdk with GNU General Public License v2.0 8 votes vote down vote up
private void combination_2(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    c.updateAAD(AAD);
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }
    byte[] part21 = c.update(plainText, 0, t);
    byte[] part22 = new byte[c.getOutputSize(plainText.length)];
    int len2 = c.doFinal(plainText, t, offset, part22, 0);
    int part21Length = part21 != null ? part21.length : 0;
    byte[] outputText2 = new byte[part21Length + len2];
    if (part21 != null) {
        System.arraycopy(part21, 0, outputText2, 0, part21Length);
    }
    System.arraycopy(part22, 0, outputText2, part21Length, len2);
    results.add(outputText2);
}
 
Example 2
Source File: CipherNCFuncTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    byte[] plainText = new byte[801];
    // Initialization
    RandomFactory.getRandom().nextBytes(plainText);
    Cipher ci = new NullCipher();
    // Encryption
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // Decryption
    byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
    int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText);
    // Comparison
    if (len != plainText.length ||
            !TestUtilities.equalsBlock(plainText, cipherText, len) ||
            !TestUtilities.equalsBlock(plainText, recoveredText, len)) {
        throw new RuntimeException(
            "Test failed because plainText not equal to cipherText and revoveredText");
    }
}
 
Example 3
Source File: DefaultCryptor.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt the plain text password.
 * <p>
 * Warning: This uses AES128 with a fixed encryption key. This is only an obfuscation no cryptographic secure
 * protection.
 *
 * @param plainKey The password.
 * @return The encrypted password String.
 * @throws Exception If an error occurs.
 */
@Override
public String encrypt(final String plainKey) throws Exception {
    final byte[] input = plainKey.getBytes();
    final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");

    final Cipher cipher = Cipher.getInstance("AES");

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);

    final byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    return encode(cipherText);
}
 
Example 4
Source File: SameBuffer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void doTestWithSeparateArrays(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare buffers to test
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset * 2;

    byte[] inputText = Helper.generateBytes(outputBufSize);
    byte[] AAD = Helper.generateBytes(AADLength);

    // do the test
    runGCMWithSeparateArray(Cipher.ENCRYPT_MODE, AAD, inputText, offset * 2,
            textLength, offset, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    runGCMWithSeparateArray(Cipher.DECRYPT_MODE, AAD, inputText, offset,
            textLength + tagLength, offset, params);
}
 
Example 5
Source File: Encrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(buf);

    // prepare an empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocate(0);
    emptyBuf.put(new byte[0]);
    ci.updateAAD(emptyBuf);
    byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len12 = ci.update(plainText, 0, plainText.length - offset,
            part12_1, 0);
    int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
            part12_1, len12);
    byte[] outputText12 = new byte[len12 + rest12];
    System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
    results.add(outputText12);
}
 
Example 6
Source File: SecureUtil.java    From pay with Apache License 2.0 6 votes vote down vote up
public static byte[] decryptedPin(PrivateKey privateKey, byte[] cryptPin) throws Exception {
    try {
        byte[] e = base64Decode(cryptPin);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
        cipher.init(2, privateKey);
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(e.length);
        int leavedSize = e.length % blockSize;
        int blocksSize = leavedSize != 0?e.length / blockSize + 1:e.length / blockSize;
        byte[] pinData = new byte[outputSize * blocksSize];

        for(int i = 0; e.length - i * blockSize > 0; ++i) {
            if(e.length - i * blockSize > blockSize) {
                cipher.doFinal(e, i * blockSize, blockSize, pinData, i * outputSize);
            } else {
                cipher.doFinal(e, i * blockSize, e.length - i * blockSize, pinData, i * outputSize);
            }
        }

        return pinData;
    } catch (Exception var10) {
        logger.error("解密失败", var10);
        return null;
    }
}
 
Example 7
Source File: SameBuffer.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void doTestWithSameBuffer(int offset, AlgorithmParameters params)
        throws Exception {
    // calculate output length
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);

    // prepare byte buffer contained AAD and plain text
    int bufSize = AADLength + offset + outputLength;
    byte[] AAD_and_Text = Helper.generateBytes(bufSize);
    ByteBuffer AAD_and_Text_Buf = ByteBuffer.allocate(bufSize);
    AAD_and_Text_Buf.put(AAD_and_Text, 0, AAD_and_Text.length);

    // do test
    runGCMWithSameBuffer(Cipher.ENCRYPT_MODE, AAD_and_Text_Buf, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    AAD_and_Text_Buf.limit(AADLength + offset + textLength + tagLength);
    runGCMWithSameBuffer(Cipher.DECRYPT_MODE, AAD_and_Text_Buf, offset,
            textLength + tagLength, params);

}
 
Example 8
Source File: Encrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void combination_2(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    c.updateAAD(AAD);
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }
    byte[] part21 = c.update(plainText, 0, t);
    byte[] part22 = new byte[c.getOutputSize(plainText.length)];
    int len2 = c.doFinal(plainText, t, offset, part22, 0);
    int part21Length = part21 != null ? part21.length : 0;
    byte[] outputText2 = new byte[part21Length + len2];
    if (part21 != null) {
        System.arraycopy(part21, 0, outputText2, 0, part21Length);
    }
    System.arraycopy(part22, 0, outputText2, part21Length, len2);
    results.add(outputText2);
}
 
Example 9
Source File: SameBuffer.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doTestWithSeparatedBuffer(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare AAD byte buffers to test
    byte[] AAD = Helper.generateBytes(AADLength);
    ByteBuffer AAD_Buf = ByteBuffer.allocate(AADLength);
    AAD_Buf.put(AAD, 0, AAD.length);
    AAD_Buf.flip();

    // prepare text byte buffer to encrypt/decrypt
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset;
    byte[] inputText = Helper.generateBytes(outputBufSize);
    ByteBuffer plainTextBB = ByteBuffer.allocateDirect(inputText.length);
    plainTextBB.put(inputText);
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength);

    // do test
    runGCMWithSeparateBuffers(Cipher.ENCRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength + tagLength);
    runGCMWithSeparateBuffers(Cipher.DECRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength + tagLength, params);
}
 
Example 10
Source File: Encrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void combination_4(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD);
    byte[] part41 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part41, 0);
    int rest4 = ci.doFinal(plainText, plainText.length - offset, offset,
            part41, len);
    byte[] outputText4 = new byte[len + rest4];
    System.arraycopy(part41, 0, outputText4, 0, outputText4.length);
    results.add(outputText4);
}
 
Example 11
Source File: InstallKeyEncrypt.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public static byte[] encrypt(byte[] srcBytes) throws Exception {
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
	KeyFactory kf = KeyFactory.getInstance(algorithm);
	PublicKey keyPublic = kf.generatePublic(keySpec);

	Cipher cipher;
	cipher = Cipher.getInstance(algorithm,
			new org.bouncycastle.jce.provider.BouncyCastleProvider());

	cipher.init(Cipher.ENCRYPT_MODE, keyPublic);
	int blockSize = cipher.getBlockSize();
	int outputSize = cipher.getOutputSize(srcBytes.length);
	int leavedSize = srcBytes.length % blockSize;
	int blocksSize = leavedSize != 0 ? srcBytes.length / blockSize + 1
			: srcBytes.length / blockSize;
	byte[] raw = new byte[outputSize * blocksSize];
	int i = 0;
	while (srcBytes.length - i * blockSize > 0) {
		if (srcBytes.length - i * blockSize > blockSize)
			cipher.doFinal(srcBytes, i * blockSize, blockSize, raw, i
					* outputSize);
		else
			cipher.doFinal(srcBytes, i * blockSize, srcBytes.length - i
					* blockSize, raw, i * outputSize);
		i++;
	}
	return raw;
}
 
Example 12
Source File: SameBuffer.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void doTestWithSeparatedBuffer(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare AAD byte buffers to test
    byte[] AAD = Helper.generateBytes(AADLength);
    ByteBuffer AAD_Buf = ByteBuffer.allocate(AADLength);
    AAD_Buf.put(AAD, 0, AAD.length);
    AAD_Buf.flip();

    // prepare text byte buffer to encrypt/decrypt
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset;
    byte[] inputText = Helper.generateBytes(outputBufSize);
    ByteBuffer plainTextBB = ByteBuffer.allocateDirect(inputText.length);
    plainTextBB.put(inputText);
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength);

    // do test
    runGCMWithSeparateBuffers(Cipher.ENCRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength + tagLength);
    runGCMWithSeparateBuffers(Cipher.DECRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength + tagLength, params);
}
 
Example 13
Source File: Encrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void combination_11(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer1 to test
    ByteBuffer buf1 = ByteBuffer.allocate(AAD.length / 2);
    buf1.put(AAD, 0, AAD.length / 2);
    buf1.position(0);
    buf1.limit(AAD.length / 2);

    // get a Cipher object and do combination
    Cipher ci = createCipher(mode, params);

    // process the first half of AAD data
    ci.updateAAD(buf1);

    // prepare ByteBuffer2 to test
    ByteBuffer buf2 = ByteBuffer.allocate(AAD.length - AAD.length / 2);
    buf2.put(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    buf2.position(0);
    buf2.limit(AAD.length - AAD.length / 2);

    // process the rest of AAD data
    ci.updateAAD(buf2);

    // encrypt plain text
    byte[] part11_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len_11 = ci.update(plainText, 0, plainText.length - offset,
            part11_1, 0);
    byte[] part11_2 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText11 = new byte[len_11 + part11_2.length];
    System.arraycopy(part11_1, 0, outputText11, 0, len_11);
    System.arraycopy(part11_2, 0, outputText11, len_11, part11_2.length);
    results.add(outputText11);
}
 
Example 14
Source File: SameBuffer.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void doTestWithSeparatedBuffer(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare AAD byte buffers to test
    byte[] AAD = Helper.generateBytes(AADLength);
    ByteBuffer AAD_Buf = ByteBuffer.allocate(AADLength);
    AAD_Buf.put(AAD, 0, AAD.length);
    AAD_Buf.flip();

    // prepare text byte buffer to encrypt/decrypt
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset;
    byte[] inputText = Helper.generateBytes(outputBufSize);
    ByteBuffer plainTextBB = ByteBuffer.allocateDirect(inputText.length);
    plainTextBB.put(inputText);
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength);

    // do test
    runGCMWithSeparateBuffers(Cipher.ENCRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength + tagLength);
    runGCMWithSeparateBuffers(Cipher.DECRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength + tagLength, params);
}
 
Example 15
Source File: SecKFTranslateTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(Algorithm algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        InvalidKeySpecException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    AlgorithmParameterSpec[] aps = new AlgorithmParameterSpec[1];
    byte[] plainText = new byte[800];

    SecretKey key1 = algo.intSecurityKey(aps);
    Random random = new Random();
    // Initialization
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.toString(),
            SUN_JCE);

    random.nextBytes(plainText);
    Cipher ci = Cipher.getInstance(algo.toString(), SUN_JCE);
    // Encryption
    ci.init(Cipher.ENCRYPT_MODE, key1, aps[0]);
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // translate key
    SecretKey key2 = skf.translateKey(key1);

    // Decryption
    ci.init(Cipher.DECRYPT_MODE, key2, aps[0]);
    byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
    ci.doFinal(cipherText, 0, cipherText.length, recoveredText);

    // Comparison
    if (!Arrays.equals(plainText, recoveredText)) {
        System.out.println("Key1:" + new String(key1.getEncoded())
                + " Key2:" + new String(key2.getEncoded()));
        throw new RuntimeException("Testing translate key failed with "
                + algo);
    }

}
 
Example 16
Source File: Encrypt.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void combination_10(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length / 2);

    // get a Cipher object and do the combination
    Cipher c = createCipher(mode, params);

    // process the first half of AAD data
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prapare variables for the combination
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }

    // encrypt the text
    byte[] part10_1 = c.update(plainText, 0, t);
    int part10_1_Length = part10_1 != null ? part10_1.length : 0;
    byte[] part10_2 = new byte[c.getOutputSize(plainText.length)];
    int len2 = c.doFinal(plainText, t, offset, part10_2, 0);

    // form the combination's result
    byte[] outputText10 = new byte[part10_1_Length + len2];
    if (part10_1 != null) {
        System.arraycopy(part10_1, 0, outputText10, 0, part10_1_Length);
    }
    System.arraycopy(part10_2, 0, outputText10, part10_1_Length, len2);
    results.add(outputText10);
}
 
Example 17
Source File: DirectBBRemaining.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    boolean failedOnce = false;
    Exception failedReason = null;

    byte[] keyBytes = new byte[8];
    random.nextBytes(keyBytes);
    SecretKey key = new SecretKeySpec(keyBytes, "DES");

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    /*
     * Iterate through various sizes to make sure that the code does empty
     * blocks, single partial blocks, 1 full block, full + partial blocks,
     * multiple full blocks, etc. 5 blocks (using DES) is probably overkill
     * but will feel more confident the fix isn't breaking anything.
     */
    System.out.println("Output test results for every "
            + outputFrequency + " tests...");

    for (int size = 0; size <= testSizes; size++) {
        boolean output = (size % outputFrequency) == 0;
        if (output) {
            System.out.print("\nTesting buffer size: " + size + ":");
        }

        int outSize = cipher.getOutputSize(size);

        try {
            encrypt(cipher, size,
                    ByteBuffer.allocate(size),
                    ByteBuffer.allocate(outSize),
                    ByteBuffer.allocateDirect(size),
                    ByteBuffer.allocateDirect(outSize),
                    output);
        } catch (Exception e) {
            System.out.print("\n    Failed with size " + size);
            failedOnce = true;
            failedReason = e;

            // If we got an exception, let's be safe for future
            // testing and reset the cipher to a known good state.
            cipher.init(Cipher.ENCRYPT_MODE, key);
        }
    }
    if (failedOnce) {
        throw failedReason;
    }
    System.out.println("\nTest Passed...");
}
 
Example 18
Source File: Encrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void combination_10(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length / 2);

    // get a Cipher object and do the combination
    Cipher c = createCipher(mode, params);

    // process the first half of AAD data
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prapare variables for the combination
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }

    // encrypt the text
    byte[] part10_1 = c.update(plainText, 0, t);
    int part10_1_Length = part10_1 != null ? part10_1.length : 0;
    byte[] part10_2 = new byte[c.getOutputSize(plainText.length)];
    int len2 = c.doFinal(plainText, t, offset, part10_2, 0);

    // form the combination's result
    byte[] outputText10 = new byte[part10_1_Length + len2];
    if (part10_1 != null) {
        System.arraycopy(part10_1, 0, outputText10, 0, part10_1_Length);
    }
    System.arraycopy(part10_2, 0, outputText10, part10_1_Length, len2);
    results.add(outputText10);
}
 
Example 19
Source File: Encrypt.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void combination_10(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length / 2);

    // get a Cipher object and do the combination
    Cipher c = createCipher(mode, params);

    // process the first half of AAD data
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prapare variables for the combination
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }

    // encrypt the text
    byte[] part10_1 = c.update(plainText, 0, t);
    int part10_1_Length = part10_1 != null ? part10_1.length : 0;
    byte[] part10_2 = new byte[c.getOutputSize(plainText.length)];
    int len2 = c.doFinal(plainText, t, offset, part10_2, 0);

    // form the combination's result
    byte[] outputText10 = new byte[part10_1_Length + len2];
    if (part10_1 != null) {
        System.arraycopy(part10_1, 0, outputText10, 0, part10_1_Length);
    }
    System.arraycopy(part10_2, 0, outputText10, part10_1_Length, len2);
    results.add(outputText10);
}
 
Example 20
Source File: TestSymmCiphersNoPad.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void test(Cipher cipher, int mode, SecretKey key,
                         AlgorithmParameters params,
                         byte[] in, byte[] answer) throws Exception {
    // test setup
    debugBuf = new StringBuffer();
    cipher.init(mode, key, params);
    int outLen = cipher.getOutputSize(in.length);
    debugBuf.append("Estimated output size = " + outLen + "\n");

    // test data preparation
    ByteBuffer inBuf = ByteBuffer.allocate(in.length);
    inBuf.put(in);
    inBuf.position(0);
    ByteBuffer inDirectBuf = ByteBuffer.allocateDirect(in.length);
    inDirectBuf.put(in);
    inDirectBuf.position(0);
    ByteBuffer outBuf = ByteBuffer.allocate(outLen);
    ByteBuffer outDirectBuf = ByteBuffer.allocateDirect(outLen);

    // test#1: byte[] in + byte[] out
    debugBuf.append("Test#1:\n");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] testOut1 = cipher.update(in, 0, 16);
    if (testOut1 != null) baos.write(testOut1, 0, testOut1.length);
    testOut1 = cipher.doFinal(in, 16, in.length-16);
    if (testOut1 != null) baos.write(testOut1, 0, testOut1.length);
    testOut1 = baos.toByteArray();
    match(testOut1, answer);

    // test#2: Non-direct Buffer in + non-direct Buffer out
    debugBuf.append("Test#2:\n");
    debugBuf.append("inputBuf: " + inBuf + "\n");
    debugBuf.append("outputBuf: " + outBuf + "\n");
    cipher.update(inBuf, outBuf);
    cipher.doFinal(inBuf, outBuf);
    match(outBuf, answer);

    // test#3: Direct Buffer in + direc Buffer out
    debugBuf.append("Test#3:\n");
    debugBuf.append("(pre) inputBuf: " + inDirectBuf + "\n");
    debugBuf.append("(pre) outputBuf: " + outDirectBuf + "\n");
    cipher.update(inDirectBuf, outDirectBuf);
    cipher.doFinal(inDirectBuf, outDirectBuf);

    debugBuf.append("(post) inputBuf: " + inDirectBuf + "\n");
    debugBuf.append("(post) outputBuf: " + outDirectBuf + "\n");
    match(outDirectBuf, answer);

    // test#4: Direct Buffer in + non-direct Buffer out
    debugBuf.append("Test#4:\n");
    inDirectBuf.position(0);
    outBuf.position(0);
    debugBuf.append("inputBuf: " + inDirectBuf + "\n");
    debugBuf.append("outputBuf: " + outBuf + "\n");
    cipher.update(inDirectBuf, outBuf);
    cipher.doFinal(inDirectBuf, outBuf);
    match(outBuf, answer);

    // test#5: Non-direct Buffer in + direct Buffer out
    debugBuf.append("Test#5:\n");
    inBuf.position(0);
    outDirectBuf.position(0);

    debugBuf.append("(pre) inputBuf: " + inBuf + "\n");
    debugBuf.append("(pre) outputBuf: " + outDirectBuf + "\n");

    cipher.update(inBuf, outDirectBuf);
    cipher.doFinal(inBuf, outDirectBuf);

    debugBuf.append("(post) inputBuf: " + inBuf + "\n");
    debugBuf.append("(post) outputBuf: " + outDirectBuf + "\n");
    match(outDirectBuf, answer);

    // test#6: Streams
    debugBuf.append("Test#6: Streaming\n");
    outBuf.position(0);
    InputStream stream =
        new CipherInputStream(new ByteArrayInputStream(in), cipher);
    byte[] data = new byte[1024];
    int bytesRead = 0;
    try {
        while (bytesRead >= 0) {
            bytesRead = stream.read(data);
            if (bytesRead == -1)
                break;
            debugBuf.append("bytesRead: " + bytesRead);
            debugBuf.append("\toutBuf.position(): " + outBuf.position() +
                "\n");
            outBuf.put(data, 0 , bytesRead);
        }
    } catch (Exception ex) {
        debugBuf.append("Caught Exception during stream reading\n");
        throw ex;
    }
    match(outBuf, answer);

    debugBuf = null;
}