/* Encrypt the message. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
public PBKDF2Encryptor(final String passPhrase, final byte[] salt, final int iterationCount, final int i1) { this.iterationCount = iterationCount; try { // create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, i1); SecretKey tmp = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // encryptor ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ecipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = ecipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); // decryptor dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); } catch (Exception ex) { throw new IllegalArgumentException(ex); } }
private Cipher createAndInitCipher(SecretKey secretKey) throws GeneralSecurityException { Cipher cipher = provider == null ? Cipher.getInstance(transformation) : Cipher.getInstance(transformation, provider); if (cipherMode == Cipher.ENCRYPT_MODE) { cipher.init(cipherMode, secretKey, generateAlgorithmParameters(parametersAlgorithm, cipherIteration, cipherSalt, null, provider)); algorithmParameters = cipher.getParameters(); } else { if (algorithmParameters != null) { cipher.init(cipherMode, secretKey, algorithmParameters); } else { cipher.init(cipherMode, secretKey, generateAlgorithmParameters(parametersAlgorithm, cipherIteration, cipherSalt, ivSpec, provider)); } } return cipher; }
oos.writeObject(object); oos.flush(); AlgorithmParameters ap = c.getParameters(); this.encodedParams = (ap == null) ? null : ap.getEncoded(); this.paramsAlg = (ap == null) ? null : ap.getAlgorithm();
AlgorithmParameters params = mEcipher.getParameters ();
public static void main(String... args) throws Exception { byte[] data = "hello".getBytes(); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); // 192 and 256 bits may not be available SecretKey secretKey = keyGenerator.generateKey(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // By initializing the cipher in CBC mode, an "initialization vector" has been randomly // generated. This initialization vector will be necessary to decrypt the encrypted data. // It is safe to store the initialization vector in plain text for later use. You can obtain // it's bytes by calling iv.getIV(). cipher.init(Cipher.ENCRYPT_MODE, secretKey); IvParameterSpec iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class); byte[] encryptedData = cipher.doFinal(data); // When decrypting the encrypted data, you must provide the initialization vector used // during the encryption phase. cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); byte[] decryptedData = cipher.doFinal(encryptedData); if (!Arrays.equals(data, decryptedData)) { throw new Exception("Data was not decrypted successfully"); } }
public static String encryptAES(String data, String secretKey) { try { byte[] secretKeys = Arrays.copyOfRange(Hashing.sha256().hashString(secretKey, Charsets.UTF_8) .asBytes(), 0, 16); final SecretKey secret = new SecretKeySpec(secretKeys, "AES"); final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); final AlgorithmParameters params = cipher.getParameters(); final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); final byte[] cipherText = cipher.doFinal(data.getBytes(Charsets.UTF_8)); return DatatypeConverter.printHexBinary(iv) + DatatypeConverter.printHexBinary(cipherText); } catch (Exception e) { throw Throwables.propagate(e); } }
@Override @SneakyThrows public byte[] encrypt(byte[] message) { // create Key final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); byte[] salt = saltGenerator.generateSalt(8); final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations); SecretKey key = factory.generateSecret(keySpec); // Build cipher. final Cipher cipherEncrypt = Cipher.getInstance(algorithm); cipherEncrypt.init(Cipher.ENCRYPT_MODE, key); // Save parameters byte[] params = cipherEncrypt.getParameters().getEncoded(); // Encrypted message byte[] encryptedMessage = cipherEncrypt.doFinal(message); return ByteBuffer .allocate(1 + params.length + encryptedMessage.length) .put((byte) params.length) .put(params) .put(encryptedMessage) .array(); }
@Override OutputStream encrypt(OutputStream output) throws IOException { try { Cipher cipher = InsecureCipherFactory.create(cipherAlgo); cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); if (params == null) { context = EMPTY; } else { context = Base64.encodeBytes(params.getEncoded()); } return new CipherOutputStream(output, cipher); } catch (Exception e) { throw error(e); } }
/** * Encrypts plaintext without specifying mode and padding scheme during {@link Cipher} initialization. * * @param plaintext the plaintext to encrypt as a hexadecimal string * @return ciphertext the ciphertext as a hexadecimal string. */ private static String encryptWithoutSpecifyingAlgorithmParams(String plaintext) throws Exception { SecretKeySpec sks = new SecretKeySpec(StringHelper.hexStringToByteArray(Config.ENCRYPTION_KEY), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); byte[] encrypted = cipher.doFinal(plaintext.getBytes()); return StringHelper.byteArrayToHexString(encrypted); }
@SuppressWarnings("PMD.UnusedPrivateMethod") // false positive private static <T> void saveEncryptedJsonToFile(String fileName, T object, Type typeOfObject) throws Exception { SecretKeySpec sks = new SecretKeySpec(StringHelper.hexStringToByteArray(Config.ENCRYPTION_KEY), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) { CipherOutputStream out = new CipherOutputStream(os, cipher); JsonWriter writer = new JsonWriter(new OutputStreamWriter(out)); getSerializer().toJson(object, typeOfObject, writer); writer.close(); out.close(); } }
String passwordToEncrypt = ....//user entered byte[] passwordToEncryptBytes = passwordToEncrypt.getBytes(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey mySecretKey = keyGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, mySecretKey); IvParameterSpec ivParameter = cipher.getParameters().getParameterSpec(IvParameterSpec.class); byte[] encryptedPasswordData = cipher.doFinal(passwordToEncryptBytes);
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
/** * Initializes the Cipher for use. */ public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException e) { throw new IllegalArgumentException("Unable to access parameter", e); } }
public EncryptionResult encrypt(byte[] plain) throws Exception { byte[] salt = new byte[saltSize]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(salt); SecretKey tmp = getKeyFromPassword(new String(passPhrase), salt); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), alg); Cipher ecipher = Cipher.getInstance(transformation); ecipher.init(Cipher.ENCRYPT_MODE, secret); return new EncryptionResult(salt, ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(), ecipher.doFinal(plain)); }
private Cipher initializeCipher(String keyAlias, String keyPass, String keyStore, String keyStorePassword) throws Exception { Cipher cipher = GenericUtils.initializeBasicCipher(keyAlias, keyPass, keyStore, keyStorePassword, null); AlgorithmParameters params = cipher.getParameters(); initVector = Base64.encode(params.getParameterSpec(IvParameterSpec.class).getIV()); return cipher; }