List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java
/** * De- or encrypt a file.//from w w w . j a v a 2s. c o m * * @param inputFileFullPath * file to en- or decrypt * @param outputFileFullPath * file with result of en-/decryption * @param cipherMode * Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE * @param progress * progress info class to print progress percentage * */ public void doCipherOperation(InputStream in, OutputStream out, long nrOfBytesToCipher, int cipherMode, ProgressInfo progress) throws Exception { if (nrOfBytesToCipher > 0) { try { // If the nr of bytes to read is smaller than readBufferSize // use the nr of bytes as the max buffer size. int maxBufferSize = (int) Math.min(readBufferSize, nrOfBytesToCipher); byte[] readBuffer = new byte[maxBufferSize]; if (isInitialized == false) { cipher.init(cipherMode, cipherKey, new IvParameterSpec(initializationVector.getEncoded())); isInitialized = true; } long nrOfBytesLeftToCipher = nrOfBytesToCipher; while (nrOfBytesLeftToCipher > 0) { in.read(readBuffer, 0, maxBufferSize); nrOfBytesLeftToCipher -= cipher.update(readBuffer, 0, maxBufferSize, readBuffer); // If a ProgressInfo was given, calculate the current // percentage and print it if (progress != null) progress.trackAndPrintProgress(); out.write(readBuffer, 0, maxBufferSize); if (nrOfBytesLeftToCipher > 0 && nrOfBytesLeftToCipher < maxBufferSize) { maxBufferSize = (int) nrOfBytesLeftToCipher; } } //cipher.doFinal(); } catch (IOException e) { throw new IOException("Error reading bytes to encrypt: " + e.getMessage()); } 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."); } } else { // Print progress even if nrOfBytesToCipher == 0 if (progress != null) progress.trackAndPrintProgress(); } }
From source file:org.lamsfoundation.lams.admin.web.RegisterAction.java
public static String decrypt(String text, String password) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //setup key//from w ww. j a va 2 s . c om byte[] keyBytes = new byte[16]; byte[] b = password.getBytes("UTF-8"); int len = b.length; if (len > keyBytes.length) len = keyBytes.length; System.arraycopy(b, 0, keyBytes, 0, len); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); BASE64Decoder decoder = new BASE64Decoder(); byte[] results = cipher.doFinal(decoder.decodeBuffer(text)); return new String(results, "UTF-8"); }
From source file:com.gfw.press.encrypt.Encrypt.java
/** * ?/* ww w . ja v a2s . c om*/ * * @param content * ? * @return ?? */ public static String simpleEncrypt(String content, String key) { int SIMPLE_ENCRYPT_KEY_LENGTH = 16; byte[] keyBytes = null; byte[] encrypt = null; byte[] allData = null; try { keyBytes = key.getBytes(CHARSET); byte[] _keyBytes = new byte[SIMPLE_ENCRYPT_KEY_LENGTH]; if (keyBytes.length < SIMPLE_ENCRYPT_KEY_LENGTH) { SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(_keyBytes); System.arraycopy(keyBytes, 0, _keyBytes, 0, keyBytes.length); } else { System.arraycopy(keyBytes, 0, _keyBytes, 0, SIMPLE_ENCRYPT_KEY_LENGTH); } keyBytes = _keyBytes; Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); IvParameterSpec IVSpec = new IvParameterSpec(keyBytes); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES"), IVSpec); encrypt = cipher.doFinal(content.getBytes(CHARSET)); allData = new byte[encrypt.length + keyBytes.length]; System.arraycopy(keyBytes, 0, allData, 0, keyBytes.length); System.arraycopy(encrypt, 0, allData, keyBytes.length, encrypt.length); return encodeBase64(allData); } catch (Exception e) { } finally { keyBytes = encrypt = allData = null; } return ""; }
From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}/* w ww .j av a 2 s . c o m*/ */ @Override public final byte[] aesCbcMac(byte[] data, byte[] bKey) throws McbpCryptoException { byte[] dataWithPadding = addIso7816Padding(data); SecretKey secretKey = new SecretKeySpec(bKey, "AES"); byte[] iv = new byte[16]; // iv is all 0x00 byte[] xorData = null; try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); for (int i = 0, j; i < (dataWithPadding.length / 16); i++) { j = i * 16; xorData = Utils.doXor(dataWithPadding, j, iv, 0, 16); iv = cipher.doFinal(xorData); } byte[] macBytes = new byte[8]; System.arraycopy(iv, 0, macBytes, 0, 8); return macBytes; } catch (Exception e) { throw new McbpCryptoException(e.toString()); } finally { // Clear temporary data structures before returning Utils.clearByteArray(iv); Utils.clearByteArray(dataWithPadding); Utils.clearByteArray(xorData); } }
From source file:net.jmhertlein.core.crypto.Keys.java
/** * Given a secret key and an input stream, wraps the input stream first in a CipherInputStream using the given secret key, then in an ObjectInputStream * * @param key the secret key to use to encrypt data with * @param is the input stream to encrypt and wrap * * @return an ObjectInputStream whose data will be encrypted with the secret key * @throws NoSuchAlgorithmException//from ww w . j av a 2 s . c o m * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IOException */ public static ObjectInputStream getEncryptedObjectInputStream(SecretKey key, InputStream is) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException { Cipher inCipher = Cipher.getInstance("AES/CFB8/NoPadding"); inCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(getKeyBytes(key))); return new ObjectInputStream(new CipherInputStream(is, inCipher)); }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
public String getDecryptedFileName(File file) throws SecrecyCipherStreamException, FileNotFoundException { Cipher c;/*w w w .j a v a2 s. c o m*/ 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(file.getParent() + FILE_HEADER_PREFIX + file.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.getFileNameIV().toByteArray())); } catch (InvalidKeyException e) { throw new SecrecyCipherStreamException("Invalid encryption key!"); } catch (InvalidAlgorithmParameterException e) { throw new SecrecyCipherStreamException("Invalid algorithm parameter!"); } byte[] decryptedFileName; try { decryptedFileName = c.doFinal(fileHeader.getEncryptedFileName().toByteArray()); } catch (IllegalBlockSizeException e) { throw new SecrecyCipherStreamException("Illegal block size!"); } catch (BadPaddingException e) { throw new SecrecyCipherStreamException("Bad padding"); } return new String(decryptedFileName); }
From source file:press.gfw.Encrypt.java
/** * ?//from w w w . ja va 2 s. c om * * @param key * SecretKey * * @param bytes * ? * * @return * [?+?]? + [? + ?] * */ public byte[] encryptNet(SecretKey key, byte[] bytes) { if (key == null || bytes == null || bytes.length == 0) { return null; } byte[] IV = getSecureRandom(IV_SIZE); IvParameterSpec IVSpec = new IvParameterSpec(IV); try { cipher.init(Cipher.ENCRYPT_MODE, key, IVSpec); } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) { log("?Cipher"); ex.printStackTrace(); return null; } // ? byte[] cipher_bytes = null; try { cipher_bytes = cipher.doFinal(bytes); } catch (IllegalBlockSizeException | BadPaddingException ex) { log("?"); ex.printStackTrace(); return null; } // long start = System.currentTimeMillis(); // ? byte[] noise_bytes = (cipher_bytes.length < NOISE_MAX / 2) ? getSecureRandom(secureRandom.nextInt(NOISE_MAX)) : new byte[0]; // long end = System.currentTimeMillis(); // log("" + noise_bytes.length); // log("" + (end - start)); // [IV+?+?]30 byte[] size_bytes = encrypt(key, getBlockSizeBytes((IV_SIZE + cipher_bytes.length), noise_bytes.length)); if (size_bytes == null || size_bytes.length != ENCRYPT_SIZE) { return null; } byte[] all_cipher = new byte[size_bytes.length + IV_SIZE + cipher_bytes.length + noise_bytes.length]; System.arraycopy(size_bytes, 0, all_cipher, 0, size_bytes.length); System.arraycopy(IV, 0, all_cipher, size_bytes.length, IV.length); System.arraycopy(cipher_bytes, 0, all_cipher, size_bytes.length + IV.length, cipher_bytes.length); if (noise_bytes.length > 0) { // ?? System.arraycopy(noise_bytes, 0, all_cipher, size_bytes.length + IV.length + cipher_bytes.length, noise_bytes.length); } size_bytes = null; IV = null; cipher_bytes = null; noise_bytes = null; return all_cipher; }
From source file:servlets.module.challenge.BrokenCryptoHomeMade.java
public static String decryptUserSpecificSolution(String userNameKey, String encryptedSolution) throws GeneralSecurityException, Exception { try {//from w w w .jav a 2 s. c o m String key = createUserSpecificEncryptionKey(userNameKey); 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(encryptedSolution)); return new String(original, Charset.forName("US-ASCII")); } catch (Exception e) { throw new Exception("Decryption Failure: Could not Craft User Key or Ciphertext was Bad"); } }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * initializes a cipher//from www. j a va 2s . com * * @param key the key * @param mode the mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE) * * @return an initialized cipher * * @throws VaSolSimException for all the usual crypto stuff */ public static Cipher initCrypto(byte[] key, int mode) throws VaSolSimException { if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) throw new VaSolSimException(ERROR_MESSAGE_BAD_CIPHER_MODE); byte[] parametricIV = new byte[16]; Cipher cipher; try { //create an IV SecureRandom random = new SecureRandom(); random.nextBytes(parametricIV); //initialize the crypto cipher = Cipher.getInstance(DEFAULT_SERVICE_PROVIDER_INTERFACE, DEFAULT_SERVICE_PROVIDER); cipher.init(mode, new SecretKeySpec(key, DEFAULT_ENCRYPTION_ALGORITHM), new IvParameterSpec(parametricIV)); } catch (NoSuchAlgorithmException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (NoSuchProviderException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (NoSuchPaddingException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (InvalidKeyException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (InvalidAlgorithmParameterException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } return cipher; }
From source file:net.java.jless.tls.Record.java
/** * Sets the key block for the pending state. * * @param keyBlock enough material to set all keys *//* w w w . j ava 2s .co m*/ public void setKeyBlock(int cipherSuite, byte[] keyBlock) { try { // assume TLS_RSA_WITH_RC4_128_MD5 macSize = 16; blockSize = 0; int keySize = 16; int ivSize = 0; String keyAlg = "RC4"; String cipherAlg = "RC4"; String macAlg = "MD5"; if (cipherSuite == TLSSocket.TLS_RSA_WITH_3DES_EDE_CBC_SHA) { cipherAlg = "DESede/CBC/NoPadding"; keyAlg = "DESede"; macAlg = "SHA-1"; macSize = 20; blockSize = 8; keySize = 24; ivSize = 8; } else if (cipherSuite == TLSSocket.TLS_RSA_WITH_AES_128_CBC_SHA) { cipherAlg = "AES/CBC/NoPadding"; keyAlg = "AES"; macAlg = "SHA-1"; macSize = 20; blockSize = 16; keySize = 16; ivSize = 16; } byte[] clientWriteMACSecret = sub(keyBlock, 0, macSize); byte[] serverWriteMACSecret = sub(keyBlock, macSize, macSize); byte[] clientWriteKey = sub(keyBlock, 2 * macSize, keySize); byte[] serverWriteKey = sub(keyBlock, 2 * macSize + keySize, keySize); byte[] clientWriteIV = sub(keyBlock, 2 * (macSize + keySize), ivSize); byte[] serverWriteIV = sub(keyBlock, 2 * (macSize + keySize) + ivSize, ivSize); hmacClientWrite = new HMAC(MessageDigest.getInstance(macAlg), clientWriteMACSecret); hmacServerWrite = new HMAC(MessageDigest.getInstance(macAlg), serverWriteMACSecret); encryptCipher = Cipher.getInstance(cipherAlg); decryptCipher = Cipher.getInstance(cipherAlg); // no IV for RC4 if (cipherSuite == TLSSocket.TLS_RSA_WITH_RC4_128_MD5) { encryptCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(clientWriteKey, keyAlg)); decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(serverWriteKey, keyAlg)); } else { encryptCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(clientWriteKey, keyAlg), new IvParameterSpec(clientWriteIV)); decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(serverWriteKey, keyAlg), new IvParameterSpec(serverWriteIV)); } log("client write key: " + Hex.b2s(clientWriteKey)); log("client write iv : " + Hex.b2s(clientWriteIV)); log("server write key: " + Hex.b2s(serverWriteKey)); log("server write iv : " + Hex.b2s(serverWriteIV)); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }