List of usage examples for org.bouncycastle.crypto.params ParametersWithIV getIV
public byte[] getIV()
From source file:com.dinochiesa.edgecallouts.util.PasswordUtil.java
License:Apache License
public static KeyAndIv deriveKeyAndIv(String plainPassword, byte[] salt, int keyBits, int ivBits, int iterations) { // Derive keys and IVs from passwords, as defined by PKCS 5 V2.0 Scheme // 2. This generator uses a SHA-1 HMac as the // calculation function. This is also known as PBKDF2, and is defined in RFC2898. // See https://en.wikipedia.org/wiki/PBKDF2 PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(); generator.init(plainPassword.getBytes(StandardCharsets.UTF_8), salt, iterations); ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(keyBits, ivBits); return new KeyAndIv(((KeyParameter) params.getParameters()).getKey(), params.getIV()); }
From source file:com.giacomodrago.immediatecrypt.aes.AESFacadeImpl.java
License:Open Source License
@Override public AESEncryptedMessage encrypt(byte[] plaintext, String password) throws EncryptionException { // Check password is not empty if (password.isEmpty()) { throw new EncryptionException("Password is empty."); }//from w w w. j a v a 2 s .co m // Generate random password salt String salt = RandomStringUtils.randomAlphanumeric(SALT_LENGTH); ParametersWithIV params = createEncryptionParameters(password, salt); byte[] iv = params.getIV(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.init(true, params); byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)]; int outputLen = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); try { cipher.doFinal(ciphertext, outputLen); } catch (DataLengthException ex) { throw new EncryptionException(ex); } catch (IllegalStateException ex) { throw new EncryptionException(ex); } catch (InvalidCipherTextException ex) { throw new EncryptionException(ex); } return new AESEncryptedMessage(salt, iv, ciphertext); }
From source file:com.password.locker.crypto.SecureCryptoImpl.java
License:Open Source License
/** * SecureCrypto Constructor./*from w w w .java 2s . c o m*/ * * @param password * password for the crypto keyspec. * * @throws InvalidAlgorithmParameterException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException */ public SecureCryptoImpl(final char[] password) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { SHA256Digest digest = new SHA256Digest(); String s = Constants.PROPERTIES.getStringProperty(Constants.SALT_KEY, PasswordUtils.getSalt(digest)); salt = Hex.decode(s); if (salt.length != digest.getDigestSize()) { LOGGER.warn("Warning salt size is not the size of the Digest."); } //--------------------------------------------------- // Setup encryption. //--------------------------------------------------- PBEParametersGenerator pGen = new PKCS12ParametersGenerator(digest); pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(password), salt, ITERATIONS); ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(KEY_LEN, IV_LEN); SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES"); encryption = Cipher.getInstance(Constants.CRYPTO_ALGORITHM, new BouncyCastleProvider()); encryption.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV())); //--------------------------------------------------- // Setup decryption. //--------------------------------------------------- decryption = Cipher.getInstance(Constants.CRYPTO_SEC_KEY_SPEC, new BouncyCastleProvider()); PBEKeySpec keySpec = new PBEKeySpec(password, salt, ITERATIONS); SecretKeyFactory fact = SecretKeyFactory.getInstance(Constants.CRYPTO_SEC_KEY_SPEC, new BouncyCastleProvider()); try { decryption.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec)); } catch (InvalidKeySpecException e) { ExceptionUtils.fatalError(SecureCryptoImpl.class, e); } Constants.PROPERTIES.addProperty(Constants.SALT_KEY, s); }
From source file:com.symbian.security.Pkcs12Pbe.java
License:Open Source License
private void getKey(int keyLen, int ivLen, int iterCount, String password, byte[] salt) { System.out.print("key len = " + keyLen + ", iter count = " + iterCount + ", password = \"" + password + "\", salt = "); printUnformattedByteArray(salt);/*from www. j a v a 2 s . c o m*/ char[] pwChars = password.toCharArray(); byte[] pwBytes = PBEParametersGenerator.PKCS12PasswordToBytes(pwChars); pgen.init(pwBytes, salt, iterCount); CipherParameters cp = pgen.generateDerivedParameters(keyLen, ivLen); ParametersWithIV ivp = (ParametersWithIV) cp; KeyParameter kp = (KeyParameter) ivp.getParameters(); System.out.print("key "); printUnformattedByteArray((kp.getKey())); System.out.print("iv "); printUnformattedByteArray(ivp.getIV()); kp = (KeyParameter) pgen.generateDerivedMacParameters(160); System.out.print("160bit hmac key "); printUnformattedByteArray((kp.getKey())); }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
public synchronized void writeCrypto(final Connection_ connection, final ByteBuf buffer, final Object message) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); ByteBuf objectOutputBuffer = this.tempBuffer; objectOutputBuffer.clear(); // always have to reset everything // write the object to a TEMP buffer! this will be compressed writer.setBuffer(objectOutputBuffer); writeClassAndObject(writer, message); // save off how much data the object took int length = objectOutputBuffer.writerIndex(); // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0) && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) { // we can use it... inputArray = objectOutputBuffer.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = objectOutputBuffer.arrayOffset(); } else {//from ww w .j a v a 2s . c om // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length); inputOffset = 0; } ////////// compressing data // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger // output), will be negated by the increase in size by the encryption byte[] compressOutput = this.compressOutput; int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative) int maxCompressedLength = compressor.maxCompressedLength(length); // add 4 so there is room to write the compressed size to the buffer int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset; // lazy initialize the compression output buffer if (maxCompressedLengthWithOffset > compressOutputLength) { compressOutputLength = maxCompressedLengthWithOffset; compressOutput = new byte[maxCompressedLengthWithOffset]; this.compressOutput = compressOutput; } // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput, maxLengthLengthOffset, maxCompressedLength); // bytes can now be written to, because our compressed data is stored in a temp array. final int lengthLength = OptimizeUtilsByteArray.intLength(length, true); // correct input. compression output is now encryption input inputArray = compressOutput; inputOffset = maxLengthLengthOffset - lengthLength; // now write the ORIGINAL (uncompressed) length to the front of the byte array. This is so we can use the FAST decompress version OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset); // correct length for encryption length = compressedLength + lengthLength; // +1 to +4 for the uncompressed size bytes /////// encrypting data. final long nextGcmSequence = connection.getNextGcmSequence(); // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time final ParametersWithIV cryptoParameters = connection.getCryptoParameters(); BigEndian.Long_.toBytes(nextGcmSequence, cryptoParameters.getIV(), 4); // put our counter into the IV final GCMBlockCipher aes = this.aesEngine; aes.reset(); aes.init(true, cryptoParameters); byte[] cryptoOutput; // lazy initialize the crypto output buffer int cryptoSize = length + 16; // from: aes.getOutputSize(length); // 'output' is the temp byte array if (cryptoSize > cryptoOutputLength) { cryptoOutputLength = cryptoSize; cryptoOutput = new byte[cryptoSize]; this.cryptoOutput = cryptoOutput; } else { cryptoOutput = this.cryptoOutput; } int encryptedLength = aes.processBytes(inputArray, inputOffset, length, cryptoOutput, 0); try { // authentication tag for GCM encryptedLength += aes.doFinal(cryptoOutput, encryptedLength); } catch (Exception e) { throw new IOException("Unable to AES encrypt the data", e); } // write out our GCM counter OptimizeUtilsByteBuf.writeLong(buffer, nextGcmSequence, true); // have to copy over the orig data, because we used the temp buffer buffer.writeBytes(cryptoOutput, 0, encryptedLength); }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
public Object readCrypto(final Connection_ connection, final ByteBuf buffer, int length) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); //////////////// // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it! //////////////// ByteBuf inputBuf = buffer;//from ww w .jav a 2 s . co m final long gcmIVCounter = OptimizeUtilsByteBuf.readLong(buffer, true); int lengthLength = OptimizeUtilsByteArray.longLength(gcmIVCounter, true); // have to adjust for the gcmIVCounter length = length - lengthLength; /////////// decrypting data // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0) && inputBuf.array().length == inputBuf.capacity()) { // we can use it... inputArray = inputBuf.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = inputBuf.arrayOffset() + lengthLength; } else { // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length); inputOffset = 0; } // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index. buffer.readerIndex(buffer.readerIndex() + length); // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time final ParametersWithIV cryptoParameters = connection.getCryptoParameters(); BigEndian.Long_.toBytes(gcmIVCounter, cryptoParameters.getIV(), 4); // put our counter into the IV final GCMBlockCipher aes = this.aesEngine; aes.reset(); aes.init(false, cryptoParameters); int cryptoSize = length - 16; // from: aes.getOutputSize(length); // lazy initialize the decrypt output buffer byte[] decryptOutputArray; if (cryptoSize > decryptOutputLength) { decryptOutputLength = cryptoSize; decryptOutputArray = new byte[cryptoSize]; this.decryptOutput = decryptOutputArray; decryptBuf = Unpooled.wrappedBuffer(decryptOutputArray); } else { decryptOutputArray = this.decryptOutput; } int decryptedLength = aes.processBytes(inputArray, inputOffset, length, decryptOutputArray, 0); try { // authentication tag for GCM decryptedLength += aes.doFinal(decryptOutputArray, decryptedLength); } catch (Exception e) { throw new IOException("Unable to AES decrypt the data", e); } ///////// decompress data -- as it's ALWAYS compressed // get the decompressed length (at the beginning of the array) inputArray = decryptOutputArray; final int uncompressedLength = OptimizeUtilsByteArray.readInt(inputArray, true); inputOffset = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-4 bytes for the decompressed size byte[] decompressOutputArray = this.decompressOutput; if (uncompressedLength > decompressOutputLength) { decompressOutputLength = uncompressedLength; decompressOutputArray = new byte[uncompressedLength]; this.decompressOutput = decompressOutputArray; decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo } inputBuf = decompressBuf; // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength); inputBuf.setIndex(0, uncompressedLength); // read the object from the buffer. reader.setBuffer(inputBuf); return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer }
From source file:edu.vt.middleware.crypt.PbeKeyGenerator.java
License:Open Source License
/** * Generate an encryption key/IV pair from a password using the given * parameter generator./*from w ww. j av a2s . c o m*/ * * @param generator Key generator for specific PBE method. * @param password Password as byte array (depends on PBE method). * @param keyBitLength Size of generated key in bits. * @param ivBitLength Size of generated IV in bits. * @param salt Key initialization data. * * @return Secret key derived from password using PBE key generation method. */ private KeyWithIV generate(final PBEParametersGenerator generator, final byte[] password, final int keyBitLength, final int ivBitLength, final byte[] salt) { generator.init(password, salt, iterations); final ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(keyBitLength, ivBitLength); final KeyParameter keyParam = (KeyParameter) params.getParameters(); return new KeyWithIV(new SecretKeySpec(keyParam.getKey(), symmetricAlg.getAlgorithm()), params.getIV()); }
From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java
License:Apache License
protected void writeKeyfile(TarArchiveOutputStream tarArchiveOutputStream, ParametersWithIV cipherParameters) throws IOException, InvalidCipherTextException { final KeyParameter keyParameter = (KeyParameter) cipherParameters.getParameters(); final byte[] keyBytes = keyParameter.getKey(); final char[] keyHexChars = Hex.encodeHex(keyBytes); final byte[] ivBytes = cipherParameters.getIV(); final char[] ivHexChars = Hex.encodeHex(ivBytes); //Create keyfile contents final String keyfileString = new StringBuilder(keyHexChars.length + 1 + ivHexChars.length) .append(keyHexChars).append(KEYFILE_LINE_SEPERATOR).append(ivHexChars).toString(); encryptAndWrite(tarArchiveOutputStream, keyfileString, KEYFILE_ENC_NAME); }
From source file:freenet.crypt.OCBBlockCipher_v149.java
License:Open Source License
public void init(boolean forEncryption, CipherParameters parameters) throws IllegalArgumentException { this.forEncryption = forEncryption; this.macBlock = null; KeyParameter keyParameter;//from w w w .ja v a 2s . c o m byte[] N; if (parameters instanceof AEADParameters) { AEADParameters aeadParameters = (AEADParameters) parameters; N = aeadParameters.getNonce(); initialAssociatedText = aeadParameters.getAssociatedText(); int macSizeBits = aeadParameters.getMacSize(); if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0) { throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits); } macSize = macSizeBits / 8; keyParameter = aeadParameters.getKey(); } else if (parameters instanceof ParametersWithIV) { ParametersWithIV parametersWithIV = (ParametersWithIV) parameters; N = parametersWithIV.getIV(); initialAssociatedText = null; macSize = 16; keyParameter = (KeyParameter) parametersWithIV.getParameters(); } else { throw new IllegalArgumentException("invalid parameters passed to OCB"); } this.hashBlock = new byte[16]; this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)]; if (N == null) { N = new byte[0]; } /* * TODO There's currently a thread on CFRG * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including * (macSize % 128) in the nonce, in which case this test becomes simpler: */ // if (N.length > 15) // { // throw new IllegalArgumentException("IV must be no more than 120 bits"); // } if (N.length > 16 || (N.length == 16 && (N[0] & 0x80) != 0)) { /* * NOTE: We don't just ignore bit 128 because it would hide from the caller the fact * that two nonces differing only in bit 128 are not different. */ throw new IllegalArgumentException("IV must be no more than 127 bits"); } /* * KEY-DEPENDENT INITIALISATION */ if (keyParameter == null) { // TODO If 'keyParameter' is null we're re-using the last key. } // hashCipher always used in forward mode hashCipher.init(true, keyParameter); mainCipher.init(forEncryption, keyParameter); this.L_Asterisk = new byte[16]; hashCipher.processBlock(L_Asterisk, 0, L_Asterisk, 0); this.L_Dollar = OCB_double(L_Asterisk); this.L = new Vector(); this.L.addElement(OCB_double(L_Dollar)); /* * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION */ byte[] nonce = new byte[16]; System.arraycopy(N, 0, nonce, nonce.length - N.length, N.length); /* * TODO There's currently a thread on CFRG * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including * (macSize % 128) in the nonce, in which case this code becomes simpler: */ // nonce[0] = (byte)(macSize << 4); // nonce[15 - N.length] |= 1; if (N.length == 16) { nonce[0] &= 0x80; } else { nonce[15 - N.length] = 1; } int bottom = nonce[15] & 0x3F; // System.out.println("bottom: " + bottom); byte[] Ktop = new byte[16]; nonce[15] &= 0xC0; hashCipher.processBlock(nonce, 0, Ktop, 0); byte[] Stretch = new byte[24]; System.arraycopy(Ktop, 0, Stretch, 0, 16); for (int i = 0; i < 8; ++i) { Stretch[16 + i] = (byte) (Ktop[i] ^ Ktop[i + 1]); } this.OffsetMAIN_0 = new byte[16]; int bits = bottom % 8, bytes = bottom / 8; if (bits == 0) { System.arraycopy(Stretch, bytes, OffsetMAIN_0, 0, 16); } else { for (int i = 0; i < 16; ++i) { int b1 = Stretch[bytes] & 0xff; int b2 = Stretch[++bytes] & 0xff; this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >>> (8 - bits))); } } this.hashBlockPos = 0; this.mainBlockPos = 0; this.hashBlockCount = 0; this.mainBlockCount = 0; this.OffsetHASH = new byte[16]; this.Sum = new byte[16]; this.OffsetMAIN = Arrays.clone(this.OffsetMAIN_0); this.Checksum = new byte[16]; if (initialAssociatedText != null) { processAADBytes(initialAssociatedText, 0, initialAssociatedText.length); } }
From source file:org.bunkr.core.descriptor.PBKDF2Descriptor.java
License:Open Source License
@Override public Inventory readInventoryFromBytes(byte[] source, UserSecurityProvider usp) throws BaseBunkrException { try {/*from w ww.ja v a 2 s. c o m*/ if (this.encryptionAlgorithm == Encryption.NONE) throw new IllegalArgumentException("PBKDF2Descriptor requires an active encryption mode"); PKCS5S2ParametersGenerator g = new PKCS5S2ParametersGenerator(new SHA256Digest()); g.init(usp.getHashedPassword(), this.pbkdf2Salt, this.pbkdf2Iterations); ParametersWithIV kp = (ParametersWithIV) g.generateDerivedParameters( this.encryptionAlgorithm.keyByteLength * 8, this.encryptionAlgorithm.ivByteLength * 8); byte[] decryptedInv = SimpleAES.decrypt(this.encryptionAlgorithm, source, ((KeyParameter) kp.getParameters()).getKey(), kp.getIV()); return InventoryJSON.decode(new String(decryptedInv)); } catch (IllegalPasswordException | CryptoException e) { throw new BaseBunkrException(e); } }