Example usage for javax.crypto KeyGenerator getInstance

List of usage examples for javax.crypto KeyGenerator getInstance

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator getInstance.

Prototype

public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyGenerator object that generates secret keys for the specified algorithm.

Usage

From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java

/**
 * Set up the encryption context required for encrypting blobs.
 * @param metadata/*from  www. j av  a  2s .c o m*/
 *          Reference to blob metadata object that is used to set the encryption materials.
 * @param noPadding
 *          Value indicating if the padding mode should be set or not.
 * @return The Cipher to use to decrypt the blob.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
Cipher createAndSetEncryptionContext(Map<String, String> metadata, boolean noPadding) throws StorageException {
    Utility.assertNotNull("metadata", metadata);

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

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

        Cipher myAes;
        if (noPadding) {
            myAes = Cipher.getInstance("AES/CBC/NoPadding");
        } else {
            myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }

        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

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

        // 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());

        metadata.put(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA, encryptionData.serialize());
        return myAes;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:org.openmrs.util.Security.java

/**
 * generate a new secret key; should only be called once in order to not invalidate all
 * encrypted data/*from  ww w  .  ja v  a2  s .c  om*/
 *
 * @return generated secret key byte array
 * @since 1.9
 */
public static byte[] generateNewSecretKey() {
    // Get the KeyGenerator
    KeyGenerator kgen = null;
    try {
        kgen = KeyGenerator.getInstance(OpenmrsConstants.ENCRYPTION_KEY_SPEC);
    } catch (NoSuchAlgorithmException e) {
        throw new APIException("could.not.generate.cipher.key", null, e);
    }
    kgen.init(128); // 192 and 256 bits may not be available

    // Generate the secret key specs.
    SecretKey skey = kgen.generateKey();

    return skey.getEncoded();
}

From source file:org.apache.ws.security.message.token.BSTKerberosTest.java

/**
 * A test for encryption using a direct reference to a Kerberos token
 *///from w  w w .j  a va 2  s.c  o m
@org.junit.Test
public void testKerberosEncryptionDRCreation() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    BinarySecurity bst = new BinarySecurity(doc);
    bst.setValueType(AP_REQ);
    bst.setEncodingType(BASE64_NS);

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    bst.setToken(keyData);
    bst.setID("Id-" + bst.hashCode());
    WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());

    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
    builder.setSymmetricKey(key);
    builder.setEncryptSymmKey(false);
    builder.setCustomReferenceValue(AP_REQ);
    builder.setEncKeyId(bst.getID());
    Document encryptedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
}

From source file:org.openanzo.security.keystore.SecretKeyStore.java

/**
 * Loads the secret key to use for encryption and decryption. It will read the key from the keystore if it exists. Otherwise it will create a new randomly
 * generated key and save it in a keystore at the given file. It will use the algorithm defined in the <code>algorithm</code> member.
 * //from  w w  w  .  ja v a 2s . c  om
 * @param keyStoreStream
 *            stream from which to read the keystore which holds the secret key. If null, a new keystore is created.
 * @param password
 *            password used to protect the and integrity-check the secret key.
 * @param keyStoreDestination
 *            File path to which to save the keystore in case it is newly created or a new key was added. If null, then nothing is written out.
 * @return the loaded or newly generated secret key.
 * @throws AnzoException
 */
private SecretKey loadKey(InputStream keyStoreStream, String password, File keyStoreDestination,
        String keystoreType) throws AnzoException {

    try {
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(keyStoreStream, password.toCharArray());

        Key key = null;
        if (keyStore.containsAlias(KEY_NAME)) {
            key = keyStore.getKey(KEY_NAME, password.toCharArray());
        } else {
            log.warn("Could not find key '{}' within keystore. Generating a new key.", KEY_NAME);
            KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
            key = kgen.generateKey();
            keyStore.setKeyEntry(KEY_NAME, key, password.toCharArray(), new Certificate[0]);
            if (keyStoreDestination != null) {
                log.warn("Storing new key in the keystore.");
                OutputStream outputStream = null;
                try {
                    outputStream = FileUtils.openOutputStream(keyStoreDestination);
                    keyStore.store(outputStream, password.toCharArray());
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            }
        }

        if (!(key instanceof SecretKey))
            throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR,
                    "key must be of type SecretKey: " + key);
        return (SecretKey) key;
    } catch (GeneralSecurityException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    } catch (IOException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    }

}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private SecretKey generateAESKey() throws NoSuchAlgorithmException {
    KeyGenerator aeskeygen = KeyGenerator.getInstance("AES");
    SecretKey aeskey = aeskeygen.generateKey();
    return aeskey;
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Common payload content encryption method which is called after sanity
 * checks, and after any content signing is performed.
 * //from   w  w  w  .j  ava  2  s.  c om
 * @throws Exception 
 */
private void doEncryption() throws Exception {
    // Make the one-time symmetric key, and encrypt the payload content using it.
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(AESKEYSIZE);
    SecretKey key = kgen.generateKey();
    String cipherData = doAESEncryption(key);

    // Start constructing the XML Encryption "EncryptedData" element. The main 
    // payload encryption is AES-256/CBC
    //
    StringBuilder sb = new StringBuilder(
            "<xenc:EncryptedData xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\">");
    sb.append("<xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>");

    // And then the KeyInfo which is the symmetric key byte[] encrypted for each
    // reader certificate.
    //
    sb.append("<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">");
    byte[] keyMaterial = key.getEncoded();
    for (X509Certificate x : readerCerts) {
        sb.append(doRSASymmetricKeyEncryption(x, keyMaterial));
    }
    sb.append("</ds:KeyInfo>");
    sb.append(cipherData);
    sb.append("</xenc:EncryptedData>");

    // Set the payloadBody to the EncryptedData, and the "encrypted" flag to "true".
    // Note that "base64" and "compressed" apply to the *cleartext*, and so are not
    // altered by this operation. The same goes for the mime type. Receiving systems
    // that decrypt the payload will need these other data set correctly in order to
    // convert the encrypted and possibly otherwise-processed content into something
    // they can use.
    //
    payloadBody = sb.toString();
    encrypted = true;

    // Make sure we overwrite the key byte[] before we leave, and mark the
    // one-time secret key null.
    //
    for (int i = 0; i < keyMaterial.length; i++) {
        keyMaterial[i] = 0;
    }
    key = null;
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java

@Test
public void testGetAlgorithm() throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);//  w w  w .  j  a v a 2s .c  o  m
    SecretKey key = kgen.generateKey();
    LOG.debug("Algorithm AES-128: " + key.getAlgorithm());

}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Generates a random Base64 encoded string value.
 * //from  w w  w  . jav  a  2s.c  o m
 * @param length
 *          The length of the key.
 * @return A random key value.
 */
public byte[] generateRandomKeyBytes(final int length) {
    byte[] randomKey = null;

    // Use a SecureRandom generator
    try {
        final SecureRandom secureRandom = new SecureRandom();
        final KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM);
        keyGenerator.init(length, secureRandom);
        final SecretKey secretKey = keyGenerator.generateKey();
        randomKey = secretKey.getEncoded();
    } catch (final NoSuchAlgorithmException e) {
        Log.e(TAG, "Exception generating random key", e);
    }

    return randomKey;
}

From source file:org.apache.ws.security.message.token.BSTKerberosTest.java

/**
 * A test for encryption using a Key Identifier to a Kerberos token
 *//*from  w w  w . jav a2 s.  com*/
@org.junit.Test
public void testKerberosEncryptionKICreation() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    BinarySecurity bst = new BinarySecurity(doc);
    bst.setValueType(AP_REQ);
    bst.setEncodingType(BASE64_NS);

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    bst.setToken(keyData);
    bst.setID("Id-" + bst.hashCode());
    WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());

    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
    builder.setSymmetricKey(key);
    builder.setEncryptSymmKey(false);
    builder.setCustomReferenceValue(WSConstants.WSS_KRB_KI_VALUE_TYPE);

    byte[] digestBytes = WSSecurityUtil.generateDigest(keyData);
    builder.setEncKeyId(Base64.encode(digestBytes));

    Document encryptedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
}

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);/*from   www.ja v  a  2 s . c o m*/
    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();
}