Example usage for javax.crypto KeyGenerator init

List of usage examples for javax.crypto KeyGenerator init

Introduction

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

Prototype

public final void init(int keysize) 

Source Link

Document

Initializes this key generator for a certain keysize.

Usage

From source file:org.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java

private SecretKey generateDataEncryptionKey() {
    try {//ww  w  .ja va 2s.  com
        logger.debug("using uri algorithm [" + getSymmetricKeyAlgorithmURI() + "]");
        String jceAlgorithmName = JCEMapper.getJCEKeyAlgorithmFromURI(getSymmetricKeyAlgorithmURI());
        int keyLength = JCEMapper.getKeyLengthFromURI(getSymmetricKeyAlgorithmURI());
        logger.debug("generating key with algorithm [" + jceAlgorithmName + ":" + keyLength + "]");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
        keyGenerator.init(keyLength);
        return keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

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

@Test
public void testAttributEncryptionSymmetric() throws Exception {

    // Setup//from ww  w . j a v a  2 s.  com
    String algorithm = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;

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

    Encrypter encrypter = Saml2Util.getEncrypter(algorithm, key);

    // 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("Number of EncryptedKeys", 0,
            encTarget.getEncryptedData().getKeyInfo().getEncryptedKeys().size());

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

    // Setup
    Decrypter decrypter = Saml2Util.getDecrypter(key);

    // 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:org.apache.ws.security.message.token.BSTKerberosTest.java

/**
 * A test for encryption using a direct reference to a Kerberos token
 *///ww w . j a  va 2s .  c om
@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.apache.ws.security.message.token.BSTKerberosTest.java

/**
 * A test for signing using a direct reference to a Kerberos token
 *//*from  www  .j  a  v a 2 s .  c o  m*/
@org.junit.Test
public void testKerberosSignatureDRCreation() 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());

    WSSecSignature sign = new WSSecSignature();
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
    sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    sign.setCustomTokenValueType(AP_REQ);
    sign.setCustomTokenId(bst.getID());
    sign.setSecretKey(keyData);

    Document signedDoc = sign.build(doc, crypto, secHeader);

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

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

/**
 * A test for signing using a KeyIdentifier to a Kerberos token
 */// w w  w  . j  a  v  a 2s . co  m
@org.junit.Test
public void testKerberosSignatureKICreation() 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());

    WSSecSignature sign = new WSSecSignature();
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
    sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    sign.setCustomTokenValueType(WSConstants.WSS_KRB_KI_VALUE_TYPE);

    byte[] digestBytes = WSSecurityUtil.generateDigest(keyData);
    sign.setCustomTokenId(Base64.encode(digestBytes));
    sign.setSecretKey(keyData);

    Document signedDoc = sign.build(doc, crypto, secHeader);

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

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 ww.j ava 2 s . c om
@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:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2Test.java

@Test
public void testAttributEncryptionAsymmetric2() throws Exception {

    // Setup//w  ww. j av a  2 s .  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:edu.stanford.junction.extra.Encryption.java

@Override
public boolean beforeActivityCreate() {
    try {//from  w w w. ja  v  a  2  s .  co  m
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        SecretKey skey = kgen.generateKey();

        mKey = skey.getEncoded();
        init();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

From source file:com.grarak.kerneladiutor.activities.SecurityActivity.java

private void loadFingerprint() {
    try {/*  w  w  w . ja va2  s  .c  om*/
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        keyStore.load(null);
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();

        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        mCipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException
            | UnrecoverableKeyException | InvalidKeyException | CertificateException
            | InvalidAlgorithmParameterException | IOException e) {
        return;
    }

    mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher);
    FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent);
    final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl));
    swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    fingerprintParent.addView(swirlView);
    fingerprintParent.setVisibility(View.VISIBLE);

    mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat)
            .build(swirlView, new FingerprintUiHelper.Callback() {
                @Override
                public void onAuthenticated() {
                    try {
                        mCipher.doFinal(SECRET_MESSAGE.getBytes());
                        mPasswordWrong.setVisibility(View.GONE);
                        setResult(1);
                        finish();
                    } catch (IllegalBlockSizeException | BadPaddingException e) {
                        e.printStackTrace();
                        swirlView.setState(SwirlView.State.ERROR);
                    }
                }

                @Override
                public void onError() {
                }
            });
    mFingerprintUiHelper.startListening(mCryptoObject);
}

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  ww w.  j av a2s  .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();
    }
}