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:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 *//*from  w  w w .jav  a  2 s. co m*/

public void testAES128ElementRSAKWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);
        log.debug("Encrypted document");
        log.debug(toString(ed));

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        log.debug("Output document");
        log.debug(target);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available");
    }
}

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

@Test
public void testAttributEncryptionAsymmetric2() throws Exception {

    // Setup/*from  ww w  .  j a  va  2s.  c  o  m*/
    String algorithm = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey key = kgen.generateKey();

    KeyPair keyPair = generateKeyPair();
    Encrypter encrypter = Saml2Util.getEncrypter(algorithm, key, keyPair.getPublic());

    // Operate: encrypt
    EncryptedAttribute encTarget;
    XMLObject encObject = null;
    try {
        encObject = encrypter.encrypt(getAttribute());
    } catch (EncryptionException e) {
        fail("Object encryption failed: " + e);
    }

    // Verify
    LOG.debug(Saml2Util.domToString(Saml2Util.marshall(encObject), true));

    assertNotNull("Encrypted object was null", encObject);
    assertTrue("Encrypted object was not an instance of the expected type",
            encObject instanceof EncryptedAttribute);
    encTarget = (EncryptedAttribute) encObject;

    assertEquals("Type attribute", EncryptionConstants.TYPE_ELEMENT, encTarget.getEncryptedData().getType());
    assertEquals("Algorithm attribute", algorithm,
            encTarget.getEncryptedData().getEncryptionMethod().getAlgorithm());
    assertNotNull("KeyInfo", encTarget.getEncryptedData().getKeyInfo());
    assertEquals(1, encTarget.getEncryptedData().getKeyInfo().getRetrievalMethods().size());
    assertEquals(XMLConstants.XMLENC_NS + EncryptedKey.DEFAULT_ELEMENT_LOCAL_NAME,
            encTarget.getEncryptedData().getKeyInfo().getRetrievalMethods().get(0).getType());

    assertEquals("Number of EncryptedKeys", 1, encTarget.getEncryptedKeys().size());
    assertEquals(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15,
            encTarget.getEncryptedKeys().get(0).getEncryptionMethod().getAlgorithm());

    assertFalse("EncryptedData ID attribute was empty",
            DatatypeHelper.isEmpty(encTarget.getEncryptedData().getID()));

    // Setup
    Decrypter decrypter = Saml2Util.getDecrypter(keyPair.getPrivate());

    // Operate: decrypt
    SAMLObject decryptedTarget = null;
    try {
        decryptedTarget = decrypter.decrypt(encTarget);
    } catch (DecryptionException e) {
        fail("Error on decryption of encrypted SAML 2 type to element: " + e);
    }

    // Verify
    assertNotNull("Decrypted target was null", decryptedTarget);
    assertTrue("Decrypted target was not the expected type", decryptedTarget instanceof Attribute);
    LOG.debug(Saml2Util.domToString(Saml2Util.marshall(decryptedTarget), true));
}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

static Key makeKey(int keyBit) throws NoSuchAlgorithmException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    SecureRandom rd = SecureRandom.getInstance("SHA1PRNG");
    kg.init(keyBit, rd);//from ww  w .ja  v  a  2  s  .c om
    Key key = kg.generateKey();
    return key;

}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java

private void startRedis() {
    redisService = StageUtils.startDockerRedis(dockerTestSupport);
    KeyGenerator kg = null;/*from w  ww  . j  av  a 2 s  .c om*/
    try {
        kg = KeyGenerator.getInstance("AES");
        userStore = new RedisUserStore(kg.generateKey(), redisService.getHost(), redisService.getPort());
    } catch (NoSuchAlgorithmException e) {
        fail(e.getMessage());
    }
}

From source file:org.xwiki.contrib.encryption.internal.DefaultEncryptionTool.java

private SecretKeySpec generateRandomKey() {
    try {/*from   w  w  w.  j  a v  a  2  s  .  c  om*/
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey key = keyGenerator.generateKey();
        return (SecretKeySpec) key;
    } catch (Exception e) {
        logger.warn("Exception encountered while generating the encryption key : " + e.getMessage());
        return null;
    }
}

From source file:com.ironchain.common.kits.DigestKit.java

/**
 * ?AES,?128,192,256?.//from w w  w  .ja va2s .c o  m
 */
public static byte[] generateAesKey(int keysize) {
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
        keyGenerator.init(keysize);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jsecurity.crypto.BlowfishCipher.java

/**
 * Generates a new {@link Key Key} of the specified size suitable for this Cipher
 * (based on the {@link #ALGORITHM ALGORITHM} using the JDK {@link KeyGenerator KeyGenerator}.
 * @param keyBitSize the bit size of the key to create
 * @return the created key suitable for use with this Cipher.
 *//*from  ww  w.ja va 2 s.c  o m*/
public static Key generateNewKey(int keyBitSize) {
    KeyGenerator kg;
    try {
        kg = KeyGenerator.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        String msg = "Unable to acquire " + ALGORITHM + " algorithm.  This is required to function.";
        throw new IllegalStateException(msg, e);
    }
    kg.init(keyBitSize);
    return kg.generateKey();
}

From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java

private SecretKey createSecretKey(Path keyPath) throws Exception {
    KeyGenerator keyGenerator = null;
    keyGenerator = KeyGenerator.getInstance(MigrationZipConstants.KEY_ALGORITHM);
    SecretKey secretKey = keyGenerator.generateKey();
    char[] hexKey = encodeHex(secretKey.getEncoded());
    writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8);
    return secretKey;
}

From source file:org.slc.sli.bulk.extract.files.ExtractFile.java

private static Pair<Cipher, SecretKey> getCiphers() throws Exception {
    SecretKey secret = KeyGenerator.getInstance("AES").generateKey();

    Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encrypt.init(Cipher.ENCRYPT_MODE, secret);

    return Pair.of(encrypt, secret);
}

From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java

private void generateKeyWithWrongAlgorithm(Path keyPath) throws NoSuchAlgorithmException, IOException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
    SecretKey secretKey = keyGenerator.generateKey();
    char[] hexKey = encodeHex(secretKey.getEncoded());
    writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8);
}