use of javax.crypto.ShortBufferException in project jdk8u_jdk by JetBrains.
the class CTR method runTest.
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
Random rdm = new Random();
byte[] plainText;
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
for (int i = 0; i < 15; i++) {
plainText = new byte[1600 + i + 1];
rdm.nextBytes(plainText);
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
} else {
ci.init(Cipher.ENCRYPT_MODE, key);
}
byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
ci.doFinal(cipherText, offset);
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.DECRYPT_MODE, key, aps);
} else {
ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
}
byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText);
byte[] tmp = new byte[len];
for (int j = 0; j < len; j++) {
tmp[j] = recoveredText[j];
}
Arrays.toString(plainText);
if (!java.util.Arrays.equals(plainText, tmp)) {
System.out.println("Original: ");
dumpBytes(plainText);
System.out.println("Recovered: ");
dumpBytes(tmp);
throw new RuntimeException("Original text is not equal with recovered text, with mode:" + mo);
}
}
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
use of javax.crypto.ShortBufferException in project CommandHelper by EngineHub.
the class CSecureString method construct.
private void construct(byte[] val) {
try {
SecureRandom rand = SecureRandom.getInstanceStrong();
byte[] keyBytes = new byte[24];
rand.nextBytes(keyBytes);
byte[] ivBytes = new byte[8];
SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher encrypter = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decrypter = Cipher.getInstance("DESede/CBC/PKCS5Padding");
encrypter.init(Cipher.ENCRYPT_MODE, key, ivSpec);
decrypter.init(Cipher.DECRYPT_MODE, key, ivSpec);
encrypted = new byte[encrypter.getOutputSize(val.length)];
encLength = encrypter.update(val, 0, val.length, encrypted, 0);
encLength += encrypter.doFinal(encrypted, encLength);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException ex) {
throw new RuntimeException(ex);
}
}
use of javax.crypto.ShortBufferException in project Bytecoder by mirkosertic.
the class DHKeyAgreement method engineGenerateSecret.
/**
* Generates the shared secret, and places it into the buffer
* <code>sharedSecret</code>, beginning at <code>offset</code>.
*
* <p>If the <code>sharedSecret</code> buffer is too small to hold the
* result, a <code>ShortBufferException</code> is thrown.
* In this case, this call should be repeated with a larger output buffer.
*
* <p>This method resets this <code>KeyAgreementSpi</code> object,
* so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>engineInit</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @param sharedSecret the buffer for the shared secret
* @param offset the offset in <code>sharedSecret</code> where the
* shared secret will be stored
*
* @return the number of bytes placed into <code>sharedSecret</code>
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
* @exception ShortBufferException if the given output buffer is too small
* to hold the secret
*/
protected int engineGenerateSecret(byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException {
if (generateSecret == false) {
throw new IllegalStateException("Key agreement has not been completed yet");
}
if (sharedSecret == null) {
throw new ShortBufferException("No buffer provided for shared secret");
}
BigInteger modulus = init_p;
int expectedLen = (modulus.bitLength() + 7) >>> 3;
if ((sharedSecret.length - offset) < expectedLen) {
throw new ShortBufferException("Buffer too short for shared secret");
}
// Reset the key agreement after checking for ShortBufferException
// above, so user can recover w/o losing internal state
generateSecret = false;
/*
* NOTE: BigInteger.toByteArray() returns a byte array containing
* the two's-complement representation of this BigInteger with
* the most significant byte is in the zeroth element. This
* contains the minimum number of bytes required to represent
* this BigInteger, including at least one sign bit whose value
* is always 0.
*
* Keys are always positive, and the above sign bit isn't
* actually used when representing keys. (i.e. key = new
* BigInteger(1, byteArray)) To obtain an array containing
* exactly expectedLen bytes of magnitude, we strip any extra
* leading 0's, or pad with 0's in case of a "short" secret.
*/
byte[] secret = this.y.modPow(this.x, modulus).toByteArray();
if (secret.length == expectedLen) {
System.arraycopy(secret, 0, sharedSecret, offset, secret.length);
} else {
// Array too short, pad it w/ leading 0s
if (secret.length < expectedLen) {
System.arraycopy(secret, 0, sharedSecret, offset + (expectedLen - secret.length), secret.length);
} else {
// Array too long, check and trim off the excess
if ((secret.length == (expectedLen + 1)) && secret[0] == 0) {
// ignore the leading sign byte
System.arraycopy(secret, 1, sharedSecret, offset, expectedLen);
} else {
throw new ProviderException("Generated secret is out-of-range");
}
}
}
return expectedLen;
}
use of javax.crypto.ShortBufferException in project KeePassDX by Kunzisoft.
the class AndroidFinalKey method transformMasterKey.
@Override
public byte[] transformMasterKey(byte[] pKeySeed, byte[] pKey, long rounds) throws IOException {
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/ECB/NoPadding");
} catch (NoSuchAlgorithmException e) {
throw new IOException("NoSuchAlgorithm: " + e.getMessage());
} catch (NoSuchPaddingException e) {
throw new IOException("NoSuchPadding: " + e.getMessage());
}
try {
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(pKeySeed, "AES"));
} catch (InvalidKeyException e) {
throw new IOException("InvalidPasswordException: " + e.getMessage());
}
// Encrypt key rounds times
byte[] newKey = new byte[pKey.length];
System.arraycopy(pKey, 0, newKey, 0, pKey.length);
byte[] destKey = new byte[pKey.length];
for (int i = 0; i < rounds; i++) {
try {
cipher.update(newKey, 0, newKey.length, destKey, 0);
System.arraycopy(destKey, 0, newKey, 0, newKey.length);
} catch (ShortBufferException e) {
throw new IOException("Short buffer: " + e.getMessage());
}
}
// Hash the key
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
assert true;
throw new IOException("SHA-256 not implemented here: " + e.getMessage());
}
md.update(newKey);
return md.digest();
}
use of javax.crypto.ShortBufferException in project cassandra by apache.
the class EncryptionUtils method decrypt.
/**
* Decrypt the input data, as well as manage sizing of the {@code outputBuffer}; if the buffer is not big enough,
* deallocate current, and allocate a large enough buffer.
*
* @return the byte buffer that was actaully written to; it may be the {@code outputBuffer} if it had enough capacity,
* or it may be a new, larger instance. Callers should capture the return buffer (if calling multiple times).
*/
public static ByteBuffer decrypt(ReadableByteChannel channel, ByteBuffer outputBuffer, boolean allowBufferResize, Cipher cipher) throws IOException {
ByteBuffer metadataBuffer = reusableBuffers.get();
if (metadataBuffer.capacity() < ENCRYPTED_BLOCK_HEADER_SIZE) {
metadataBuffer = ByteBufferUtil.ensureCapacity(metadataBuffer, ENCRYPTED_BLOCK_HEADER_SIZE, true);
reusableBuffers.set(metadataBuffer);
}
metadataBuffer.position(0).limit(ENCRYPTED_BLOCK_HEADER_SIZE);
channel.read(metadataBuffer);
if (metadataBuffer.remaining() < ENCRYPTED_BLOCK_HEADER_SIZE)
throw new IllegalStateException("could not read encrypted blocked metadata header");
int encryptedLength = metadataBuffer.getInt();
// this is the length of the compressed data
int plainTextLength = metadataBuffer.getInt();
outputBuffer = ByteBufferUtil.ensureCapacity(outputBuffer, Math.max(plainTextLength, encryptedLength), allowBufferResize);
outputBuffer.position(0).limit(encryptedLength);
channel.read(outputBuffer);
ByteBuffer dupe = outputBuffer.duplicate();
dupe.clear();
try {
cipher.doFinal(outputBuffer, dupe);
} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
throw new IOException("failed to decrypt commit log block", e);
}
dupe.position(0).limit(plainTextLength);
return dupe;
}
Aggregations