List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:org.apache.nifi.registry.properties.AESSensitivePropertyProvider.java
/** * Returns the decrypted plaintext./*from w ww .j a v a 2 s . com*/ * * @param protectedValue the cipher text read from the {@code nifi.properties} file * @return the raw value to be used by the application * @throws SensitivePropertyProtectionException if there is an error decrypting the cipher text */ @Override public String unprotect(String protectedValue) throws SensitivePropertyProtectionException { if (protectedValue == null || protectedValue.trim().length() < MIN_CIPHER_TEXT_LENGTH) { throw new IllegalArgumentException( "Cannot decrypt a cipher text shorter than " + MIN_CIPHER_TEXT_LENGTH + " chars"); } if (!protectedValue.contains(DELIMITER)) { throw new IllegalArgumentException("The cipher text does not contain the delimiter " + DELIMITER + " -- it should be of the form Base64(IV) || Base64(cipherText)"); } protectedValue = protectedValue.trim(); final String IV_B64 = protectedValue.substring(0, protectedValue.indexOf(DELIMITER)); byte[] iv = Base64.decode(IV_B64); if (iv.length < IV_LENGTH) { throw new IllegalArgumentException( "The IV (" + iv.length + " bytes) must be at least " + IV_LENGTH + " bytes"); } String CIPHERTEXT_B64 = protectedValue.substring(protectedValue.indexOf(DELIMITER) + 2); // Restore the = padding if necessary to reconstitute the GCM MAC check if (CIPHERTEXT_B64.length() % 4 != 0) { final int paddedLength = CIPHERTEXT_B64.length() + 4 - (CIPHERTEXT_B64.length() % 4); CIPHERTEXT_B64 = StringUtils.rightPad(CIPHERTEXT_B64, paddedLength, '='); } try { byte[] cipherBytes = Base64.decode(CIPHERTEXT_B64); cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(iv)); byte[] plainBytes = cipher.doFinal(cipherBytes); logger.debug(getName() + " decrypted a sensitive value successfully"); return new String(plainBytes, StandardCharsets.UTF_8); } catch (BadPaddingException | IllegalBlockSizeException | DecoderException | InvalidAlgorithmParameterException | InvalidKeyException e) { final String msg = "Error decrypting a protected value"; logger.error(msg, e); throw new SensitivePropertyProtectionException(msg, e); } }
From source file:org.chililog.server.common.CryptoUtils.java
/** * <p>// w w w.ja v a 2 s . c om * Encrypt a plain text string using AES. The output is an encrypted plain text string. See * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413 * </p> * <p> * The algorithm used is <code>base64(aes(plainText))</code> * </p> * * * @param plainText * text to encrypt * @param password * password to use for encryption * @return encrypted text * @throws ChiliLogException */ public static String encryptAES(String plainText, 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"); byte[] plainTextBytes = plainText.getBytes("UTF-8"); AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret, paramSpec); byte[] cipherText = cipher.doFinal(plainTextBytes); // Convert hash to string Base64 encoder = new Base64(1000, new byte[] {}, false); return encoder.encodeToString(cipherText); } catch (Exception ex) { throw new ChiliLogException(ex, "Error attempting to encrypt. " + ex.getMessage()); } }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * ???/*from ww w . j a v a 2s . co m*/ * <dl> * <dt>? * <dd>AES??????? * </dl> * @param key ? * @param secured {@link SecuredData ?} * @return */ public byte[] decrypt(final byte[] key, final SecuredData secured) { try { final Cipher cipher = Cipher.getInstance(AES_TRANSFORM_NAME); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, AES_ALGO_NAME), new IvParameterSpec(secured.getVector())); try (final ByteArrayOutputStream stream = new ByteArrayOutputStream();) { stream.write(cipher.doFinal(secured.getEncrypted())); return stream.toByteArray(); } } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | IOException e) { throw new RuntimeException(e); } }
From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java
public byte[] cipherBytes(byte[] bytesToCipher, int cipherMode) throws Exception { if (isInitialized == false) { try {//from ww w . j a v a 2s. c o m cipher.init(cipherMode, cipherKey, new IvParameterSpec(initializationVector.getEncoded())); } catch (InvalidKeyException e) { throw new InvalidKeyException("Error : " + e.getMessage() + "\nKey file corrupt or invalid key parameters." + "\nTo use key sizes above 128 bits please install the JCE Unlimited Strength Jurisdiction Policy Files."); } isInitialized = true; } return cipher.update(bytesToCipher); }
From source file:com.tremolosecurity.proxy.SessionManagerImpl.java
public static TremoloHttpSession findSessionFromCookie(Cookie sessionCookie, SecretKey encKey, SessionManagerImpl sessionMgr) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String tokenHeader = new String( org.bouncycastle.util.encoders.Base64.decode(sessionCookie.getValue().getBytes("UTF-8"))); Gson gson = new Gson(); Token token = gson.fromJson(tokenHeader, Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, encKey, spec); byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest()); String requestToken = new String(cipher.doFinal(encBytes)); TremoloHttpSession tsession = sessionMgr.getSessions().get(requestToken); return tsession; }
From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java
/** * Encrypt or decrypt data with AES256./*from ww w. j a v a 2s .c om*/ * * @param data The data to encrypt. * @param output The output to write the encrypted data to. * @param decrypt true to decrypt the data, false to encrypt it. * * @throws IOException If there is an error reading the data. */ private void encryptDataAES256(InputStream data, OutputStream output, boolean decrypt) throws IOException { byte[] iv = new byte[16]; if (decrypt) { // read IV from stream data.read(iv); } else { // generate random IV and write to stream SecureRandom rnd = new SecureRandom(); rnd.nextBytes(iv); output.write(iv); } Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, keySpec, ivSpec); } catch (GeneralSecurityException e) { throw new IOException(e); } CipherInputStream cis = new CipherInputStream(data, cipher); try { IOUtils.copy(cis, output); } catch (IOException exception) { // starting with java 8 the JVM wraps an IOException around a GeneralSecurityException // it should be safe to swallow a GeneralSecurityException if (!(exception.getCause() instanceof GeneralSecurityException)) { throw exception; } LOG.debug("A GeneralSecurityException occured when decrypting some stream data", exception); } finally { cis.close(); } }
From source file:com.dinochiesa.edgecallouts.AesCryptoCallout.java
public static byte[] aesEncrypt(String cipherName, byte[] key, byte[] iv, byte[] clearText) throws Exception { Cipher cipher = Cipher.getInstance(cipherName); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); byte[] cryptoText = cipher.doFinal(clearText); return cryptoText; }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Encrypt and write the given stream as a full section. Writes section * header and encrypted data starting at the current file offset. When * finished, file offset is at the end of the entire section. *//*from w ww. j a va2 s . c om*/ private int writeSection(RandomAccessFile f, InputStream in) throws IOException, GeneralSecurityException { final long start = f.getFilePointer(); // Write header; we'll come back later to finalize details final Section section = new Section(); section.write(f); final long dataStart = f.getFilePointer(); mRandom.nextBytes(section.iv); final IvParameterSpec ivSpec = new IvParameterSpec(section.iv); mCipher.init(Cipher.ENCRYPT_MODE, mDataKey, ivSpec); mMac.init(mMacKey); int plainLength = 0; byte[] inbuf = new byte[8192]; byte[] outbuf; int n; while ((n = in.read(inbuf)) != -1) { plainLength += n; outbuf = mCipher.update(inbuf, 0, n); if (outbuf != null) { mMac.update(outbuf); f.write(outbuf); } } outbuf = mCipher.doFinal(); if (outbuf != null) { mMac.update(outbuf); f.write(outbuf); } section.setMac(mMac.doFinal()); final long dataEnd = f.getFilePointer(); section.length = dataEnd - dataStart; // Rewind and update header f.seek(start); section.write(f); f.seek(dataEnd); return plainLength; }
From source file:org.apache.myfaces.shared_impl.util.StateUtils.java
private static byte[] symmetric(byte[] data, SecretKey secretKey, String algorithm, String algorithmParams, byte[] iv, int mode) { try {/* www .ja v a2s . c o m*/ // keep local to avoid threading issue Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(mode, secretKey, ivSpec); } else { cipher.init(mode, secretKey); } if (log.isDebugEnabled()) { String action = mode == Cipher.ENCRYPT_MODE ? "encrypting" : "decrypting"; log.debug(action + " w/ " + algorithm + "/" + algorithmParams); } return cipher.doFinal(data); } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/*from ww w.j a v a 2 s .co m*/ testConfiguration(ctx); 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); } }