Example usage for javax.crypto Cipher WRAP_MODE

List of usage examples for javax.crypto Cipher WRAP_MODE

Introduction

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

Prototype

int WRAP_MODE

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

Click Source Link

Document

Constant used to initialize cipher to key-wrapping mode.

Usage

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: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.  j a v  a  2 s.  co m

    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:RSATest.java

public static void main(String[] args) {
    try {/*from   w  w w . j a  va 2 s. c  o  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

/**
 * Encrypts the secret key (symmetric key) held inside the OxalisCipher instance using the supplied PublicKey, after
 * which the resulting wrapped secret key is transformed into a hex string suitable for transmission, persistence etc.
 *
 * @param publicKey the public asymmetric key to use for encrypting the secret symmetric key
 * @param oxalisCipher the instance of OxalisCipher in which the secret symmetric key is held.
 * @return/*  w w w  .j  a  v  a2  s.  c  om*/
 */
public String getWrappedSymmetricKeyAsString(PublicKey publicKey, OxalisCipher oxalisCipher) {

    try {
        Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM);
        cipher.init(Cipher.WRAP_MODE, publicKey);
        SecretKey secretKey = oxalisCipher.getSecretKey();
        byte[] encodedBytes = cipher.wrap(secretKey);

        return new String(Hex.encodeHex(encodedBytes));

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
                "Unable to create cipher with algorithm: " + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalStateException("Unable to create cipher with default padding for algorithm "
                + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("The public key is invalid " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException("Error during encryption of symmetric key: " + e.getMessage(), e);
    }
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

/**
 * Encrypts the current masterKey with the given password and writes the result to the given output stream.
 *//*from   ww  w  . j  ava 2  s  . c o m*/
@Override
public void encryptMasterKey(OutputStream out, CharSequence password) throws IOException {
    try {
        // derive key:
        final byte[] kekSalt = randomData(SCRYPT_SALT_LENGTH);
        final SecretKey kek = scrypt(password, kekSalt, SCRYPT_COST_PARAM, SCRYPT_BLOCK_SIZE,
                AES_KEY_LENGTH_IN_BITS);

        // encrypt:
        final Cipher encCipher = aesKeyWrapCipher(kek, Cipher.WRAP_MODE);
        byte[] wrappedPrimaryKey = encCipher.wrap(primaryMasterKey);
        byte[] wrappedSecondaryKey = encCipher.wrap(hMacMasterKey);

        // save encrypted masterkey:
        final KeyFile keyfile = new KeyFile();
        keyfile.setScryptSalt(kekSalt);
        keyfile.setScryptCostParam(SCRYPT_COST_PARAM);
        keyfile.setScryptBlockSize(SCRYPT_BLOCK_SIZE);
        keyfile.setKeyLength(AES_KEY_LENGTH_IN_BITS);
        keyfile.setPrimaryMasterKey(wrappedPrimaryKey);
        keyfile.setHMacMasterKey(wrappedSecondaryKey);
        objectMapper.writeValue(out, keyfile);
    } catch (InvalidKeyException | IllegalBlockSizeException ex) {
        throw new IllegalStateException("Invalid hard coded configuration.", ex);
    }
}

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

private void writeVaultHeader(File headerFile, byte[] vaultNonce, byte[] salt, int pbkdf2Iterations, Key aesKey,
        SecretKey keyFromPassphrase) throws Exception {
    Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
    FileOutputStream headerOutputStream = new FileOutputStream(headerFile);

    c.init(Cipher.WRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultNonce));
    byte[] encryptedAesKey = c.wrap(aesKey);

    VaultHeader.Builder vaultHeaderBuilder = VaultHeader.newBuilder();
    vaultHeaderBuilder.setVersion(VAULT_HEADER_VERSION);
    vaultHeaderBuilder.setSalt(ByteString.copyFrom(salt));
    vaultHeaderBuilder.setVaultIV(ByteString.copyFrom(vaultNonce));
    vaultHeaderBuilder.setPbkdf2Iterations(pbkdf2Iterations);
    vaultHeaderBuilder.setEncryptedAesKey(ByteString.copyFrom(encryptedAesKey));
    vaultHeaderBuilder.build().writeTo(headerOutputStream);
    headerOutputStream.close();/*from  w  w w . ja  va2 s.  c  o m*/
}

From source file:com.amazonaws.services.s3.internal.crypto.S3CryptoModuleBase.java

protected final SecuredCEK secureCEK(SecretKey toBeEncrypted, EncryptionMaterials materials,
        Provider cryptoProvider) {
    Key kek;//  www  .j a  v a2s . co  m
    if (materials.getKeyPair() != null) {
        // Do envelope encryption with public key from key pair
        kek = materials.getKeyPair().getPublic();
    } else {
        // Do envelope encryption with symmetric key
        kek = materials.getSymmetricKey();
    }
    S3KeyWrapScheme kwScheme = cryptoScheme.getKeyWrapScheme();
    String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
    try {
        if (keyWrapAlgo != null) {
            Cipher cipher = cryptoProvider == null ? Cipher.getInstance(keyWrapAlgo)
                    : Cipher.getInstance(keyWrapAlgo, cryptoProvider);
            cipher.init(Cipher.WRAP_MODE, kek, cryptoScheme.getSecureRandom());
            return new SecuredCEK(cipher.wrap(toBeEncrypted), keyWrapAlgo);
        }
        // fall back to the Encryption Only (EO) key encrypting method
        Cipher cipher;
        byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded();
        String algo = kek.getAlgorithm();
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(algo, cryptoProvider);
        } else {
            cipher = Cipher.getInstance(algo); // Use default JCE Provider
        }
        cipher.init(Cipher.ENCRYPT_MODE, kek);
        return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null);
    } catch (Exception e) {
        throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e);
    }
}

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

public static ByteBuffer seal(String msg, String nymID, PublicKey nymKey, SecretKeySpec aesSecret,
        IvParameterSpec vector) throws InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    ByteBuffer buff = ByteBuffer.allocate(msg.length() + 500);//donno?
    buff.order(ByteOrder.BIG_ENDIAN);
    buff.putShort((short) 1);//asymmetric
    buff.putInt(1);//array size
    buff.putInt(nymID.length() + 1);/*from ww  w .  j  av a  2  s  .com*/
    buff.put(bytes(nymID + '\0', US_ASCII));

    // create encoded key and message
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.ENCRYPT_MODE, aesSecret, vector);
    byte[] encrypted = cipher.doFinal(bytes(msg + '\0', UTF8));
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.WRAP_MODE, nymKey);
    byte[] encKeyBytes = cipher.wrap(aesSecret);

    buff.putInt(encKeyBytes.length);
    buff.put(encKeyBytes);
    buff.putInt(vector.getIV().length);
    buff.put(vector.getIV());
    buff.put(encrypted);
    buff.flip();

    return buff;
}

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

@Override
public String encryptSecretKey(String algorithmUsedToEncryptTheKey, Key key, SecretKey keyToEncrypt)
        throws NetInfCheckedSecurityException {
    try {//from   w w w .  j av  a2s  .c o  m
        LOG.debug("Encrypting SecretKey.");
        LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey);
        LOG.trace("Used key: " + key);
        LOG.trace("Used key to be encrypted: " + keyToEncrypt);
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.WRAP_MODE, key);
        return Base64.encodeBase64String(cipher.wrap(keyToEncrypt));
    } 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());
    } catch (IllegalBlockSizeException e) {
        throw new NetInfCheckedSecurityException("Illegal cipher-block-size: " + e.getMessage());
    }
}

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

@Override
public String encryptPrivateKey(String algorithmUsedToEncryptTheKey, Key key, PrivateKey keyToEncrypt)
        throws NetInfCheckedSecurityException {
    try {/*  w w  w. j a v a2s.co m*/
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.WRAP_MODE, key);
        return Utils.bytesToString(cipher.wrap(keyToEncrypt));
    } 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());
    } catch (IllegalBlockSizeException e) {
        throw new NetInfCheckedSecurityException("Illegal cipher-block-size: " + e.getMessage());
    }
}