List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:com.microsoft.azure.storage.queue.CloudQueueEncryptionTests.java
@Test public void testQueueMessageValidateEncryption() throws StorageException, JsonProcessingException, IOException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InterruptedException, ExecutionException { // Create the Key to be used for wrapping. SymmetricKey aesKey = TestHelper.getSymmetricKey(); byte[] messageBytes = new byte[100]; Random rand = new Random(); rand.nextBytes(messageBytes);//from w w w . j ava2 s .c om String inputMessage = Base64.encode(messageBytes); CloudQueueMessage message = new CloudQueueMessage(inputMessage); this.queue.setShouldEncodeMessage(false); QueueRequestOptions options = new QueueRequestOptions(); options.setEncryptionPolicy(new QueueEncryptionPolicy(aesKey, null)); // add message this.queue.addMessage(message, 0, 0, options, null); // Retrieve message without decrypting CloudQueueMessage retrMessage = this.queue.retrieveMessage(); // Decrypt locally CloudQueueMessage decryptedMessage; CloudQueueEncryptedMessage encryptedMessage = CloudQueueEncryptedMessage .deserialize(retrMessage.getMessageContentAsString()); EncryptionData encryptionData = encryptedMessage.getEncryptionData(); byte[] contentEncryptionKey = aesKey.unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(), encryptionData.getWrappedContentKey().getAlgorithm()).get(); SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES"); Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); myAes.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(encryptionData.getContentEncryptionIV())); byte[] src = Base64.decode(encryptedMessage.getEncryptedMessageContents()); decryptedMessage = new CloudQueueMessage(myAes.doFinal(src, 0, src.length)); assertArrayEquals(message.getMessageContentAsByte(), decryptedMessage.getMessageContentAsByte()); }
From source file:io.syndesis.rest.v1.state.ClientSideState.java
static byte[] decrypt(final String encryptionAlgorithm, final byte[] iv, final byte[] encrypted, final SecretKey encryptionKey) { try {//from w ww . ja va 2s .c om final Cipher cipher = Cipher.getInstance(encryptionAlgorithm); cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); return cipher.doFinal(encrypted); } catch (final GeneralSecurityException e) { throw new IllegalStateException("Unable to encrypt the given value", e); } }
From source file:com.eucalyptus.auth.crypto.StringCrypto.java
public String decrypt(byte[] stringEncoded, String secret) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { final byte[] keyBytes = makeKey(secret); byte[] stringEncrypted = UrlBase64.decode(stringEncoded); final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance(this.symmetricFormat); cipher.init(Cipher.DECRYPT_MODE, key, iv); return new String(cipher.doFinal(stringEncrypted)); }
From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}// w w w. java 2 s . co m */ @Override public final byte[] des3(byte[] data, byte[] bKey, Mode mode) throws McbpCryptoException { if (bKey.length != 24 && bKey.length != 16) { throw new McbpCryptoException("Invalid 3DES key length: " + bKey.length); } // We store the key in a temporary vector in case we need to extend it byte[] extendedKey = new byte[24]; // Extend the key to 24 bytes, if only 16 are provided System.arraycopy(bKey, 0, extendedKey, 0, bKey.length); if (bKey.length == 16) { System.arraycopy(bKey, 0, extendedKey, 16, 8); } final SecretKey key = new SecretKeySpec(extendedKey, "DESede"); try { Cipher cipher = Cipher.getInstance("DESede/CBC/noPadding"); final IvParameterSpec ips = new IvParameterSpec(new byte[8]); if (mode == Mode.ENCRYPT) { cipher.init(Cipher.ENCRYPT_MODE, key, ips); } else { cipher.init(Cipher.DECRYPT_MODE, key, ips); } return cipher.doFinal(data); } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { throw new McbpCryptoException(e.toString()); } finally { // We clear the temporary key. For secure implementation the caller must delete the // original key used for encryption / decryption Utils.clearByteArray(extendedKey); } }
From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java
/** * Encrypt or decrypt data with AES with key length other than 256 bits. * * @param finalKey The final key obtained with via {@link #calcFinalKey()}. * @param data The data to encrypt.//from w w w .ja va 2 s . c om * @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 encryptDataAESother(byte[] finalKey, InputStream data, OutputStream output, boolean decrypt) throws IOException { byte[] iv = new byte[16]; int ivSize = data.read(iv); if (ivSize != iv.length) { throw new IOException("AES initialization vector not fully read: only " + ivSize + " bytes read instead of " + iv.length); } try { Cipher decryptCipher; try { decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { // should never happen throw new RuntimeException(e); } SecretKey aesKey = new SecretKeySpec(finalKey, "AES"); IvParameterSpec ips = new IvParameterSpec(iv); decryptCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, aesKey, ips); byte[] buffer = new byte[256]; int n; while ((n = data.read(buffer)) != -1) { output.write(decryptCipher.update(buffer, 0, n)); } output.write(decryptCipher.doFinal()); } catch (InvalidKeyException e) { throw new IOException(e); } catch (InvalidAlgorithmParameterException e) { throw new IOException(e); } catch (NoSuchPaddingException e) { throw new IOException(e); } catch (IllegalBlockSizeException e) { throw new IOException(e); } catch (BadPaddingException e) { throw new IOException(e); } }
From source file:Networking.Client.java
public void PRF() { try {/*from w ww . j a v a2 s. c o m*/ SecretKeySpec myKey = new SecretKeySpec(this.node.getHashed_key_128(), "AES"); byte[] plainText = new byte[128]; byte[] ones = new byte[16]; Arrays.fill(ones, (byte) 1); SecureRandom random = new SecureRandom(); byte IV[] = new byte[16]; random.nextBytes(IV); IvParameterSpec iv = new IvParameterSpec(IV); Cipher c = Cipher.getInstance("AES/CTR/NoPadding"); c.init(Cipher.ENCRYPT_MODE, myKey, iv); byte[] macKey = new byte[c.getOutputSize(plainText.length)]; c.doFinal(plainText, 0, plainText.length, macKey); this.node.setMacKey(macKey); Cipher c1 = Cipher.getInstance("AES/CTR/NoPadding"); c1.init(Cipher.ENCRYPT_MODE, myKey, iv); byte[] sessionKey = new byte[c1.getOutputSize(ones.length)]; c1.doFinal(ones, 0, ones.length, sessionKey); this.node.setSessionKey(sessionKey); } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (ShortBufferException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java
/** * Get the cipher for the key protecting the saved password for a file *//*from w ww . j a va2 s. c o m*/ @TargetApi(Build.VERSION_CODES.M) private Cipher getKeyCipher(Uri fileUri, boolean encrypt) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { String keyName = getPrefsKey(fileUri); KeyStore keystore = getKeystore(); Key key = keystore.getKey(keyName, null); if (key == null) { throw new IOException(itsContext.getString(R.string.key_not_found, fileUri)); } Cipher ciph = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (encrypt) { ciph.init(Cipher.ENCRYPT_MODE, key); } else { SharedPreferences prefs = getPrefs(); String ivStr = prefs.getString(getIvPrefsKey(keyName), null); if (TextUtils.isEmpty(ivStr)) { throw new IOException("Key IV not found for " + fileUri); } byte[] iv = Base64.decode(ivStr, Base64.NO_WRAP); ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } return ciph; }
From source file:org.axiom_tools.crypto.Symmetric.java
private IvParameterSpec buildSeed() throws Exception { return new IvParameterSpec(Hex.decodeHex(getSeedValue().toCharArray())); }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding/* w ww. j av a 2s . c o m*/ * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String decryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String decPass = null; try { String decoded = new String(Base64.getDecoder().decode(value)); String iv = decoded.split(":")[0]; String property = decoded.split(":")[1]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv))); decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidAlgorithmParameterException iapx) { throw new SecurityException(iapx.getMessage(), iapx); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } return decPass; }
From source file:com.wallellen.wechat.common.util.crypto.WxCryptUtil.java
/** * .// ww w . jav a 2 s. co m * * @param cipherText ? * @return */ public String decrypt(String cipherText) { byte[] original; try { // ?AESCBC? Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); // BASE64? byte[] encrypted = Base64.decodeBase64(cipherText); // original = cipher.doFinal(encrypted); } catch (Exception e) { throw new RuntimeException(e); } String xmlContent, from_appid; try { // ? byte[] bytes = PKCS7Encoder.decode(original); // 16??,?AppId byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); int xmlLength = bytesNetworkOrder2Number(networkOrder); xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET); from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET); } catch (Exception e) { throw new RuntimeException(e); } // appid?? if (!from_appid.equals(appidOrCorpid)) { throw new RuntimeException("AppID?"); } return xmlContent; }