/** * Returns the block size (in bytes). * * @return the block size (in bytes), or 0 if the underlying algorithm is * not a block cipher */ final int getBlockSize() { return cipher.getBlockSize(); }
/** * @param cipher Cipher. * @return Init vector for encryption. * @see <a href="https://en.wikipedia.org/wiki/Initialization_vector">Initialization vector</a> */ private byte[] initVector(Cipher cipher) { byte[] iv = new byte[cipher.getBlockSize()]; ThreadLocalRandom.current().nextBytes(iv); return iv; }
/** {@inheritDoc} */ @Override public byte[] decrypt(byte[] data, Serializable key) { assert key instanceof KeystoreEncryptionKey; ensureStarted(); try { SecretKeySpec keySpec = new SecretKeySpec(((KeystoreEncryptionKey)key).key().getEncoded(), CIPHER_ALGO); Cipher cipher = aesWithPadding.get(); cipher.init(DECRYPT_MODE, keySpec, new IvParameterSpec(data, 0, cipher.getBlockSize())); return cipher.doFinal(data, cipher.getBlockSize(), data.length - cipher.getBlockSize()); } catch (InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new IgniteSpiException(e); } }
/** {@inheritDoc} */ @Override public void decryptNoPadding(ByteBuffer data, Serializable key, ByteBuffer res) { assert key instanceof KeystoreEncryptionKey; ensureStarted(); try { SecretKeySpec keySpec = new SecretKeySpec(((KeystoreEncryptionKey)key).key().getEncoded(), CIPHER_ALGO); Cipher cipher = aesWithoutPadding.get(); byte[] iv = new byte[cipher.getBlockSize()]; data.get(iv); cipher.init(DECRYPT_MODE, keySpec, new IvParameterSpec(iv)); cipher.doFinal(data, res); } catch (InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | ShortBufferException | BadPaddingException e) { throw new IgniteSpiException(e); } }
public AesFlushingCipher(int mode, byte[] secretKey, long nonce, long offset) { try { cipher = Cipher.getInstance("AES/CTR/NoPadding"); blockSize = cipher.getBlockSize(); zerosBlock = new byte[blockSize]; flushedBlock = new byte[blockSize]; long counter = offset / blockSize; int startPadding = (int) (offset % blockSize); cipher.init( mode, new SecretKeySpec(secretKey, Util.splitAtFirst(cipher.getAlgorithm(), "/")[0]), new IvParameterSpec(getInitializationVector(nonce, counter))); if (startPadding != 0) { updateInPlace(new byte[startPadding], 0, startPadding); } } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { // Should never happen. throw new RuntimeException(e); } }
private int calculateSaltLength(EncryptionMethod encryptionMethod) { try { Cipher cipher = Cipher.getInstance(encryptionMethod.getAlgorithm(), encryptionMethod.getProvider()); return cipher.getBlockSize() > 0 ? cipher.getBlockSize() : getDefaultSaltLength(); } catch (Exception e) { logger.warn("Encountered exception determining salt length from encryption method {}", encryptionMethod.getAlgorithm(), e); final int defaultSaltLength = getDefaultSaltLength(); logger.warn("Returning default length: {} bytes", defaultSaltLength); return defaultSaltLength; } }
private void loadSecretKey(ObjectInputStream ois) throws IOException, GeneralSecurityException { byte[] encryptedData = readBytes(ois); byte[] iv = readBytes(ois); decrypt.init(Cipher.DECRYPT_MODE, storageSecretKey, new IvParameterSpec(iv)); Assert.checkMaximumParameter("cipher block size", 256, decrypt.getBlockSize()); byte[] unPadded = pkcs7UnPad(decrypt.doFinal(encryptedData)); ObjectInputStream entryOis = new ObjectInputStream(new ByteArrayInputStream(unPadded)); String ksAlias = entryOis.readUTF(); byte[] encodedSecretKey = readBytes(entryOis); KeyStore.Entry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encodedSecretKey, DATA_OID)); dataKeyStore.setEntry(ksAlias, entry, convertParameter(protectionParameter)); }
int blockSize = cipher.getBlockSize();
private void saveSecretKey(String ksAlias, ObjectOutputStream oos, KeyStore.SecretKeyEntry entry) throws IOException, GeneralSecurityException { ByteArrayOutputStream entryData = new ByteArrayOutputStream(1024); ObjectOutputStream entryOos = new ObjectOutputStream(entryData); entryOos.writeUTF(ksAlias); writeBytes(entry.getSecretKey().getEncoded(), entryOos); entryOos.flush(); encrypt.init(Cipher.ENCRYPT_MODE, storageSecretKey, (AlgorithmParameterSpec) null); // ELY-1308: third param need to workaround BouncyCastle bug int blockSize = encrypt.getBlockSize(); if (blockSize == 0) throw log.algorithmNotBlockBased(encrypt.getAlgorithm()); Assert.checkMaximumParameter("cipher block size", 256, blockSize); byte[] padded = pkcs7Pad(entryData.toByteArray(), blockSize); byte[] encrypted = encrypt.doFinal(padded); byte[] iv = encrypt.getIV(); if (iv == null) throw log.algorithmNotIV(encrypt.getAlgorithm()); oos.writeInt(SECRET_KEY_ENTRY_TYPE); writeBytes(encrypted, oos); writeBytes(iv, oos); }
int ivLength = cipher.getBlockSize(); if (iv.length != ivLength) { logger.warn("An IV was provided of length {} bytes for {}ion but should be {} bytes", iv.length, operation, ivLength);
int blockSize = wrapCipher.getBlockSize(); if (blockSize > 0) { paddingLength = blockSize - ((len + 10) % blockSize);
if (unwrapCipher.getBlockSize() > 0) { int padSize = clearText[clearText.length - 10 - 1]; int decryptedMessageSize = clearText.length - 10;
/** * Returns the block size (in bytes). * * @return the block size (in bytes), or 0 if the underlying algorithm is * not a block cipher */ final int getBlockSize() { return cipher.getBlockSize(); }
/** * Calculates the length of the encrypted file given the original plaintext * file length and the cipher that will be used for encryption. * * @return The size of the encrypted file in bytes, or -1 if no content * length has been set yet. */ private static long calculateCryptoContentLength(Cipher symmetricCipher, PutObjectRequest request, ObjectMetadata metadata) { long plaintextLength = getUnencryptedContentLength(request, metadata); // If we don't know the unencrypted size, then report -1 if (plaintextLength < 0) return -1; long cipherBlockSize = symmetricCipher.getBlockSize(); long offset = cipherBlockSize - (plaintextLength % cipherBlockSize); return plaintextLength + offset; }
InputStream cipherInputStream = null; try { final StringBuilder output = new StringBuilder(); final byte[] secretKey = javax.xml.bind.DatatypeConverter.parseHexBinary("E4A38479A2349177EAE6038A018483318350E7F5430BDC8F82F1974715CB54E5"); final byte[] initVector = javax.xml.bind.DatatypeConverter.parseHexBinary("629E2E1500B6BA687A385D410D5B08E3"); final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey, "AES"), new IvParameterSpec(initVector, 0, cipher.getBlockSize())); cipherInputStream = new CipherInputStream(new FileInputStream("text_ENCRYPTED"), cipher); final String charsetName = "UTF-8"; final byte[] buffer = new byte[8192]; int read = cipherInputStream.read(buffer); while (read > -1) { output.append(new String(buffer, 0, read, charsetName)); read = cipherInputStream.read(buffer); } System.out.println(output); } finally { if (cipherInputStream != null) { cipherInputStream.close(); } }
byte[] iv = new byte[cipher.getBlockSize()]; new SecureRandom().nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv);
@Override public OutputStream encryptStream(OutputStream outputStream) throws CryptoException { sr.nextBytes(initVector); try { outputStream.write(initVector); } catch (IOException e) { throw new CryptoException("Unable to write IV to stream", e); } Cipher cipher; try { cipher = Cipher.getInstance(transformation); cipher.init(Cipher.ENCRYPT_MODE, fek, new IvParameterSpec(initVector)); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { throw new CryptoException("Unable to initialize cipher", e); } CipherOutputStream cos = new CipherOutputStream(outputStream, cipher); return new BlockedOutputStream(cos, cipher.getBlockSize(), 1024); }
@Override public InputStream decryptStream(InputStream inputStream) throws CryptoException { byte[] initVector = new byte[IV_LENGTH_IN_BYTES]; try { IOUtils.readFully(inputStream, initVector); } catch (IOException e) { throw new CryptoException("Unable to read IV from stream", e); } Cipher cipher; try { cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, fek, new IvParameterSpec(initVector)); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { throw new CryptoException("Unable to initialize cipher", e); } CipherInputStream cis = new CipherInputStream(inputStream, cipher); return new BlockedInputStream(cis, cipher.getBlockSize(), 1024); } }
@Override public InputStream decryptStream(InputStream inputStream) throws CryptoException { byte[] initVector = new byte[GCM_IV_LENGTH_IN_BYTES]; try { IOUtils.readFully(inputStream, initVector); } catch (IOException e) { throw new CryptoException("Unable to read IV from stream", e); } Cipher cipher; try { cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, fek, new GCMParameterSpec(GCM_TAG_LENGTH_IN_BITS, initVector)); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { throw new CryptoException("Unable to initialize cipher", e); } CipherInputStream cis = new CipherInputStream(inputStream, cipher); return new BlockedInputStream(cis, cipher.getBlockSize(), 1024); } }
/** * Calculates the content length of the crypto. * @param symmetricCipher the Cipher. * @param request the UploadPartRequest. * @return the length of the content. */ public static long calculateCryptoContentLength(Cipher symmetricCipher, UploadPartRequest request) { long plaintextLength; if (request.getFile() != null) { if (request.getPartSize() > 0) plaintextLength = request.getPartSize(); else plaintextLength = request.getFile().length(); } else if (request.getInputStream() != null) { plaintextLength = request.getPartSize(); } else { return -1; } long cipherBlockSize = symmetricCipher.getBlockSize(); long offset = cipherBlockSize - (plaintextLength % cipherBlockSize); return plaintextLength + offset; }