List of usage examples for org.bouncycastle.crypto.modes GCMBlockCipher GCMBlockCipher
public GCMBlockCipher(BlockCipher c)
From source file:edu.tamu.tcat.crypto.bouncycastle.SymmetricCipherBuilderImpl.java
License:Apache License
@Override public AEADSymmetricCipher buildAEADCipher(Cipher cipher, Mode mode, boolean encryption, byte[] key, byte[] iv) throws CipherException { ParametersWithIV cipherParameters = new ParametersWithIV(new KeyParameter(key), iv); BlockCipher underlyingCipher = null; int macSize = 0; switch (cipher) { case AES128:/* ww w.ja v a2 s. c o m*/ case AES192: case AES256: underlyingCipher = new AESEngine(); break; } AEADBlockCipher aeadCipher = null; switch (mode) { case CBC: throw new CipherException(mode + " is not an authenticating encryption mode; use buildCipher instead"); case GCM: aeadCipher = new GCMBlockCipher(underlyingCipher); macSize = underlyingCipher.getBlockSize(); break; } aeadCipher.init(encryption, cipherParameters); return new BouncyCastleAEADCipher(aeadCipher, macSize, encryption); }
From source file:org.avasquez.seccloudfs.utils.CryptoUtils.java
License:Open Source License
/** * Creates a cipher that uses AES encryption with GCM block mode. * * @param forEncryption true if the cipher is going to be used for encryption, false for decryption * @param key the encryption key * @param iv the initialization vector, or nonce * * @return the initialized cipher/* w w w .ja v a 2s . c om*/ */ public static AEADBlockCipher createAesWithGcmCipher(boolean forEncryption, byte[] key, byte[] iv) { AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine()); cipher.init(forEncryption, new AEADParameters(new KeyParameter(key), 128, iv)); return cipher; }
From source file:org.cryptacular.spec.AEADBlockCipherSpec.java
License:Open Source License
/** * Creates a new AEAD block cipher from the specification in this instance. * * @return New AEAD block cipher instance. */// www. j a v a2 s. c o m @Override public AEADBlockCipher newInstance() { final BlockCipher blockCipher = new BlockCipherSpec(algorithm).newInstance(); AEADBlockCipher aeadBlockCipher; switch (mode) { case "GCM": aeadBlockCipher = new GCMBlockCipher(blockCipher); break; case "CCM": aeadBlockCipher = new CCMBlockCipher(blockCipher); break; case "OCB": aeadBlockCipher = new OCBBlockCipher(blockCipher, new BlockCipherSpec(algorithm).newInstance()); break; case "EAX": aeadBlockCipher = new EAXBlockCipher(blockCipher); break; default: throw new IllegalStateException("Unsupported mode " + mode); } return aeadBlockCipher; }
From source file:org.cryptacular.util.CipherUtilTest.java
License:Open Source License
@DataProvider(name = "aead-block-cipher") public Object[][] getAeadBlockCipherData() { return new Object[][] { new Object[] { // Plaintext is NOT multiple of block size "I never picked cotton like my mother did", new GCMBlockCipher(new AESEngine()), }, new Object[] { // Plaintext is multiple of block size "Cogito ergo sum.", new GCMBlockCipher(new AESEngine()), }, // CCM new Object[] { "Thousands of candles can be lit from a single candle and the life " + "of the candle will not be shortened.", new CCMBlockCipher(new TwofishEngine()), }, // OCB new Object[] { "I slept and dreamt life was joy. I awoke and saw that life was " + "service. I acted and behold: service was joy.", new OCBBlockCipher(new AESEngine(), new AESEngine()), }, }; }
From source file:org.cryptacular.util.CipherUtilTest.java
License:Open Source License
@Test(dataProvider = "plaintext-files") public void testAeadBlockCipherEncryptDecryptStream(final String path) throws Exception { final AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine()); final SecretKey key = SecretKeyGenerator.generate(cipher.getUnderlyingCipher()); final File file = new File(path); final String expected = new String(StreamUtil.readAll(file)); final ByteArrayOutputStream tempOut = new ByteArrayOutputStream(); CipherUtil.encrypt(cipher, key, new RBGNonce(), StreamUtil.makeStream(file), tempOut); final ByteArrayInputStream tempIn = new ByteArrayInputStream(tempOut.toByteArray()); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); CipherUtil.decrypt(cipher, key, tempIn, actual); assertEquals(new String(actual.toByteArray()), expected); }
From source file:org.jboss.aerogear.crypto.BlockCipher.java
License:Apache License
/** * Retrieve a new instance of the block mode provided * @param blockMode block mode name// w w w . java2 s . co m * @return instance to the block mode */ public static AEADBlockCipher getNewCipher(Mode blockMode) { AESEngine aesEngine = new AESEngine(); switch (blockMode) { case GCM: return new GCMBlockCipher(aesEngine); default: throw new RuntimeException("Block cipher not found"); } }
From source file:org.openmuc.jdlms.internal.security.HlsProcessorGmac.java
License:Open Source License
@Override public byte[] process(byte[] challenge, byte[] authenticationKey, byte[] encryptionKey, byte[] systemTitle, int frameCounter) throws IOException, UnsupportedOperationException { byte[] sc = new byte[] { 0x10 }; byte[] frameCounterBytes = ByteBuffer.allocate(4).putInt(frameCounter).array(); byte[] iv = ByteBuffer.allocate(systemTitle.length + frameCounterBytes.length).put(systemTitle) .put(frameCounterBytes).array(); CipherParameters cipherParameters = new KeyParameter(encryptionKey); ParametersWithIV parameterWithIV = new ParametersWithIV(cipherParameters, iv); GMac mac = new GMac(new GCMBlockCipher(new AESFastEngine()), 96); mac.init(parameterWithIV);//from ww w .j a v a 2s . co m byte[] input = ByteBuffer.allocate(sc.length + authenticationKey.length + challenge.length).put(sc) .put(authenticationKey).put(challenge).array(); mac.update(input, 0, input.length); final byte[] generatedMac = new byte[mac.getMacSize()]; mac.doFinal(generatedMac, 0); return ByteBuffer.allocate(sc.length + frameCounterBytes.length + generatedMac.length).put(sc) .put(frameCounterBytes).put(generatedMac).array(); }
From source file:org.panbox.core.crypto.io.AESGCMRandomAccessFileCompat.java
License:Open Source License
/** * initialize ciphers// ww w . ja v a 2 s . com * * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws RandomDataGenerationException * @throws InvalidAlgorithmParameterException * @throws NoSuchProviderException */ protected void initCiphers() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, RandomDataGenerationException, InvalidAlgorithmParameterException, NoSuchProviderException { super.initCiphers(); this.gcmEngine = new GCMBlockCipher(new AESFastEngine()); }
From source file:org.panbox.core.crypto.io.AESGCMRandomAccessFileCompat.java
License:Open Source License
@Override protected byte[] _readChunk(long index) throws IOException, FileEncryptionException, FileIntegrityException { // first, get chunk iv for decryption long oldpos = backingRandomAccessFile.getFilePointer(); backingRandomAccessFile.seek(chunkOffset(index)); // read iv// www . j a va2 s. co m byte[] iv = new byte[CHUNK_IV_SIZE]; int ret = backingRandomAccessFile.read(iv); if (ret != CHUNK_IV_SIZE) { throw new FileEncryptionException("Size mismatch reading chunk IV!"); } // prepare params for GCM decryption // retrieve key bytes from SecretKey byte[] key = getFileKeyBytes(); if ((key == null) || (key.length != KeyConstants.SYMMETRIC_FILE_KEY_SIZE_BYTES)) { throw new FileEncryptionException("Invalid encryption key format!"); } // prepare additional authenticated data (index and lastchunkflag as // bytes) for verifying metadata integrity // byte[] indexAsBytes = IntByteConv.int2byte(index); byte[] indexAsBytes = LongByteConv.long2Bytes(index); byte[] lastchunkflagAsBytes = BooleanByteConv.bool2byte(false); if ((indexAsBytes == null) || (lastchunkflagAsBytes == null) || (indexAsBytes.length == 0) || (lastchunkflagAsBytes.length == 0)) { throw new FileEncryptionException("Invalid additional autenticated data!"); } byte[] associatedText = new byte[indexAsBytes.length + lastchunkflagAsBytes.length]; System.arraycopy(indexAsBytes, 0, associatedText, 0, indexAsBytes.length); System.arraycopy(lastchunkflagAsBytes, 0, associatedText, indexAsBytes.length, lastchunkflagAsBytes.length); AEADParameters gcmParams = new AEADParameters(new KeyParameter(key), GCM_AUTHENTICATION_TAG_LEN, iv, associatedText); GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine()); gcmEngine.init(false, gcmParams); byte[] decMsg = new byte[gcmEngine.getOutputSize(CHUNK_ENC_DATA_SIZE)]; byte[] encMsg = new byte[CHUNK_ENC_DATA_SIZE]; ret = backingRandomAccessFile.read(encMsg); backingRandomAccessFile.seek(oldpos); if (ret != CHUNK_ENC_DATA_SIZE) { throw new FileEncryptionException("Size mismatch reading encrypted chunk data!"); } int decLen = gcmEngine.processBytes(encMsg, 0, encMsg.length, decMsg, 0); try { decLen += gcmEngine.doFinal(decMsg, decLen); } catch (IllegalStateException | InvalidCipherTextException e) { if ((e instanceof InvalidCipherTextException) && (e.getMessage().contains("mac check in GCM failed"))) { throw new FileIntegrityException( "Decryption error in chunk " + index + ". Possible file integrity violation.", e); } else { throw new FileEncryptionException("Decryption error in chunk " + index + ": " + e.getMessage(), e); } } if ((decMsg == null) || (decMsg.length != CHUNK_DATA_SIZE)) { throw new FileEncryptionException("Decryption error or chunk size mismatch during decryption!"); } else { if (implementsAuthentication()) { // check authentication tag for integrity byte[] tag = Arrays.copyOfRange(encMsg, decMsg.length, encMsg.length); if (!getAuthTagVerifier().verifyChunkAuthTag((int) index, tag)) { throw new FileIntegrityException( "File authentication tag verification failed in chunk " + index); } } return decMsg; } }
From source file:org.panbox.core.crypto.io.AESGCMRandomAccessFileHW.java
License:Open Source License
@Override protected void initCiphers() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, RandomDataGenerationException, InvalidAlgorithmParameterException, NoSuchProviderException { super.initCiphers(); // TODO: This following code mixes the SunJCE AES blockcipher // implementation with Bouncycastle's GCMBlockCipher to improve // performance due to SunJCE's AES NI support. Replace this with // "native" BC code, as soon as they introduce AES NI support // themselves. For more information see // http://bouncy-castle.1462172.n4.nabble.com/Using-BC-AES-GCM-for-S3-td4657050.html this.gcmEngine = new GCMBlockCipher(new BlockCipher() { Cipher aes = Cipher.getInstance("AES/ECB/NoPadding", KeyConstants.PROV_SunJCE); public void reset() { }//from w ww .jav a 2s . c om public int processBlock(byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException { try { aes.update(in, outOff, getBlockSize(), out, outOff); } catch (ShortBufferException e) { throw new DataLengthException(); } return getBlockSize(); } public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { KeyParameter kp = (KeyParameter) params; SecretKeySpec key = new SecretKeySpec(kp.getKey(), "AES"); try { aes.init(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key); } catch (InvalidKeyException e) { throw new IllegalArgumentException(e); } } public int getBlockSize() { return aes.getBlockSize(); } public String getAlgorithmName() { return aes.getAlgorithm(); } }); }