List of usage examples for org.bouncycastle.crypto.engines AESEngine AESEngine
public AESEngine()
From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java
License:Apache License
public String getAES256Cipher(String inputText, String password, boolean decrypt) { KeyIVGenerator derivedFromPassword = new KeyIVGenerator(password); // Set up key and IV these are derived from the password, using MD5 very simple. See class details. try {//from w w w . j a v a2 s . c om byte[] buffer; //Sting to encrypt if (!decrypt) { buffer = inputText.getBytes(Charset.forName("UTF-8")); } else { buffer = Base64.decode(inputText); } // Aes Encryption BlockCipher blockCipher = new AESEngine(); // Mode CBC blockCipher = new CBCBlockCipher(blockCipher); BlockCipherPadding padding = new PKCS7Padding(); // Get our Cipher. PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, padding); // Initialize the cipher. cipher.init(!decrypt, new ParametersWithIV(new KeyParameter(derivedFromPassword.getKey()), derivedFromPassword.getIV())); //byte[] bytes_output = cipher.doFinal(buffer,0); byte bytes_output[] = new byte[cipher.getOutputSize(buffer.length)]; int len = cipher.processBytes(buffer, 0, buffer.length, bytes_output, 0); int noOfBytesCopied = cipher.doFinal(bytes_output, len); if (!decrypt) { //Return base 64 encrypted text. return new String(Base64.encode(bytes_output), Charset.forName("UTF-8")); //return Convert.ToBase64String(bytes_output, Base64FormattingOptions.InsertLineBreaks); } else { //Return plain text. return new String(bytes_output, Charset.forName("UTF-8")); } } catch (Exception e) { logger.severe(" Failure attempting to AES256 encrypt/decrypt the xml " + e.toString()); e.printStackTrace(); throw new RuntimeException(" Failure attempting AES256 " + (decrypt ? "decryption" : "encryption") + " :" + e.getMessage()); } finally { derivedFromPassword.Clean(); } }
From source file:com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.java
License:Open Source License
@Override public byte[] wrap(final byte[] data) throws MslCryptoException { // Create the header. final String header; try {/*from ww w. ja v a2 s . c om*/ header = new JSONStringer().object().key(KEY_ALGORITHM).value(algo.toString()).key(KEY_ENCRYPTION) .value(enc.name()).endObject().toString(); } catch (final JSONException e) { throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e); } // Determine algorithm byte lengths. final int keylen, ivlen, atlen; if (Encryption.A128GCM.equals(enc)) { keylen = A128_GCM_KEY_LENGTH; ivlen = A128_GCM_IV_LENGTH; atlen = A128_GCM_AT_LENGTH; } else if (Encryption.A256GCM.equals(enc)) { keylen = A256_GCM_KEY_LENGTH; ivlen = A256_GCM_IV_LENGTH; atlen = A256_GCM_AT_LENGTH; } else { throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name()); } // Generate the key and IV. final Random random = ctx.getRandom(); final byte[] key = new byte[keylen]; random.nextBytes(key); final KeyParameter cek = new KeyParameter(key); final byte[] iv = new byte[ivlen]; random.nextBytes(iv); // Encrypt the CEK. final byte[] ecek = cekCryptoContext.encrypt(cek.getKey()); // Base64-encode the data. final String headerB64 = JsonUtils.b64urlEncode(header.getBytes(UTF_8)); final String ecekB64 = JsonUtils.b64urlEncode(ecek); final String ivB64 = JsonUtils.b64urlEncode(iv); // Create additional authenticated data. final String aad = headerB64 + "." + ecekB64 + "." + ivB64; // TODO: AES-GCM is not available via the JCE. // // Create and initialize the cipher for encryption. final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine()); final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8)); plaintextCipher.init(true, params); // Encrypt the plaintext. final byte[] ciphertextATag; try { final int clen = plaintextCipher.getOutputSize(data.length); ciphertextATag = new byte[clen]; // Encrypt the plaintext and get the resulting ciphertext length // which will be used for the authentication tag offset. final int offset = plaintextCipher.processBytes(data, 0, data.length, ciphertextATag, 0); // Append the authentication tag. plaintextCipher.doFinal(ciphertextATag, offset); } catch (final IllegalStateException e) { throw new MslCryptoException(MslError.WRAP_ERROR, e); } catch (final InvalidCipherTextException e) { throw new MslInternalException("Invalid ciphertext not expected when encrypting.", e); } // Split the result into the ciphertext and authentication tag. final byte[] ciphertext = Arrays.copyOfRange(ciphertextATag, 0, ciphertextATag.length - atlen / Byte.SIZE); final byte[] at = Arrays.copyOfRange(ciphertextATag, ciphertext.length, ciphertextATag.length); // Base64-encode the ciphertext and authentication tag. final String ciphertextB64 = JsonUtils.b64urlEncode(ciphertext); final String atB64 = JsonUtils.b64urlEncode(at); // Envelope the data. switch (format) { case JWE_CS: { final String serialization = aad + "." + ciphertextB64 + "." + atB64; return serialization.getBytes(UTF_8); } case JWE_JS: { try { // Create recipients array. final JSONArray recipients = new JSONArray(); final JSONObject recipient = new JSONObject(); recipient.put(KEY_HEADER, headerB64); recipient.put(KEY_ENCRYPTED_KEY, ecekB64); recipient.put(KEY_INTEGRITY_VALUE, atB64); recipients.put(recipient); // Create JSON serialization. final JSONObject serialization = new JSONObject(); serialization.put(KEY_RECIPIENTS, recipients); serialization.put(KEY_INITIALIZATION_VECTOR, ivB64); serialization.put(KEY_CIPHERTEXT, ciphertextB64); return serialization.toString().getBytes(UTF_8); } catch (final JSONException e) { throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e); } } default: throw new MslCryptoException(MslError.UNSUPPORTED_JWE_SERIALIZATION, format.name()); } }
From source file:com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.java
License:Open Source License
@Override public byte[] unwrap(final byte[] data) throws MslCryptoException { // Parse the serialization. final String serialization = new String(data, UTF_8); final String headerB64, ecekB64, ivB64; final byte[] ciphertext, at; if (data[0] == '{') { try {//from ww w. ja v a 2 s .c om final JSONObject serializationJo = new JSONObject(serialization); ivB64 = serializationJo.getString(KEY_INITIALIZATION_VECTOR); ciphertext = JsonUtils.b64urlDecode(serializationJo.getString(KEY_CIPHERTEXT)); // TODO: For now, we only support one recipient. final JSONArray recipients = serializationJo.getJSONArray(KEY_RECIPIENTS); final JSONObject recipient = recipients.getJSONObject(0); headerB64 = recipient.getString(KEY_HEADER); ecekB64 = recipient.getString(KEY_ENCRYPTED_KEY); at = JsonUtils.b64urlDecode(recipient.getString(KEY_INTEGRITY_VALUE)); } catch (final JSONException e) { throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization, e); } } else { // Separate the compact serialization. final String[] parts = serialization.split("\\."); if (parts.length != 5) throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization); // Extract the data from the serialization. headerB64 = parts[0]; ecekB64 = parts[1]; ivB64 = parts[2]; ciphertext = JsonUtils.b64urlDecode(parts[3]); at = JsonUtils.b64urlDecode(parts[4]); } // Decode header, encrypted content encryption key, and IV. final byte[] headerBytes = JsonUtils.b64urlDecode(headerB64); final byte[] ecek = JsonUtils.b64urlDecode(ecekB64); final byte[] iv = JsonUtils.b64urlDecode(ivB64); // Verify data. if (headerBytes == null || headerBytes.length == 0 || ecek == null || ecek.length == 0 || iv == null || iv.length == 0 || ciphertext == null || ciphertext.length == 0 || at == null || at.length == 0) { throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization); } // Reconstruct and parse the header. final String header = new String(headerBytes, UTF_8); final Algorithm algo; final Encryption enc; try { final JSONObject headerJo = new JSONObject(header); final String algoName = headerJo.getString(KEY_ALGORITHM); try { algo = Algorithm.fromString(algoName); } catch (final IllegalArgumentException e) { throw new MslCryptoException(MslError.JWE_PARSE_ERROR, algoName, e); } final String encName = headerJo.getString(KEY_ENCRYPTION); try { enc = Encryption.valueOf(encName); } catch (final IllegalArgumentException e) { throw new MslCryptoException(MslError.JWE_PARSE_ERROR, encName, e); } } catch (final JSONException e) { throw new MslCryptoException(MslError.JWE_PARSE_ERROR, header, e); } // Confirm header matches. if (!this.algo.equals(algo) || !this.enc.equals(enc)) throw new MslCryptoException(MslError.JWE_ALGORITHM_MISMATCH, header); // Decrypt the CEK. final KeyParameter cek; try { final byte[] cekBytes = cekCryptoContext.decrypt(ecek); cek = new KeyParameter(cekBytes); } catch (final ArrayIndexOutOfBoundsException e) { // Thrown if the encrypted content encryption key is an invalid // length. throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e); } // Create additional authenticated data. final String aad = headerB64 + "." + ecekB64 + "." + ivB64; // Determine algorithm byte lengths. final int keylen, atlen; if (Encryption.A128GCM.equals(enc)) { keylen = A128_GCM_KEY_LENGTH; atlen = A128_GCM_AT_LENGTH; } else if (Encryption.A256GCM.equals(enc)) { keylen = A256_GCM_KEY_LENGTH; atlen = A256_GCM_AT_LENGTH; } else { throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name()); } // Verify algorithm parameters. if (cek.getKey().length != keylen) throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, "content encryption key length: " + cek.getKey().length); if (at.length != atlen / Byte.SIZE) throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, "authentication tag length: " + at.length); // TODO: AES-GCM is not available via the JCE. // // Create and initialize the cipher for decryption. final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine()); final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8)); plaintextCipher.init(false, params); // Decrypt the ciphertext. try { // Reconstruct the ciphertext and authentication tag. final byte[] ciphertextAtag = Arrays.copyOf(ciphertext, ciphertext.length + at.length); System.arraycopy(at, 0, ciphertextAtag, ciphertext.length, at.length); int plen = plaintextCipher.getOutputSize(ciphertextAtag.length); byte[] plaintext = new byte[plen]; // Decrypt the ciphertext and get the resulting plaintext length // which will be used for the authentication tag offset. int offset = plaintextCipher.processBytes(ciphertextAtag, 0, ciphertextAtag.length, plaintext, 0); // Verify the authentication tag. plaintextCipher.doFinal(plaintext, offset); return plaintext; } catch (final IllegalStateException e) { throw new MslCryptoException(MslError.UNWRAP_ERROR, e); } catch (final InvalidCipherTextException e) { throw new MslCryptoException(MslError.UNWRAP_ERROR, e); } catch (final ArrayIndexOutOfBoundsException e) { // Thrown if the ciphertext is an invalid length. throw new MslCryptoException(MslError.UNWRAP_ERROR, e); } }
From source file:com.netflix.msl.crypto.SymmetricCryptoContext.java
License:Open Source License
@Override public byte[] sign(final byte[] data) throws MslCryptoException { if (signatureKey == null) throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "No signature key."); try {/* www. ja v a 2 s .co m*/ // Compute the xMac. final byte[] xmac; if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) { final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO); mac.init(signatureKey); xmac = mac.doFinal(data); } else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) { final CipherParameters params = new KeyParameter(signatureKey.getEncoded()); final BlockCipher aes = new AESEngine(); final CMac mac = new CMac(aes); mac.init(params); mac.update(data, 0, data.length); xmac = new byte[mac.getMacSize()]; mac.doFinal(xmac, 0); } else { throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "Unsupported algorithm."); } // Return the signature envelope byte representation. return new MslSignatureEnvelope(xmac).getBytes(); } catch (final NoSuchAlgorithmException e) { throw new MslInternalException("Invalid MAC algorithm specified.", e); } catch (final InvalidKeyException e) { throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e); } }
From source file:com.netflix.msl.crypto.SymmetricCryptoContext.java
License:Open Source License
@Override public boolean verify(final byte[] data, final byte[] signature) throws MslCryptoException { if (signatureKey == null) throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "No signature key."); try {/*from w ww .j a v a 2s . co m*/ // Reconstitute the signature envelope. final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature); // Compute the xMac. final byte[] xmac; if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) { final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO); mac.init(signatureKey); xmac = mac.doFinal(data); } else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) { final CipherParameters params = new KeyParameter(signatureKey.getEncoded()); final BlockCipher aes = new AESEngine(); final CMac mac = new CMac(aes); mac.init(params); mac.update(data, 0, data.length); xmac = new byte[mac.getMacSize()]; mac.doFinal(xmac, 0); } else { throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "Unsupported algorithm."); } // Compare the computed hash to the provided signature. return MslUtils.safeEquals(xmac, envelope.getSignature()); } catch (final MslEncodingException e) { throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e); } catch (final NoSuchAlgorithmException e) { throw new MslInternalException("Invalid MAC algorithm specified.", e); } catch (final InvalidKeyException e) { throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e); } }
From source file:com.nimbusds.jose.crypto.impl.LegacyAESGCM.java
License:Apache License
/** * Creates a new AES cipher./*from www .j a va 2s.c o m*/ * * @param secretKey The AES key. Must not be {@code null}. * @param forEncryption If {@code true} creates an AES encryption * cipher, else creates an AES decryption * cipher. * * @return The AES cipher. */ public static AESEngine createAESCipher(final SecretKey secretKey, final boolean forEncryption) { AESEngine cipher = new AESEngine(); CipherParameters cipherParams = new KeyParameter(secretKey.getEncoded()); cipher.init(forEncryption, cipherParams); return cipher; }
From source file:com.raphfrk.craftproxyclient.net.protocol.p16x.P16xProtocol.java
License:Open Source License
private void enableEncryption(PacketChannel server, PacketChannel client, byte[] serverSecret, byte[] clientSecret) { BufferedBlockCipher outServer = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); BufferedBlockCipher inServer = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); CipherParameters paramsServer = new ParametersWithIV(new KeyParameter(serverSecret), serverSecret); outServer.init(true, paramsServer);/* w w w.ja va 2s. c o m*/ inServer.init(false, paramsServer); BufferedBlockCipher outClient = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); BufferedBlockCipher inClient = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); CipherParameters paramsClient = new ParametersWithIV(new KeyParameter(clientSecret), clientSecret); outClient.init(true, paramsClient); inClient.init(false, paramsClient); client.setWrappedChannel(new CryptByteChannelWrapper(client.getRawChannel(), outClient, inClient)); server.setWrappedChannel(new CryptByteChannelWrapper(server.getRawChannel(), outServer, inServer)); }
From source file:com.raphfrk.craftproxyclient.net.protocol.p17xlogin.P17xLoginProtocol.java
License:Open Source License
private void enableEncryption(PacketChannel server, PacketChannel client, byte[] secret) { BufferedBlockCipher out = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); BufferedBlockCipher in = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8)); CipherParameters params = new ParametersWithIV(new KeyParameter(secret), secret); out.init(true, params);//ww w .java2 s . co m in.init(false, params); // Unencrypted client.setWrappedChannel(client.getRawChannel()); // AES server.setWrappedChannel(new CryptByteChannelWrapper(server.getRawChannel(), out, in)); }
From source file:com.rcythr.masq.util.AES.java
License:Open Source License
/** * Uses inputs to encrypt/decrypt based on the value of encrypt * @param forEncryption if true encrypt, if false decrypt * @param input the data to work with//from w w w . jav a2s .c o m * @param key the key to use * @return the result * * @throws InvalidCipherTextException if something goes wrong */ public static byte[] handle(boolean forEncryption, byte[] input, byte[] key) throws InvalidCipherTextException { CipherParameters cipherParameters = new KeyParameter(key); BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(new AESEngine(), new ZeroBytePadding()); bufferedBlockCipher.init(forEncryption, cipherParameters); int inputOffset = 0; int inputLength = input.length; int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength); byte[] output = new byte[maximumOutputLength]; int outputOffset = 0; int outputLength = 0; int bytesProcessed; bytesProcessed = bufferedBlockCipher.processBytes(input, inputOffset, inputLength, output, outputOffset); outputOffset += bytesProcessed; outputLength += bytesProcessed; bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset); outputOffset += bytesProcessed; outputLength += bytesProcessed; if (outputLength == output.length) { return output; } else { byte[] truncatedOutput = new byte[outputLength]; System.arraycopy(output, 0, truncatedOutput, 0, outputLength); return truncatedOutput; } }
From source file:com.skplanet.jose.jwa.crypto.CryptoUtils.java
License:Open Source License
public static byte[] aesGcmEncrypt(Transformation transformation, byte[] raw, byte[] secret, int atLength, byte[] iv, byte[] aad) throws Exception { BlockCipher blockCipher = new AESEngine(); blockCipher.init(true, new KeyParameter(new SecretKeySpec(secret, "AES").getEncoded())); GCMBlockCipher aGCMBlockCipher = new GCMBlockCipher(blockCipher); aGCMBlockCipher.init(true, new AEADParameters(new KeyParameter(secret), atLength, iv, aad)); int len = aGCMBlockCipher.getOutputSize(raw.length); byte[] out = new byte[len]; int outOff = aGCMBlockCipher.processBytes(raw, 0, raw.length, out, 0); aGCMBlockCipher.doFinal(out, outOff); return out;/* ww w.j av a 2s . c om*/ }