Example usage for javax.crypto Cipher getParameters

List of usage examples for javax.crypto Cipher getParameters

Introduction

In this page you can find the example usage for javax.crypto Cipher getParameters.

Prototype

public final AlgorithmParameters getParameters() 

Source Link

Document

Returns the parameters used with this cipher.

Usage

From source file:Main.java

/**
 * Initializes the Cipher for use.//from   w w  w .j  av a2 s .  co  m
 */
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);
    }
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.license.processor2.PacketUtil.java

private static byte[] decryptData(byte[] bInput) {
    byte[] outBytes = null;
    try {/*from w ww.j  a  va2s  .c  o m*/
        Key key = new SecretKeySpec(secret_key, "DESede");

        Cipher cipher = Cipher.getInstance("DESede", "SunJCE");

        cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());

        outBytes = cipher.doFinal(bInput);

    } catch (Exception ex) {
        //log.error("PacketUtil",ex.getMessage(), ex);
        return outBytes;
    }

    return outBytes;
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.license.processor2.PacketUtil.java

private static byte[] encryptData(byte[] content) {
    byte[] outBytes = null;

    try {//from   w  w  w .  j a va  2  s  .  c  o m
        Key key = new SecretKeySpec(secret_key, "DESede");

        Cipher cipher = Cipher.getInstance("DESede", "SunJCE");

        cipher.init(Cipher.ENCRYPT_MODE, key, cipher.getParameters());

        outBytes = cipher.doFinal(content);

    } catch (Exception ex) {
        //log.error("PacketUtil",ex.getMessage(), ex);
        return outBytes;
    }

    return outBytes;
}

From source file:com.screenslicer.common.Crypto.java

private static String decodeHelper(String cipherText, String encryptionKey) {
    if (cipherText == null || encryptionKey == null) {
        return null;
    }//from   ww w .  j a v a  2 s  . c om
    try {
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(DigestUtils.sha256(encryptionKey), "AES"),
                aesCipher.getParameters());
        return new String(aesCipher.doFinal(Base64.decodeBase64(cipherText)), "utf-8");
    } catch (Exception e) {
        return null;
    }
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * /*  w w w  .  j  a  va  2 s  .com*/
 * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
public static String encryptAESPBKDF2(String plainText) throws Exception {

    // get salt
    salt = generateSaltAESPBKDF2();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // 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");

    // encrypt the message
    Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Creates a new {@link FileEncryptionProvider} instance that provides encryption/decryption
 * capabilities based on the specified password.
 * @param password encryption/decryption password.
 * @return a new {@link FileEncryptionProvider} instance.
 * @throws Exception if an error occurs in the execution of the operation.
 */// w  w  w .j ava2s  . c  o m
public static FileEncryptionProvider getInstance(final String password) throws Exception {
    checkArgument(StringUtils.isNotBlank(password), "Uninitialized or invalid password");
    // generate key from password
    final byte[] salt = generateSalt();
    LOGGER.trace("Generated salt: " + Hex.encodeHexString(salt));
    final SecretKey secret = generateKey(password, salt);
    LOGGER.trace("Generated key: " + Hex.encodeHexString(secret.getEncoded()));
    // create encryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encryptCipher.init(Cipher.ENCRYPT_MODE, secret);
    // initialization vector needed by the CBC mode
    final AlgorithmParameters params = encryptCipher.getParameters();
    final byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    // create decryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    decryptCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
    LOGGER.trace(String.format("Encryption/decryption ciphers were created - %s",
            encryptCipher.getProvider().getInfo()));
    return new FileEncryptionProvider(encryptCipher, decryptCipher);
}

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/*from w  w w  .  ja  v  a2s . co  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 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 {
    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 encPass = null;

    try {
        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.ENCRYPT_MODE, sks);

        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);

        byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding));
        byte[] iv = ivParameterSpec.getIV();

        String combined = Base64.getEncoder().encodeToString(iv) + ":"
                + Base64.getEncoder().encodeToString(cryptoText);

        encPass = Base64.getEncoder().encodeToString(combined.getBytes());
    } 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 (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    } catch (InvalidParameterSpecException ipsx) {
        throw new SecurityException(ipsx.getMessage(), ipsx);
    }

    return encPass;
}

From source file:password.pwm.util.secure.SecureEngine.java

public static byte[] encryptToBytes(final String value, final PwmSecurityKey key,
        final PwmBlockAlgorithm blockAlgorithm) throws PwmUnrecoverableException {
    try {/*  w w w.  j a va  2s  . c  om*/
        if (value == null || value.length() < 1) {
            return null;
        }

        final SecretKey aesKey = key.getKey(blockAlgorithm.getBlockKey());
        final byte[] nonce;
        final Cipher cipher;
        if (blockAlgorithm == PwmBlockAlgorithm.AES128_GCM) {
            nonce = AES_GCM_NONCE_GENERATOR.nextValue();
            final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.ENCRYPT_MODE, aesKey, spec);
        } else {
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.ENCRYPT_MODE, aesKey, cipher.getParameters());
            nonce = null;
        }
        final byte[] encryptedBytes = cipher.doFinal(value.getBytes(PwmConstants.DEFAULT_CHARSET));

        final byte[] output;
        if (blockAlgorithm.getHmacAlgorithm() != null) {
            final byte[] hashChecksum = computeHmacToBytes(blockAlgorithm.getHmacAlgorithm(), key,
                    encryptedBytes);
            output = appendByteArrays(blockAlgorithm.getPrefix(), hashChecksum, encryptedBytes);
        } else {
            if (nonce == null) {
                output = appendByteArrays(blockAlgorithm.getPrefix(), encryptedBytes);
            } else {
                final byte[] nonceLength = new byte[1];
                nonceLength[0] = (byte) nonce.length;
                output = appendByteArrays(blockAlgorithm.getPrefix(), nonceLength, nonce, encryptedBytes);
            }
        }
        return output;

    } catch (Exception e) {
        final String errorMsg = "unexpected error performing simple crypt operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        LOGGER.error(errorInformation.toDebugStr());
        throw new PwmUnrecoverableException(errorInformation);
    }
}

From source file:uk.gov.hmrc.mobiletokenproxy.aes.Decrypter.java

protected byte[] decryptAsBytes(String data, Key key, String algorithm) {
    try {/* ww w . j ava  2  s.  c  o  m*/
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
        return cipher.doFinal(Base64.decodeBase64(data.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
        throw new SecurityException("Failed decrypting data", e);
    }
}

From source file:uk.gov.hmrc.mobiletokenproxy.aes.Encrypter.java

protected String encrypt(byte[] data, Key key, String algorithm) {
    try {/*from  www .  j  a  va 2s  .  c o  m*/
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, cipher.getParameters());
        return new String(Base64.encodeBase64(cipher.doFinal(data)), StandardCharsets.UTF_8);
    } catch (Exception e) {
        throw new SecurityException("Failed encrypting data", e);
    }
}