javax.crypto.ShortBufferException Java Examples

The following examples show how to use javax.crypto.ShortBufferException. 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: JavaVelocityCipher.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void process(ByteBuf source, ByteBuf destination) throws ShortBufferException {
  ensureNotDisposed();

  int inBytes = source.readableBytes();
  ByteBuf asHeapBuf = asHeapBuf(source);

  int outputSize = cipher.getOutputSize(inBytes);
  if (!destination.hasArray()) {
    byte[] outBuf = new byte[outputSize];
    cipher.update(asHeapBuf.array(), asHeapBuf.arrayOffset(), inBytes, outBuf);
    destination.writeBytes(outBuf);
  } else {
    // If the destination we write to is an array, we can use the backing array directly.
    destination.ensureWritable(outputSize);
    int produced = cipher.update(asHeapBuf.array(), asHeapBuf.arrayOffset(), inBytes,
        destination.array(), destination.arrayOffset());
    destination.writerIndex(destination.writerIndex() + produced);
  }
}
 
Example #2
Source File: TestCipher.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
 
Example #3
Source File: ISO10126Padding.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    byte[] padding = new byte[len - 1];
    SunJCE.getRandom().nextBytes(padding);
    System.arraycopy(padding, 0, in, off, len - 1);
    in[idx - 1] = paddingOctet;
    return;
}
 
Example #4
Source File: PKCS5Padding.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    Arrays.fill(in, off, idx, paddingOctet);
    return;
}
 
Example #5
Source File: CipherNCFuncTest.java    From dragonwell8_jdk 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 #6
Source File: TestCipher.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
 
Example #7
Source File: ISO10126Padding.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    byte[] padding = new byte[len - 1];
    SunJCE.getRandom().nextBytes(padding);
    System.arraycopy(padding, 0, in, off, len - 1);
    in[idx - 1] = paddingOctet;
    return;
}
 
Example #8
Source File: ISO10126Padding.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    byte[] padding = new byte[len - 1];
    SunJCE.getRandom().nextBytes(padding);
    System.arraycopy(padding, 0, in, off, len - 1);
    in[idx - 1] = paddingOctet;
    return;
}
 
Example #9
Source File: PKCS5Padding.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    Arrays.fill(in, off, idx, paddingOctet);
    return;
}
 
Example #10
Source File: CipherNCFuncTest.java    From TencentKona-8 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 #11
Source File: TestCipher.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
 
Example #12
Source File: PKCS5Padding.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    int idx = Math.addExact(off, len);
    if (idx > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    Arrays.fill(in, off, idx, paddingOctet);
    return;
}
 
Example #13
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 #14
Source File: PKCS5Padding.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds the given number of padding bytes to the data input.
 * The value of the padding bytes is determined
 * by the specific padding mechanism that implements this
 * interface.
 *
 * @param in the input buffer with the data to pad
 * @param off the offset in <code>in</code> where the padding bytes
 * are appended
 * @param len the number of padding bytes to add
 *
 * @exception ShortBufferException if <code>in</code> is too small to hold
 * the padding bytes
 */
public void padWithLen(byte[] in, int off, int len)
    throws ShortBufferException
{
    if (in == null)
        return;

    if ((off + len) > in.length) {
        throw new ShortBufferException("Buffer too small to hold padding");
    }

    byte paddingOctet = (byte) (len & 0xff);
    for (int i = 0; i < len; i++) {
        in[i + off] = paddingOctet;
    }
    return;
}
 
Example #15
Source File: AESUtilsJCA.java    From fingen with Apache License 2.0 6 votes vote down vote up
public void cryptUpdate(byte[] in, int length) {
	try {
		/*
		 * We must implement CTR mode by hand, because WinZip's AES encryption
		 * scheme is incompatible with Java's AES/CTR/NoPadding.
		 */
		for (int i = 0; i < length; ++i) {
			/*
			 * If we've exhausted the current keystream block, we need to
			 * increment the iv and generate another one.
			 */
			if (next == BLOCK_SIZE) {
				for (int j = 0; j < BLOCK_SIZE; ++j)
					if (++iv[j] != 0)
						break;
				cipher.update(iv, 0, BLOCK_SIZE, keystream);
				next = 0;
			}

			in[i] ^= keystream[next++];
		}
	} catch (ShortBufferException e) {
		/* Shouldn't happen: our output buffer is always appropriately sized. */
		throw new Error();
	}
}
 
Example #16
Source File: EncryptionDecoder.java    From Cleanstone with MIT License 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    Connection connection = ctx.channel().attr(AttributeKey.<Connection>valueOf("connection")).get();
    SecretKey sharedSecret = connection.getSharedSecret();
    if (cipher == null) {
        cipher = Cipher.getInstance("AES/CFB8/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, sharedSecret, new IvParameterSpec(sharedSecret.getEncoded()));
    }
    ByteBuffer outNioBuf = ByteBuffer.allocate(in.readableBytes());
    try {
        cipher.update(in.nioBuffer(), outNioBuf);
    } catch (ShortBufferException e) {
        throw new DecoderException("encryption output buffer too small", e);
    }
    outNioBuf.flip();
    out.add(Unpooled.wrappedBuffer(outNioBuf));
}
 
Example #17
Source File: NativeVelocityCipher.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void process(ByteBuf source, ByteBuf destination) throws ShortBufferException {
  ensureNotDisposed();
  source.memoryAddress();
  destination.memoryAddress();

  // The exact amount we read in is also the amount we write out.
  int len = source.readableBytes();
  destination.ensureWritable(len);

  impl.process(ctx, source.memoryAddress() + source.readerIndex(), len,
      destination.memoryAddress() + destination.writerIndex(), encrypt);

  source.skipBytes(len);
  destination.writerIndex(destination.writerIndex() + len);
}
 
Example #18
Source File: SSLCipher.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Plaintext decrypt(byte contentType, ByteBuffer bb,
        byte[] sequence) throws GeneralSecurityException {
    int len = bb.remaining();
    int pos = bb.position();
    ByteBuffer dup = bb.duplicate();
    try {
        if (len != cipher.update(dup, bb)) {
            // catch BouncyCastle buffering error
            throw new RuntimeException(
                    "Unexpected number of plaintext bytes");
        }
        if (bb.position() != dup.position()) {
            throw new RuntimeException(
                    "Unexpected ByteBuffer position");
        }
    } catch (ShortBufferException sbe) {
        // catch BouncyCastle buffering error
        throw new RuntimeException("Cipher buffering error in " +
            "JCE provider " + cipher.getProvider().getName(), sbe);
    }
    bb.position(pos);
    if (SSLLogger.isOn && SSLLogger.isOn("plaintext")) {
        SSLLogger.fine(
                "Plaintext after DECRYPTION", bb.duplicate());
    }

    MAC signer = (MAC)authenticator;
    if (signer.macAlg().size != 0) {
        checkStreamMac(signer, bb, contentType, sequence);
    } else {
        authenticator.increaseSequenceNumber();
    }

    return new Plaintext(contentType,
            ProtocolVersion.NONE.major, ProtocolVersion.NONE.minor,
            -1, -1L, bb.slice());
}
 
Example #19
Source File: AesFlushingCipher.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private int nonFlushingUpdate(byte[] in, int inOffset, int length, byte[] out, int outOffset) {
  try {
    return cipher.update(in, inOffset, length, out, outOffset);
  } catch (ShortBufferException e) {
    // Should never happen.
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String decryptKeyHandle(String keyHandleWithIV) throws DecoderException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeySpecException, SignatureException {

        //get secure element key to decrypt
        byte[] Seckeybytes = Hex.decodeHex(CSConstants.SECURE_ELEMENT_SECRET_KEY.toCharArray());
        SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");

        byte[] receivedkeyHandle = DatatypeConverter.parseBase64Binary(keyHandleWithIV);

        //get IV
        byte[] receivedIV = new byte[16];
        System.arraycopy(receivedkeyHandle, 0, receivedIV, 0, 16);

        //unwrap the key handle
        //get the wrapped key handle bytes
        byte[] wrappedKeyHandleBytes = new byte[receivedkeyHandle.length - receivedIV.length];
        System.arraycopy(receivedkeyHandle, receivedIV.length, wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length);

        //unwrapping received key handle
        //decrypt
        Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
        IvParameterSpec ivspec = new IvParameterSpec(receivedIV);
        cipher1.init(Cipher.DECRYPT_MODE, sks, ivspec);

        byte[] receivedunwrappedKeyHandle = new byte[cipher1.getOutputSize(wrappedKeyHandleBytes.length)];
        int p = cipher1.update(wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length, receivedunwrappedKeyHandle, 0);
        cipher1.doFinal(receivedunwrappedKeyHandle, p);

        //put decrypted key in a BCPrivate key object //to test
        String privateKey = keyHandleDecode(new String(receivedunwrappedKeyHandle, "UTF-8"), 0); //0 for key
        byte[] prk = Base64.decodeBase64(privateKey);

        //get private key into BC understandable form -- test working
        ECPrivateKeySpec ecpks = new ECPrivateKeySpec(new BigInteger(prk), null);
        KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
        PrivateKey privatetest = kf.generatePrivate(ecpks);

        return new String(receivedunwrappedKeyHandle, "UTF-8");

    }
 
Example #21
Source File: NettyEncryptionTranslator.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
protected ByteBuf decipher(ChannelHandlerContext ctx, ByteBuf buffer) throws ShortBufferException {
	int i = buffer.readableBytes();
	byte[] abyte = this.func_150502_a(buffer);
	ByteBuf bytebuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(i));
	bytebuf.writerIndex(this.cipher.update(abyte, 0, i, bytebuf.array(), bytebuf.arrayOffset()));
	return bytebuf;
}
 
Example #22
Source File: NettyEncryptionTranslator.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
protected void cipher(ByteBuf in, ByteBuf out) throws ShortBufferException {
	int i = in.readableBytes();
	byte[] abyte = this.func_150502_a(in);
	int j = this.cipher.getOutputSize(i);

	if (this.field_150506_c.length < j) {
		this.field_150506_c = new byte[j];
	}

	out.writeBytes(this.field_150506_c, 0, this.cipher.update(abyte, 0, i, this.field_150506_c));
}
 
Example #23
Source File: SSLCipher.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int encrypt(byte contentType, ByteBuffer bb) {
    // add message authentication code
    MAC signer = (MAC)authenticator;
    if (signer.macAlg().size != 0) {
        addMac(signer, bb, contentType);
    } else {
        authenticator.increaseSequenceNumber();
    }

    if (SSLLogger.isOn && SSLLogger.isOn("plaintext")) {
        SSLLogger.finest(
            "Padded plaintext before ENCRYPTION", bb.duplicate());
    }

    int len = bb.remaining();
    ByteBuffer dup = bb.duplicate();
    try {
        if (len != cipher.update(dup, bb)) {
            // catch BouncyCastle buffering error
            throw new RuntimeException(
                    "Unexpected number of plaintext bytes");
        }
        if (bb.position() != dup.position()) {
            throw new RuntimeException(
                    "Unexpected ByteBuffer position");
        }
    } catch (ShortBufferException sbe) {
        // catch BouncyCastle buffering error
        throw new RuntimeException("Cipher buffering error in " +
            "JCE provider " + cipher.getProvider().getName(), sbe);
    }

    return len;
}
 
Example #24
Source File: JavaVelocityCipher.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public ByteBuf process(ChannelHandlerContext ctx, ByteBuf source) throws ShortBufferException {
  ensureNotDisposed();

  int inBytes = source.readableBytes();
  ByteBuf asHeapBuf = asHeapBuf(source);

  ByteBuf out = ctx.alloc().heapBuffer(cipher.getOutputSize(inBytes));
  out.writerIndex(cipher.update(asHeapBuf.array(), asHeapBuf.arrayOffset(), inBytes, out.array(),
      out.arrayOffset()));
  return out;
}
 
Example #25
Source File: CryptoUtils.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
static byte[] runCipher(Cipher cipher, byte[] input) {
    final byte[] output = new byte[cipher.getOutputSize(input.length)];

    try {
        cipher.doFinal(input, 0, input.length, output);
    } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
        throw new Error(e);
    }

    return output;
}
 
Example #26
Source File: SecKFTranslateTest.java    From dragonwell8_jdk 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 #27
Source File: AesFlushingCipher.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private int nonFlushingUpdate(byte[] in, int inOffset, int length, byte[] out, int outOffset) {
  try {
    return cipher.update(in, inOffset, length, out, outOffset);
  } catch (ShortBufferException e) {
    // Should never happen.
    throw new RuntimeException(e);
  }
}
 
Example #28
Source File: AuthenticationHelper.java    From alexa-web-information-service-api-samples with MIT License 5 votes vote down vote up
/**
 * @param info   REQUIRED
 * @param length REQUIRED
 * @param output REQUIRED
 * @param offset REQUIRED
 * @throws ShortBufferException
 */
private void deriveKey(byte[] info, int length, byte[] output, int offset)
        throws ShortBufferException {
    this.assertInitialized();
    if (length < 0) {
        throw new IllegalArgumentException("Length must be a non-negative value.");
    } else if (output.length < offset + length) {
        throw new ShortBufferException();
    } else {
        final Mac mac = this.createMac();
        if (length > MAX_KEY_SIZE * mac.getMacLength()) {
            throw new IllegalArgumentException(
                    "Requested keys may not be longer than 255 times the underlying HMAC length.");
        } else {
            byte[] t = EMPTY_ARRAY;

            try {
                int loc = 0;

                for (byte i = 1; loc < length; ++i) {
                    mac.update(t);
                    mac.update(info);
                    mac.update(i);
                    t = mac.doFinal();

                    for (int x = 0; x < t.length && loc < length; ++loc) {
                        output[loc] = t[x];
                        ++x;
                    }
                }
            } finally {
                Arrays.fill(t, (byte) 0);
            }

        }
    }
}
 
Example #29
Source File: AuthenticationHelper.java    From alexa-web-information-service-api-samples with MIT License 5 votes vote down vote up
/**
 * @param info   REQUIRED
 * @param length REQUIRED
 * @return converted bytes.
 */
private byte[] deriveKey(byte[] info, int length) {
    final byte[] result = new byte[length];

    try {
        this.deriveKey(info, length, result, 0);
        return result;
    } catch (final ShortBufferException var5) {
        throw new RuntimeException(var5);
    }
}
 
Example #30
Source File: SecKFTranslateTest.java    From TencentKona-8 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);
    }

}