Example usage for javax.crypto Cipher UNWRAP_MODE

List of usage examples for javax.crypto Cipher UNWRAP_MODE

Introduction

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

Prototype

int UNWRAP_MODE

To view the source code for javax.crypto Cipher UNWRAP_MODE.

Click Source Link

Document

Constant used to initialize cipher to key-unwrapping mode.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    SecureRandom random = new SecureRandom();

    KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "BC");
    fact.initialize(1024, random);/*from ww  w  .  ja  va 2s .c om*/

    KeyPair keyPair = fact.generateKeyPair();
    Key wrapKey = createKeyForAES(256, random);
    cipher.init(Cipher.WRAP_MODE, wrapKey);

    byte[] wrappedKey = cipher.wrap(keyPair.getPrivate());
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "RSA", Cipher.PRIVATE_KEY);
    System.out.println(keyPair.getPrivate().equals(key));

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    Key sharedKey = kg.generateKey();

    String password = "password";
    byte[] salt = "salt1234".getBytes();
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey passwordKey = kf.generateSecret(keySpec);
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
    c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
    byte[] wrappedKey = c.wrap(sharedKey);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, sharedKey);
    byte[] input = "input".getBytes();
    byte[] encrypted = c.doFinal(input);

    c = Cipher.getInstance("PBEWithMD5AndDES");

    c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
    Key unwrappedKey = c.unwrap(wrappedKey, "DESede", Cipher.SECRET_KEY);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.DECRYPT_MODE, unwrappedKey);
    System.out.println(new String(c.doFinal(encrypted)));
}

From source file:RSATest.java

public static void main(String[] args) {
    try {//from  w ww  . j a  va  2 s  .  co m
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:eu.peppol.security.OxalisCipherConverter.java

/**
 * Creates an instance of OxalisCipher://from   w w  w.  jav  a2 s.  co  m
 * <ol>
 *     <li>Decodes the supplied hex string representation of a wrapped key into an array of bytes representation</li>
 *     <li>Creates a cipher, which is initialized with a private key</li>
 *     <li>Unwraps (decrypts) the secret key represented by an array of bytes into a SecretKey</li>
 *     <li>Creates an OxalisCipher using the unwrapped SecretKey</li>
 * </ol>
 * @param wrappedSymmetricKeyAsHexString
 * @param privateKey
 * @return
 */
public OxalisCipher createCipherFromWrappedHexKey(String wrappedSymmetricKeyAsHexString,
        PrivateKey privateKey) {

    // 1) Decodes the hex string representation of a wrapped key
    byte[] encodedBytes = encodedBytesFromHexString(wrappedSymmetricKeyAsHexString);

    try {
        // 2) Creates the Cipher using supplied private key
        Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM);
        cipher.init(Cipher.UNWRAP_MODE, privateKey);

        // 3) Unwraps (decrypts) the secret key using our private key
        SecretKey secretKey = (SecretKey) cipher.unwrap(encodedBytes, OxalisCipher.SYMMETRIC_KEY_ALGORITHM,
                Cipher.SECRET_KEY);

        // 4) creates the Oxalis cipher
        OxalisCipher oxalisCipher = new OxalisCipher(secretKey);
        return oxalisCipher;

    } catch (NoSuchAlgorithmException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    } catch (NoSuchPaddingException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    } catch (InvalidKeyException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    }
}

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 {/*from   w w w. j  ava2s .  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.cryptomator.crypto.aes256.Aes256Cryptor.java

/**
 * Reads the encrypted masterkey from the given input stream and decrypts it with the given password.
 * /*ww  w  . j  av a 2s .  co m*/
 * @throws DecryptFailedException If the decryption failed for various reasons (including wrong password).
 * @throws WrongPasswordException If the provided password was wrong. Note: Sometimes the algorithm itself fails due to a wrong
 *             password. In this case a DecryptFailedException will be thrown.
 * @throws UnsupportedKeyLengthException If the masterkey has been encrypted with a higher key length than supported by the system. In
 *             this case Java JCE needs to be installed.
 */
@Override
public void decryptMasterKey(InputStream in, CharSequence password)
        throws DecryptFailedException, WrongPasswordException, UnsupportedKeyLengthException, IOException {
    try {
        // load encrypted masterkey:
        final KeyFile keyfile = objectMapper.readValue(in, KeyFile.class);

        // check, whether the key length is supported:
        final int maxKeyLen = Cipher.getMaxAllowedKeyLength(AES_KEY_ALGORITHM);
        if (keyfile.getKeyLength() > maxKeyLen) {
            throw new UnsupportedKeyLengthException(keyfile.getKeyLength(), maxKeyLen);
        }

        // derive key:
        final SecretKey kek = scrypt(password, keyfile.getScryptSalt(), keyfile.getScryptCostParam(),
                keyfile.getScryptBlockSize(), AES_KEY_LENGTH_IN_BITS);

        // decrypt and check password by catching AEAD exception
        final Cipher decCipher = aesKeyWrapCipher(kek, Cipher.UNWRAP_MODE);
        SecretKey primary = (SecretKey) decCipher.unwrap(keyfile.getPrimaryMasterKey(), AES_KEY_ALGORITHM,
                Cipher.SECRET_KEY);
        SecretKey secondary = (SecretKey) decCipher.unwrap(keyfile.getHMacMasterKey(), HMAC_KEY_ALGORITHM,
                Cipher.SECRET_KEY);

        // everything ok, assign decrypted keys:
        this.primaryMasterKey = primary;
        this.hMacMasterKey = secondary;
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalStateException("Algorithm should exist.", ex);
    } catch (InvalidKeyException e) {
        throw new WrongPasswordException();
    }
}

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

@Override
public boolean changePassphrase(String oldPassphrase, String newPassphrase) {
    SecretKeyFactory secretKeyFactory;

    File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW");
    if (!headerFileNew.exists()) {
        try {//from  w w  w . j  av a 2  s  .com
            // Decrypt AES encryption key
            secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(),
                            vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
            Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
            c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase,
                    new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));
            Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM,
                    Cipher.SECRET_KEY);

            // Create new vault nonce and salt
            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt);

            // Create new key for AES key encryption
            SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey,
                    newKeyFromPassphrase);

        } catch (Exception e) {
            Util.log("Error while reading or creating new vault header!");
            return false;
        }
    } else {
        Util.log("New header file already exists. Cannot change passphrase!");
        return false;
    }

    // Try to parse new header file
    try {
        FileInputStream headerInputStream = new FileInputStream(headerFileNew);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        headerFileNew.delete();
        return false;
    }

    // Delete old header file and replace with new header file
    if (!headerFileOld.delete()) {
        headerFileNew.delete();
        Util.log("Cannot delete old vault header!");
        return false;
    }
    try {
        org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld);
    } catch (IOException e) {
        Util.log("Cannot replace old vault header!");
        return false;
    }

    headerFileNew.delete();
    return true;
}

From source file:com.kactech.otj.Utils.java

public static String open(byte[] encryptedEnvelope, PrivateKey privateKey)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String str;/*from w  w w. j  a  v  a  2  s.  c o m*/
    byte[] by;
    ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope);
    buff.order(ByteOrder.BIG_ENDIAN);
    int envType = buff.getShort();// expected 1(asymmetric)
    if (envType != 1)
        throw new UnsupportedOperationException("unexpected envelope type " + envType);
    int arraySize = buff.getInt();// can result in negative integer but not expecting it here
    if (arraySize != 1)//TODO
        throw new UnsupportedOperationException("current code doesn't support multi-nym response");
    byte[] encKeyBytes = null;
    byte[] vectorBytes = null;
    for (int i = 0; i < arraySize; i++) {
        int nymIDLen = buff.getInt();
        by = new byte[nymIDLen];
        buff.get(by);
        String nymID;
        try {
            nymID = new String(by, 0, by.length - 1, Utils.US_ASCII);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } // take nymID W/O trailing \0
          //TODO nymID matching!
        int keyLength = buff.getInt();
        encKeyBytes = new byte[keyLength];
        buff.get(encKeyBytes);
        int vectorLength = buff.getInt();
        vectorBytes = new byte[vectorLength];
        buff.get(vectorBytes);

    }
    byte[] encryptedMsg = new byte[buff.remaining()];
    buff.get(encryptedMsg);

    Cipher cipher;
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY);
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes));
    by = cipher.doFinal(encryptedMsg);
    try {
        str = new String(by, 0, by.length - 1, Utils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } // w/o trailing \0
    return str;
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public SecretKey decryptSecretKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key,
        String keyToDecrypt) throws NetInfCheckedSecurityException {
    try {//ww w.  ja  v a 2 s . c o  m
        LOG.debug("Decrypting SecretKey.");
        LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey);
        LOG.trace("Used algorithm of encrypted key: " + algorithmKeyIsUsedFor);
        LOG.trace("Used key: " + key);
        LOG.trace("Used key to be decrypted: " + keyToDecrypt);
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.UNWRAP_MODE, key);
        return (SecretKey) cipher.unwrap(Base64.decodeBase64(keyToDecrypt), algorithmKeyIsUsedFor,
                Cipher.SECRET_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public PrivateKey decryptPrivateKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key,
        String keyToDecrypt) throws NetInfCheckedSecurityException {
    try {/*from w  w w .  ja  v a 2 s  .  c  o m*/
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.UNWRAP_MODE, key);
        return (PrivateKey) cipher.unwrap(Utils.stringToBytes(keyToDecrypt), algorithmKeyIsUsedFor,
                Cipher.PRIVATE_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    }
}