List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) throw new NullPointerException("ExternalContext ctx"); testConfiguration(ctx);/*from w w w .j a v a 2 s. c o m*/ SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:com.dinochiesa.edgecallouts.AesCryptoCallout.java
public static byte[] aesDecrypt(String cipherName, byte[] key, byte[] iv, byte[] cipherText) throws Exception { Cipher cipher = Cipher.getInstance(cipherName); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); byte[] clearText = cipher.doFinal(cipherText); return clearText; }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
@Override public SecrecyCipherInputStream getCipherInputStream(File encryptedFile) throws SecrecyCipherStreamException, FileNotFoundException { Cipher c;// www . j a va 2 s . c om try { c = Cipher.getInstance(encryptionMode); } catch (NoSuchAlgorithmException e) { throw new SecrecyCipherStreamException("Encryption algorithm not found!"); } catch (NoSuchPaddingException e) { throw new SecrecyCipherStreamException("Selected padding not found!"); } File headerFile = new File(encryptedFile.getParent() + FILE_HEADER_PREFIX + encryptedFile.getName()); if (!headerFile.exists()) { throw new FileNotFoundException("Header file not found!"); } FileHeader fileHeader; try { fileHeader = FileHeader.parseFrom(new FileInputStream(headerFile)); } catch (IOException e) { throw new SecrecyCipherStreamException("Cannot parse file header!"); } try { c.init(Cipher.DECRYPT_MODE, vaultFileEncryptionKey, new IvParameterSpec(fileHeader.getFileIV().toByteArray())); } catch (InvalidKeyException e) { throw new SecrecyCipherStreamException("Invalid encryption key!"); } catch (InvalidAlgorithmParameterException e) { throw new SecrecyCipherStreamException("Invalid algorithm parameter!"); } return new SecrecyCipherInputStream(new FileInputStream(encryptedFile), c); }
From source file:eu.dety.burp.joseph.utilities.CryptoTest.java
@Test public void testAES256() throws Exception { Crypto.removeCryptoStrengthRestriction(); Cipher encryptCipher = Cipher.getInstance("AES/CBC/NoPadding", new BouncyCastleProvider()); IvParameterSpec encryptIv = new IvParameterSpec(new byte[16]); SecretKey encryptKey = new SecretKeySpec(new byte[32], "AES"); encryptCipher.init(Cipher.ENCRYPT_MODE, encryptKey, encryptIv); }
From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java
private byte[] decryptBytes(byte[] encryptedBytes, String algorithmUri, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = getCipher(Cipher.DECRYPT_MODE, algorithmUri); // Extract IV from the beginning of the encrypted bytes int ivLen = cipher.getBlockSize(); byte[] ivBytes = new byte[ivLen]; System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); IvParameterSpec iv = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] decryptedData = cipher.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen); return decryptedData; }
From source file:org.chililog.server.common.CryptoUtils.java
/** * <p>/* w w w .j a v a 2 s .c om*/ * Decrypt an encrypted text string using AES. The output is the plain text string. * </p> * * @param encryptedText * encrypted text returned by <code>encrypt</code> * @param password * password used at the time of encryption * @return decrypted plain text string * @throws ChiliLogException */ public static String decryptAES(String encryptedText, String password) throws ChiliLogException { try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); Base64 decoder = new Base64(1000, new byte[] {}, false); byte[] encryptedTextBytes = decoder.decode(encryptedText); AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, paramSpec); byte[] plainTextBytes = cipher.doFinal(encryptedTextBytes); return new String(plainTextBytes, "UTF-8"); } catch (Exception ex) { throw new ChiliLogException(ex, "Error attempting to decrpt. " + ex.getMessage()); } }
From source file:net.jmhertlein.core.crypto.Keys.java
/** * Given a secret key and an output stream, wraps the output stream first in a CipherOutputStream using the given secret key, then in an ObjectOutputStream * * @param key the secret key to use to encrypt data with * @param os the output stream to encrypt and wrap * * @return an ObjectOutputStream whose data will be encrypted with the secret key * @throws NoSuchAlgorithmException//from w ww . j ava 2 s .c om * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IOException */ public static ObjectOutputStream getEncryptedObjectOutputStream(SecretKey key, OutputStream os) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException { Cipher outCipher = Cipher.getInstance("AES/CFB8/NoPadding"); outCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(getKeyBytes(key))); return new ObjectOutputStream(new CipherOutputStream(os, outCipher)); }
From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java
private boolean initialize() { try {//from www .ja v a2 s . co m encryptionReady = false; tokenRefreshRetryCount = TOKEN_REFRESH_RETRY_COUNT; if (Cipher.getMaxAllowedKeyLength("AES") < 256) { return setError(LxOfflineReason.INTERNAL_ERROR, "Enable Java cryptography unlimited strength (see binding doc)."); } // generate a random key for the session KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES"); aesKeyGen.init(256); aesKey = aesKeyGen.generateKey(); // generate an initialization vector secureRandom = new SecureRandom(); secureRandom.nextBytes(initVector); IvParameterSpec ivSpec = new IvParameterSpec(initVector); // initialize aes cipher for command encryption aesEncryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // initialize aes cipher for response decryption aesDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesDecryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec); // get token value from configuration storage token = (String) configuration.get(SETTINGS_TOKEN); logger.debug("[{}] Retrieved token value: {}", debugId, token); } catch (InvalidParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "Invalid parameter: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES not supported on platform."); } catch (InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES cipher initialization failed."); } return true; }
From source file:servlets.module.challenge.BrokenCryptoHomeMade.java
/** * Decrypts data using specific key and ciphertext * @param key Encryption Key (Must be 16 Bytes) * @param encrypted Ciphertext to decrypt * @return Plaintext decrypted from submitted ciphertext and key * @throws GeneralSecurityException//from www . j a v a 2 s . c o m */ public static String decrypt(String key, String encrypted) throws GeneralSecurityException { byte[] raw = key.getBytes(Charset.forName("US-ASCII")); if (raw.length != 16) { throw new IllegalArgumentException("Invalid key size."); } SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); return new String(original, Charset.forName("US-ASCII")); }
From source file:com.meltmedia.jackson.crypto.EncryptionService.java
/** * Creates a decryption cipher for the encrypted value value using `AES/CBC/PKCS5Padding`. The base64 encoded * iv must already be present in the encrypted value. * // w ww . ja v a 2s .c om * @param secret the key to use for decryption. * @param value the value that will decrypted with this cipher. The base64 iv must be present on this value. * @return a cipher that will decrypt the specified value with the specified key. * @throws EncryptionException if the cipher could not be created for any reason. */ Cipher createDecryptionCipher(SecretKey secret, E value) throws EncryptionException { if (Ciphers.AES_256_CBC.equals(value.getCipher()) && KeyDerivations.PBKDF2.equals(value.getKeyDerivation())) { try { SecretKeySpec spec = new SecretKeySpec(secret.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(value.getIv())); return cipher; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException e) { throw new EncryptionException("could not create decryption cypher", e); } } else { throw new EncryptionException(String.format("unsupported cipher %s and key derivation %s", value.getCipher(), value.getKeyDerivation())); } }