Example usage for javax.crypto SecretKey getEncoded

List of usage examples for javax.crypto SecretKey getEncoded

Introduction

In this page you can find the example usage for javax.crypto SecretKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *//*from  w  ww.j  a  v  a2  s.  co  m*/
Map<String, EntityProperty> encryptEntity(Map<String, EntityProperty> properties, String partitionKey,
        String rowKey, EncryptionResolver encryptionResolver) throws StorageException {
    Utility.assertNotNull("properties", properties);

    // The Key should be set on the policy for encryption. Otherwise, throw an error.
    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        Map<String, EntityProperty> encryptedProperties = new HashMap<String, EntityProperty>();
        HashSet<String> encryptionPropertyDetailsSet = new HashSet<String>();

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptionData.setContentEncryptionIV(myAes.getIV());

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
            if (encryptionResolver != null
                    && encryptionResolver.encryptionResolver(partitionKey, rowKey, kvp.getKey())) {
                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                kvp.getValue().setIsEncrypted(true);
            }

            // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is 
            // specified in the encryption resolver or both.
            if (kvp.getValue() != null && kvp.getValue().isEncrypted()) {
                // Throw if users try to encrypt non-string properties.
                if (kvp.getValue().getEdmType() != EdmType.STRING) {
                    throw new IllegalArgumentException(String
                            .format(SR.UNSUPPORTED_PROPERTY_TYPE_FOR_ENCRYPTION, kvp.getValue().getEdmType()));
                }

                byte[] columnIVFull = digest
                        .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                byte[] columnIV = new byte[16];
                System.arraycopy(columnIVFull, 0, columnIV, 0, 16);
                myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(columnIV));

                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                // case when the property value is null.
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                byte[] src = kvp.getValue().getValueAsString().getBytes(Constants.UTF8_CHARSET);
                byte[] dest = myAes.doFinal(src, 0, src.length);

                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of 
                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly 
                // even when the service does not return the type for JSON no-metadata.
                encryptedProperties.put(kvp.getKey(), new EntityProperty(dest));
                encryptionPropertyDetailsSet.add(kvp.getKey());
            } else {
                encryptedProperties.put(kvp.getKey(), kvp.getValue());
            }

            // Encrypt the property details set and add it to entity properties.
            byte[] metadataIVFull = digest.digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                    (partitionKey + rowKey + Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS)
                            .getBytes(Constants.UTF8_CHARSET)));

            byte[] metadataIV = new byte[16];
            System.arraycopy(metadataIVFull, 0, metadataIV, 0, 16);
            myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(metadataIV));

            byte[] src = Arrays.toString(encryptionPropertyDetailsSet.toArray())
                    .getBytes(Constants.UTF8_CHARSET);
            byte[] dest = myAes.doFinal(src, 0, src.length);
            encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    new EntityProperty(dest));
        }

        encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS,
                new EntityProperty(encryptionData.serialize()));

        return encryptedProperties;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * @param salt number of the key./*ww w . j a v a2  s .c om*/
 * @return the CupherKey.
 * @throws UnsupportedEncodingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private Key getCiperKey(byte[] salt)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    // hashing the password 65K times takes 151ms, hashing 256 times takes 2ms.
    // Since the salt has 2^^72 values, 256 times is probably good enough.
    KeySpec spec = new PBEKeySpec(sharedKey.toCharArray(), salt, 256, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");
    return key;
}

From source file:org.apache.usergrid.persistence.Schema.java

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);/*from   w w w.java 2  s  .  c om*/
    keyGenerator.init(128, sr); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

From source file:press.gfw.chat.Encrypt.java

/**
 * ?SecretKey//from  w w  w .  j ava2s . c o  m
 *
 * @param secretKey
 *            SecretKey
 *
 * @return SecretKey
 *
 */
public String getStringKey(SecretKey secretKey) {

    if (secretKey == null) {

        return null;

    }

    return Base64.encodeBase64String(secretKey.getEncoded());

}

From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java

private SecretKey generateKey(String password, byte[] salt) throws CryptographyException {
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, pbeIterationCount, pbeKeyLength);

    SecretKeyFactory factory;//w w  w.  j  a  va 2  s  . c  om
    SecretKey tmp;
    try {
        factory = SecretKeyFactory.getInstance(pbeAlgorithm);
        tmp = factory.generateSecret(pbeKeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptographyException(e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new CryptographyException(e.getMessage());
    }

    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), keyGenerator);

    return secret;
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Creates a decryption cipher for the encrypted value value using `AES/CBC/PKCS5Padding`.  The base64 encoded
 * iv must already be present in the encrypted value.
 * //w  ww .  j  a  va 2  s .c  o  m
 * @param secret the key to use for decryption.
 * @param value the value that will decrypted with this cipher.  The base64 iv must be present on this value.
 * @return a cipher that will decrypt the specified value with the specified key.
 * @throws EncryptionException if the cipher could not be created for any reason.
 */
Cipher createDecryptionCipher(SecretKey secret, E value) throws EncryptionException {
    if (Ciphers.AES_256_CBC.equals(value.getCipher())
            && KeyDerivations.PBKDF2.equals(value.getKeyDerivation())) {
        try {
            SecretKeySpec spec = new SecretKeySpec(secret.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(value.getIv()));
            return cipher;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidAlgorithmParameterException e) {
            throw new EncryptionException("could not create decryption cypher", e);
        }
    } else {
        throw new EncryptionException(String.format("unsupported cipher %s and key derivation %s",
                value.getCipher(), value.getKeyDerivation()));
    }
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Creates a cipher for doing encryption.  The generated iv is placed in the value as a side effect.
 * //from   www. j ava  2s . c  o m
 * @param secret the pre stretched secret key
 * @param value the value that the encrypted data will be stored in.
 * @return the cipher to use.
 * @throws EncryptionException
 */
Cipher createEncryptionCipher(SecretKey secret, E value) throws EncryptionException {
    if (Ciphers.AES_256_CBC.equals(value.getCipher())
            && KeyDerivations.PBKDF2.equals(value.getKeyDerivation())) {
        try {
            SecretKeySpec spec = new SecretKeySpec(secret.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, spec);
            AlgorithmParameters params = cipher.getParameters();
            value.setIv(params.getParameterSpec(IvParameterSpec.class).getIV());
            return cipher;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidParameterSpecException e) {
            throw new EncryptionException("could not create encryption cypher", e);
        }
    } else {
        throw new EncryptionException(String.format("unsupported cipher %s and key derivation %s",
                value.getCipher(), value.getKeyDerivation()));
    }
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

@Override
protected final void addSecretKey(final KeyStore kstore, final String alias, final String password)
        throws KeyStoreException {
    final SecretKeyEntry secretKeyEntry; // Secret key entry
    final PasswordProtection keyPassword; // Secret key password protection
    final SecretKey secretKey; // Secret key password
    final byte[] key; // Secret key as array

    key = getPasswordArray(password);//from ww w .ja  v  a  2  s .c om
    secretKey = new SecretKeySpec(key, getSecretKeyAlgorithm());

    LOGGER.debug("Created secret key {} with format {}", Arrays.asList(secretKey.getEncoded()),
            secretKey.getFormat());

    secretKeyEntry = new SecretKeyEntry(secretKey);
    keyPassword = new PasswordProtection(password.toCharArray());
    kstore.setEntry(alias, secretKeyEntry, keyPassword);

    LOGGER.debug("Added secret key with alias {} and password {}", alias, password);
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);//  w w  w  . j a va 2 s.  c  om
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
}

From source file:com.bamboocloud.im.provisioner.json.crypto.simple.SimpleEncryptor.java

/**
 * Encrypts using an asymmetric cipher.// w w w  . jav  a 2s .com
 *
 * @param value the value to be encrypted.
 * @return the encrypted value.
 * @throws GeneralSecurityException if a cryptographic operation failed.
 * @throws IOException if an I/O exception occurred.
 */
private Object asymmetric(Object object) throws GeneralSecurityException, IOException {
    String symmetricCipher = "AES/ECB/PKCS5Padding"; // no IV required for randomly-generated session key
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128);
    SecretKey sessionKey = generator.generateKey();
    Cipher symmetric = Cipher.getInstance(symmetricCipher);
    symmetric.init(Cipher.ENCRYPT_MODE, sessionKey);
    String data = Base64.encodeBase64String(symmetric.doFinal(mapper.writeValueAsBytes(object)));
    Cipher asymmetric = Cipher.getInstance(cipher);
    asymmetric.init(Cipher.ENCRYPT_MODE, key);
    HashMap<String, Object> keyObject = new HashMap<String, Object>();
    keyObject.put("cipher", this.cipher);
    keyObject.put("key", this.alias);
    keyObject.put("data", Base64.encodeBase64String(asymmetric.doFinal(sessionKey.getEncoded())));
    HashMap<String, Object> result = new HashMap<String, Object>();
    result.put("cipher", symmetricCipher);
    result.put("key", keyObject);
    result.put("data", data);
    return result;
}