Example usage for javax.crypto.spec IvParameterSpec IvParameterSpec

List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec

Introduction

In this page you can find the example usage for javax.crypto.spec IvParameterSpec IvParameterSpec.

Prototype

public IvParameterSpec(byte[] iv) 

Source Link

Document

Creates an IvParameterSpec object using the bytes in iv as the IV.

Usage

From source file:adminpassword.AESDemo.java

@SuppressWarnings("static-access")
public String decrypt(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(password.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");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {/*from  w ww. ja  va 2  s.c o  m*/
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

From source file:com.jwt.security.auth.cryptographics.Crypto.java

private byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {
    try {//ww w.j  a v  a  2  s.  c  o m
        cipher.init(encryptMode, key, new IvParameterSpec(hex(iv)));
        return cipher.doFinal(bytes);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException e) {
        throw fail(e);
    }
}

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a String, it is decoded and the result is returned as a String as well.
 * @param encodedUrl is a String that have the full data encrypted
 * @return decoded String//w  w w.j a  va  2  s  .  c o m
 */
public static String decode(String encodedUrl) {

    try {

        //Decode URL
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));

        String result = new String(cipher.doFinal(Base64.decodeBase64(encodedUrl)));

        //Extract and remove hash from JSONObject
        JSONParser parser = new JSONParser();
        JSONObject receivedData = (JSONObject) parser.parse(result);
        String receivedHash = (String) receivedData.get("hash");
        receivedData.remove("hash");

        //Compare received hash with newly computed hash
        if (checkDataValidity(receivedData)) {
            byte[] hashOfData = createMD5Hash(receivedData);

            if (receivedHash.equals(new String(hashOfData, "UTF-8"))) { //Valid data
                return receivedData.toString();
            }
        }
    } catch (Exception e) {
    } //Invalid data (including encryption algorithm exceptions

    return null;
}

From source file:org.mozilla.android.sync.crypto.Cryptographer.java

/**
 * @param info CryptoInfo to be encrypted
 * @return encrypted CryptoInfo/*w ww  . j a v  a  2 s. com*/
 * @throws CryptoException on error
 */
public static CryptoInfo encrypt(CryptoInfo info) throws CryptoException {

    Cipher cipher = getCipher();
    try {
        byte[] encryptionKey = info.getKeys().getEncryptionKey();
        SecretKeySpec spec = new SecretKeySpec(encryptionKey, KEY_ALGORITHM_SPEC);

        // If no IV is provided, we allow the cipher to provide one.
        if (info.getIV() == null || info.getIV().length == 0) {
            cipher.init(Cipher.ENCRYPT_MODE, spec);
        } else {
            System.out.println("IV is " + info.getIV().length);
            cipher.init(Cipher.ENCRYPT_MODE, spec, new IvParameterSpec(info.getIV()));
        }
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(ex);
    }

    // Encrypt.
    byte[] encryptedBytes = commonCrypto(cipher, info.getMessage());
    info.setMessage(encryptedBytes);

    // Save IV.
    info.setIV(cipher.getIV());

    // Generate HMAC.
    info.setHMAC(generateHMAC(info));

    return info;

}

From source file:org.apache.hadoop.hbase.io.crypto.aes.CommonsCryptoAESEncryptor.java

@Override
public OutputStream createEncryptionStream(OutputStream out) {
    if (!initialized) {
        reset();/*from  w  ww.j a v  a 2s .  c om*/
    }
    try {
        return new CryptoOutputStream(cipherMode, properties, out, key, new IvParameterSpec(iv));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tremolosecurity.proxy.filters.RetreiveIdToken.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    HashMap<String, OpenIDConnectIdP> idps = (HashMap<String, OpenIDConnectIdP>) GlobalEntries
            .getGlobalEntries().get(OpenIDConnectIdP.UNISON_OPENIDCONNECT_IDPS);

    OpenIDConnectIdP idp = idps.get(this.idpName);
    if (idp == null) {
        throw new ServletException("Could not find idp '" + this.idpName + "'");
    }//from  www  . java  2s  .  co  m
    Gson gson = new Gson();
    String json = this.inflate(request.getParameter("refresh_token").getValues().get(0));
    Token token = gson.fromJson(json, Token.class);

    byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());

    IvParameterSpec spec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, GlobalEntries.getGlobalEntries().getConfigManager()
            .getSecretKey(idp.getTrusts().get(this.trustName).getCodeLastmileKeyName()), spec);

    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String refreshToken = new String(cipher.doFinal(encBytes));

    OIDCSession session = idp.getSessionByRefreshToken(refreshToken);

    if (session == null) {
        response.setStatus(401);
    } else {
        response.getWriter().print(session.getIdToken());
    }

}

From source file:edu.kit.dama.util.CryptUtil.java

/**
 * Hidden constuctor.//from w w w  . j  a va2 s.  c o  m
 *
 * @param pSecret The secret used for the SecretKeySpec. The secret must
 * have a length of 128, 192 or 256 bits.
 */
private CryptUtil(byte[] pSecret) {
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(pSecret, "AES");
        deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastleProvider());
        deCipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
        enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastleProvider());
        enCipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException e) {
        throw new IllegalStateException("Failed to create cipher instances.", e);
    }
}

From source file:it.scoppelletti.programmerpower.security.spi.IVParameterSpecFactory.java

public AlgorithmParameterSpec newInstance(Properties props, String prefix) {
    String name, value;//  w  w  w .ja  va  2 s  . c om
    byte[] iv;
    AlgorithmParameterSpec param;

    name = Strings.concat(prefix, IVParameterSpecFactory.PROP_IV);
    value = props.getProperty(name);
    if (Strings.isNullOrEmpty(value)) {
        throw new ArgumentNullException(name);
    }

    try {
        iv = Hex.decodeHex(value.toCharArray());
    } catch (DecoderException ex) {
        throw SecurityUtils.toSecurityException(ex);
    }

    param = new IvParameterSpec(iv);

    return param;
}

From source file:com.aqnote.shared.encrypt.symmetric.Blowfish.java

/**
 * ??// w  w w .j  a  va 2  s  . c  om
 * 
 * @return AlgorithmParameterSpec
 */
private static AlgorithmParameterSpec generateIV() {
    byte[] algorithmBytes = new byte[] { 20, -114, -36, -120, -36, -37, 48, 92 };
    return new IvParameterSpec(algorithmBytes);
}

From source file:cipher.UsableCipher.java

private void initCipher(int opmode) throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (transformation.requiresInitializationVector()) {
        cipher.init(opmode, key, new IvParameterSpec(new byte[8]));
    } else {/*  w ww  . ja  va 2s.  co m*/
        cipher.init(opmode, key);
    }
}