List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:com.ibasco.agql.examples.base.BaseExample.java
/** * @see <a href="https://gist.github.com/bricef/2436364">https://gist.github.com/bricef/2436364</a> *//*from w w w . ja v a2 s .c o m*/ public static String encrypt(String plainText) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(worldsMostSecureUnhackableKey.getBytes("UTF-8"), "AES"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(worldsMostSecureUnhackableIvKey.getBytes("UTF-8"))); return Base64.getEncoder().encodeToString((cipher.doFinal(padNullBytes(plainText)))); }
From source file:com.ethercamp.harmony.keystore.KeystoreFormat.java
private byte[] processAes(byte[] iv, byte[] keyBytes, byte[] cipherText, int encryptMode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); // Mode/*from w ww . ja v a 2 s .c om*/ Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); cipher.init(encryptMode, key, ivSpec); return cipher.doFinal(cipherText); }
From source file:de.digiway.rapidbreeze.client.infrastructure.cnl.ClickAndLoadHandler.java
private String decrypt(final byte[] b, final byte[] key) { try {//from w w w . ja v a 2 s . c o m final Cipher cipher; final IvParameterSpec ivSpec = new IvParameterSpec(key); final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec); return new String(cipher.doFinal(b), "UTF-8"); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException ex) { throw new IllegalStateException("Error occured during decryption.", ex); } }
From source file:org.apache.nifi.processors.standard.util.crypto.AESKeyedCipherProvider.java
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, SecretKey key, byte[] iv, boolean encryptMode) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException { if (encryptionMethod == null) { throw new IllegalArgumentException("The encryption method must be specified"); }//from w ww .ja v a 2 s. c o m if (!encryptionMethod.isKeyedCipher()) { throw new IllegalArgumentException(encryptionMethod.name() + " requires a PBECipherProvider"); } String algorithm = encryptionMethod.getAlgorithm(); String provider = encryptionMethod.getProvider(); if (key == null) { throw new IllegalArgumentException("The key must be specified"); } if (!isValidKeyLength(key)) { throw new IllegalArgumentException( "The key must be of length [" + StringUtils.join(VALID_KEY_LENGTHS, ", ") + "]"); } Cipher cipher = Cipher.getInstance(algorithm, provider); final String operation = encryptMode ? "encrypt" : "decrypt"; boolean ivIsInvalid = false; // If an IV was not provided already, generate a random IV and inject it in the cipher int ivLength = cipher.getBlockSize(); if (iv.length != ivLength) { logger.warn("An IV was provided of length {} bytes for {}ion but should be {} bytes", iv.length, operation, ivLength); ivIsInvalid = true; } final byte[] emptyIv = new byte[ivLength]; if (Arrays.equals(iv, emptyIv)) { logger.warn("An empty IV was provided of length {} for {}ion", iv.length, operation); ivIsInvalid = true; } if (ivIsInvalid) { if (encryptMode) { logger.warn( "Generating new IV. The value can be obtained in the calling code by invoking 'cipher.getIV()';"); iv = generateIV(); } else { // Can't decrypt without an IV throw new IllegalArgumentException("Cannot decrypt without a valid IV"); } } cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); return cipher; }
From source file:com.mb.framework.util.SecurityUtil.java
/** * //from w ww . j av a 2 s. c o m * This method is used for decrypt by using Algorithm - AES/CBC/PKCS5Padding * * @param String * @return String * @throws Exception */ @SuppressWarnings("static-access") public static String decryptAESPBKDF2(String encryptedText) throws Exception { byte[] saltBytes = salt.getBytes("UTF-8"); byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText); // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // Decrypt the message Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); byte[] decryptedTextBytes = null; try { decryptedTextBytes = cipher.doFinal(encryptedTextBytes); } catch (IllegalBlockSizeException e) { LOGGER.error("error " + e.getMessage()); } catch (BadPaddingException e) { LOGGER.error("error " + e.getMessage()); } return new String(decryptedTextBytes); }
From source file:com.joyent.manta.client.crypto.AbstractAesCipherDetails.java
@Override public AlgorithmParameterSpec getEncryptionParameterSpec(final byte[] iv) { Validate.notNull(iv, "Initialization vector must not be null"); Validate.isTrue(iv.length == getIVLengthInBytes(), "Initialization vector has the wrong byte count [%d] " + "expected [%d] bytes", iv.length, getIVLengthInBytes());// w w w.ja va 2 s . c o m return new IvParameterSpec(iv); }
From source file:org.apigw.commons.crypto.ApigwCrypto.java
/** * Will init the global salt / IV, this salt should not be stored together with encrypted values. */// ww w . ja v a 2s . c om private byte[] initSalt() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { byte[] encryptedSalt = Base64.decodeBase64(encodedEncryptedSalt.getBytes()); Key saltKey = saltKeyStore.getKey(saltKeyAlias, saltKeyPassword.toCharArray()); validateKey(saltKey); String algorithm = saltKey.getAlgorithm(); int size = saltKey.getEncoded().length * 8; log.debug("initializing salt using {} key with size {}", algorithm, size); SecretKeySpec skeySpec = new SecretKeySpec(saltKey.getEncoded(), KEY_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(getIV(encryptedSalt)); Cipher decryptCipher = Cipher.getInstance(TRANSFORMATION, securityProvider); decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec); byte[] decryptedSalt = decryptCipher.doFinal(encryptedSalt); return removeIV(decryptedSalt); }
From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java
public void validate(final String filename, final String password) throws Exception { String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED), "."); ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename)); byte[] initVector = null; byte[] encryptedSampleBytes = null; Enumeration<? extends ZipEntry> entries = encryptedFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); initVector = FileCopyUtils.copyToByteArray(inputStream); if (initVector.length != IV_SIZE) { throw new Exception("Secret file is corrupted or invalid secret file are being used."); }/*from ww w .j a v a2 s . c o m*/ } else if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(inputStream, baos); encryptedSampleBytes = baos.toByteArray(); } } if (initVector != null && encryptedSampleBytes != null) { SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY); KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128); SecretKey tmp = factory.generateSecret(spec); // generate the secret key SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); // create the cipher Cipher cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector)); // decrypt the sample ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedSampleBytes); CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(cipherInputStream, baos); String sampleText = baos.toString(); if (!sampleText.contains("This is sample text")) { throw new Exception("Upload parameters incorrect!"); } } }
From source file:com.diona.fileReader.CipherUtil.java
/** * Encrypts a file./*from www . j a v a2 s . c om*/ * * @param path * path of the original file. * @param context * context to fetch preferences. * @param encryptPath * path of the encrypted file. */ public long encryptFile(final String path, final String encryptPath, final Context context) { long empty = 123456789L; Date d1 = new Date(); // Transaction.checkLongRunningProcessing("encryptFile"); //System.err.println("Path = "+path); //System.err.println("encryptPath = "+encryptPath); try { //System.err.println("EN - 1"); // Here you read the cleartext. final FileInputStream fis = new FileInputStream(path); // This stream write the encrypted text. This stream will be wrapped by another stream. final FileOutputStream fos = new FileOutputStream(encryptPath); final OutputStream outputStream; if (ENCRYPTION_ENABLED) { //System.err.println("EN - 2"); final SecretKeySpec secret = usedSecretKey = getSecretKey(context); final byte[] ivBytes = usedIV = getIV(context); ivspec = new IvParameterSpec(ivBytes); //System.err.println("EN - 3"); // Create cipher final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secret, ivspec); //System.err.println("EN - 4"); // Wrap the output stream outputStream = new CipherOutputStream(fos, cipher); //System.err.println("EN - 5"); } else { outputStream = fos; } // Write bytes int b; //System.err.println("EN - 6"); final byte[] d = new byte[BUFFER_SIZE]; while ((b = fis.read(d)) != -1) { outputStream.write(d, 0, b); } //System.err.println("EN - 7"); // Flush and close streams. outputStream.flush(); outputStream.close(); fis.close(); //System.err.println("EN - 8"); Date d2 = new Date(); long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; System.err.println("File encrypted SUCCESSFULLY. Time = " + diffSeconds); return diffSeconds; //decryptFile(encryptPath, encryptPath+"_decrypted", null); } catch (final Exception e) { Log.e(TAG, "e" + e); return empty; } }
From source file:de.petendi.commons.crypto.HybridCrypto.java
public byte[] decrypt(HybridEncrypted encrypted, String recipientIdentifier, PrivateKey privateKey) { byte[] encryptedPassphrase = encrypted.getRecipients().get(recipientIdentifier); try {//from w w w. j a v a 2 s . co m ArrayList<byte[]> splitted = retrieveSecretAndIV(encryptedPassphrase, privateKey); Cipher cipher = Cipher.getInstance(SYMMETRIC_CIPHER_ALGORITHM); SecretKey originalKey = new SecretKeySpec(splitted.get(1), 0, splitted.get(1).length, "AES"); cipher.init(Cipher.DECRYPT_MODE, originalKey, new IvParameterSpec(splitted.get(0))); return cipher.doFinal(encrypted.getEncryptedBody()); } catch (Exception e) { throw new IllegalArgumentException(e); } }