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:org.structr.util.StructrLicenseVerifier.java

private void run() {

    try {// w w w.jav a  2 s  . co  m

        logger.info("Listening on port {}", StructrLicenseManager.ServerPort);

        final ServerSocket serverSocket = new ServerSocket(StructrLicenseManager.ServerPort);

        serverSocket.setReuseAddress(true);

        // validation loop
        while (true) {

            try (final Socket socket = serverSocket.accept()) {

                logger.info("##### New connection from {}", socket.getInetAddress().getHostAddress());

                final InputStream is = socket.getInputStream();
                final int bufSize = 4096;

                socket.setSoTimeout(2000);

                // decrypt AES stream key using RSA block cipher
                final byte[] sessionKey = blockCipher.doFinal(IOUtils.readFully(is, 256));
                final byte[] ivSpec = blockCipher.doFinal(IOUtils.readFully(is, 256));
                final byte[] buf = new byte[bufSize];
                int count = 0;

                // initialize cipher using stream key
                streamCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"),
                        new IvParameterSpec(ivSpec));

                // we want to be able to control the number of bytes AND the timeout
                // of the underlying socket, so that we read the available amount of
                // data until the socket times out or we have read all the data.
                try {

                    count = is.read(buf, 0, bufSize);

                } catch (IOException ioex) {
                }

                final byte[] decrypted = streamCipher.doFinal(buf, 0, count);
                final String data = new String(decrypted, "utf-8");

                // transform decrypted data into a Map<String, String>
                final List<Pair> pairs = split(data).stream().map(StructrLicenseVerifier::keyValue)
                        .collect(Collectors.toList());
                final Map<String, String> map = pairs.stream().filter(Objects::nonNull)
                        .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));

                // validate data against customer database
                if (isValid(map)) {

                    // send signatur of name field back to client
                    final String name = (String) map.get(StructrLicenseManager.NameKey);
                    final byte[] response = name.getBytes("utf-8");

                    // respond with the signature of the data sent to us
                    socket.getOutputStream().write(sign(response));
                    socket.getOutputStream().flush();

                } else {

                    logger.info("License verification failed.");
                }

                socket.getOutputStream().close();

            } catch (Throwable t) {
                logger.warn("Unable to verify license: {}", t.getMessage());
            }
        }

    } catch (Throwable t) {
        logger.warn("Unable to verify license: {}", t.getMessage());
    }
}

From source file:org.craftercms.security.authentication.impl.CipheredAuthenticationCookieFactory.java

/**
 * Decrypts the encrypted cookie value, using AES cipher with the initialization vector included in the cookie.
 *//*from w  w  w  . jav a2 s.  co  m*/
protected String decrypt(String encryptedValue, byte[] iv) throws CrafterSecurityException {
    try {
        byte[] encryptedBytes = Base64.decodeBase64(encryptedValue);

        Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv));

        byte[] decryptedValue = cipher.doFinal(encryptedBytes);

        return new String(decryptedValue, "UTF-8");
    } catch (Exception e) {
        throw new CrafterSecurityException("Error while trying to decrypt cookie value", e);
    }
}

From source file:com.z299studio.pb.FingerprintDialog.java

private void initCipher(int mode) {
    try {//from w w w  .j  a  v a  2 s  . c om
        IvParameterSpec ivParams;
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        SecretKey key;
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        if (mode == Cipher.ENCRYPT_MODE) {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                    "AndroidKeyStore");
            keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                            .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
            mCipher.init(mode, keyGenerator.generateKey());
        } else {
            key = (SecretKey) keyStore.getKey(KEY_NAME, null);
            ivParams = new IvParameterSpec(Application.getInstance().getFpIv());
            mCipher.init(mode, key, ivParams);
        }
        mCryptoObject = new FingerprintManager.CryptoObject(mCipher);
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
        Log.e("Pb:FingerprintDialog", "Runtime error in initCipher.");
        Log.e("Pb:FingerprintDialog", e.toString());
    }
}

From source file:de.siegmar.securetransfer.component.Cryptor.java

public InputStream getCryptIn(final InputStream in, final KeyIv keyIv) throws IOException {
    return new CryptoInputStream(TRANSFORM, new Properties(), in, new SecretKeySpec(keyIv.getKey(), "AES"),
            new IvParameterSpec(keyIv.getIv()));
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association setHandle(Association association) throws AssociationException, IOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException {
    ByteArrayOutputStream encodedAssociation = new ByteArrayOutputStream();
    String type = association.getType();
    if (type == Association.TYPE_HMAC_SHA1) {
        encodedAssociation.write(1);//from  w  w  w.j a  v  a  2  s.  com
    } else if (type == Association.TYPE_HMAC_SHA256) {
        encodedAssociation.write(2);
    } else {
        throw new AssociationException("unknown type: " + type);
    }
    SecretKey macKey = association.getMacKey();
    byte[] macKeyBytes = macKey.getEncoded();
    encodedAssociation.write(macKeyBytes);
    Date expiry = association.getExpiry();
    Long time = expiry.getTime();
    DataOutputStream dos = new DataOutputStream(encodedAssociation);
    dos.writeLong(time);
    dos.flush();
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    byte[] iv = new byte[16];
    this.secureRandom.nextBytes(iv);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] handleValue = cipher.doFinal(encodedAssociation.toByteArray());
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    result.write(iv);
    result.write(handleValue);
    if (null != this.macSecretKeySpec) {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] toBeSigned = result.toByteArray();
        byte[] signature = mac.doFinal(toBeSigned);
        result = new ByteArrayOutputStream();
        result.write(signature);
        result.write(iv);
        result.write(handleValue);
    }
    String handle = Base64.encodeBase64URLSafeString(result.toByteArray());
    this.secureRandom.setSeed(result.toByteArray());
    if (handle.getBytes().length > 255) {
        throw new AssociationException("handle size > 255");
    }
    if (type == Association.TYPE_HMAC_SHA1) {
        return Association.createHmacSha1(handle, macKeyBytes, expiry);
    } else if (type == Association.TYPE_HMAC_SHA256) {
        return Association.createHmacSha256(handle, macKeyBytes, expiry);
    }
    throw new AssociationException("unknown type: " + type);
}

From source file:org.slc.sli.encryption.tool.Encryptor.java

public String decrypt(String alias, String password, String algorithm, String initVec, String message)
        throws GeneralSecurityException {
    Key key = keystore.getKey(alias, password.toCharArray());
    Cipher cipher = Cipher.getInstance(algorithm);

    IvParameterSpec ivspec = null;
    if (initVec != null) {
        byte[] ivBytes;
        try {/*from  w  w  w.ja v a2s .  c  o  m*/
            ivBytes = Hex.decodeHex(initVec.toCharArray());
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
        ivspec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.DECRYPT_MODE, (SecretKey) key, ivspec);
    } else {
        cipher.init(Cipher.DECRYPT_MODE, (SecretKey) key);
    }

    byte[] decoded = Base64.decodeBase64(message.getBytes());
    String decrypted = new String(cipher.doFinal(decoded));

    return decrypted;
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException {
    secureRandom = new SecureRandom();
    this.vaultPath = vaultPath;
    this.encryptionMode = encryptionMode;

    File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    if (!headerFile.exists()) {
        try {/*  ww w. j  a v  a2 s.c  o  m*/
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(AES_KEY_SIZE_BIT);
            Key encryptionKey = keyGenerator.generateKey();

            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt);

            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase);
        } catch (Exception e) {
            Util.log("Cannot create vault header!");
            e.printStackTrace();
        }
    }

    try {
        FileInputStream headerInputStream = new FileInputStream(headerFile);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        e.printStackTrace();
    }

    try {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
        SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(),
                vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
        Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
        c.init(Cipher.UNWRAP_MODE, keyFromPassphrase,
                new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));

        vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(),
                KEY_ALGORITHM, Cipher.SECRET_KEY);
    } catch (InvalidKeyException e) {
        throw new InvalidKeyException("Passphrase is wrong!");
    } catch (Exception e) {
        Util.log("Cannot decrypt AES key");
        e.printStackTrace();
    }
}

From source file:org.picketbox.json.enc.JSONWebEncryption.java

/**
 * Encrypt/*from w w  w.j av a 2 s . c o m*/
 *
 * @param plainText
 * @param recipientPublicKey
 * @param contentMasterKey
 * @return
 * @throws ProcessingException
 */
public String encrypt(String plainText, PublicKey recipientPublicKey, byte[] contentMasterKey)
        throws ProcessingException {
    if (jsonWebEncryptionHeader == null) {
        throw PicketBoxJSONMessages.MESSAGES.jsonEncryptionHeaderMissing();
    }
    if (plainText == null) {
        throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("plainText");
    }
    if (recipientPublicKey == null) {
        throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("recipientPublicKey");
    }
    if (contentMasterKey == null) {
        return encrypt(plainText, recipientPublicKey);
    }

    SecretKey contentEncryptionKey = new SecretKeySpec(contentMasterKey, EncUtil.AES);

    // Encrypt using Recipient's public key to yield JWE Encrypted Key
    byte[] jweEncryptedKey = encryptKey(recipientPublicKey, contentMasterKey);
    String encodedJWEKey = PicketBoxJSONUtil.b64Encode(jweEncryptedKey);

    StringBuilder builder = new StringBuilder(PicketBoxJSONUtil.b64Encode(jsonWebEncryptionHeader.toString()));
    builder.append(PERIOD);
    builder.append(encodedJWEKey);

    if (jsonWebEncryptionHeader.needIntegrity()) {
        int cekLength = jsonWebEncryptionHeader.getCEKLength();
        byte[] cek = generateCEK(contentEncryptionKey.getEncoded(), cekLength);

        // Deal with IV
        String iv;
        try {
            iv = jsonWebEncryptionHeader.getDelegate().getString("iv");
        } catch (JSONException e) {
            throw PicketBoxJSONMessages.MESSAGES.ignorableError(e);
        }
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());

        byte[] encryptedText = EncUtil.encryptUsingAES_CBC(plainText, cek, ivParameterSpec);
        String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText);
        builder.append(PERIOD);
        builder.append(encodedJWEText);

        int cikLength = jsonWebEncryptionHeader.getCIKLength();
        byte[] cik = generateCIK(contentEncryptionKey.getEncoded(), cikLength);
        byte[] integrityValue = performMac(cik, builder.toString().getBytes());
        String encodedIntegrityValue = PicketBoxJSONUtil.b64Encode(integrityValue);

        builder.append(PERIOD);
        builder.append(encodedIntegrityValue);
    } else {
        // Encrypt the plain text
        byte[] encryptedText = encryptText(plainText, recipientPublicKey);
        String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText);
        builder.append(PERIOD);
        builder.append(encodedJWEText);
    }

    return builder.toString();
}

From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java

/**
 * Decrypts data./* ww w  . j  a v a2s  . c  o  m*/
 * 
 * @param aesCiphertext
 *          the ciphertext from the message
 * @param decryptionKey
 *          the key to decrypt
 * @param hmacKey
 *          the key to recalculate the HMAC
 * @return the decrypted data
 * @throws CryptorException
 *           if a JCE error occurs
 */
private byte[] decryptData(AES256v2Ciphertext aesCiphertext, SecretKey decryptionKey, SecretKey hmacKey)
        throws CryptorException {

    try {
        Mac mac = Mac.getInstance(HMAC_ALGORITHM);
        mac.init(hmacKey);
        byte[] hmacValue = mac.doFinal(aesCiphertext.getDataToHMAC());

        if (!Arrays.equals(hmacValue, aesCiphertext.getHmac())) {
            throw new InvalidHMACException("Incorrect HMAC value.");
        }

        Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(aesCiphertext.getIv()));

        return cipher.doFinal(aesCiphertext.getCiphertext());
    } catch (GeneralSecurityException e) {
        throw new CryptorException("Failed to decrypt message.", e);
    }
}

From source file:com.gfw.press.encrypt.Encrypt.java

/**
 * //from   w w  w. j  a  v  a  2 s . c  o  m
 * 
 * @param key
 *            SecretKey
 * @param data
 *            ?
 * 
 * @return ?
 * 
 */
private byte[] encrypt(SecretKey key, byte[] data) {
    if (key == null || data == null) {
        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(data);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        log("?");
        ex.printStackTrace();
        return null;
    }
    byte[] iv_cipher_bytes = new byte[cipher_bytes.length + IV_SIZE];
    System.arraycopy(IV, 0, iv_cipher_bytes, 0, IV.length);
    System.arraycopy(cipher_bytes, 0, iv_cipher_bytes, IV.length, cipher_bytes.length);
    return iv_cipher_bytes;
}