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.ws.security.message.token.BSTKerberosTest.java

/**
 * A test for signing using a direct reference to a Kerberos token
 *//*from w  w w. j  a v a 2s .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:com.bluepixel.security.manager.ServerClient_test.java

private static SecretKey getSecretKey() throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);//from   w  w w .  j  ava 2  s . c om
    SecretKey key = keyGenerator.generateKey();
    return key;
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService.java

public void init() {
    lessonBuilderAccessAPI.setHttpAccess(getHttpAccess());

    accessCache = memoryService.createCache(
            "org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService.cache",
            new SimpleConfiguration<Object, Object>(CACHE_MAX_ENTRIES, CACHE_TIME_TO_LIVE_SECONDS,
                    CACHE_TIME_TO_IDLE_SECONDS));

    SimplePageItem metaItem = null;//w w  w. j a v a 2  s .c  o m
    // Get crypto session key from metadata item
    //   we have to keep it in the database so it's the same on all servers
    // There's no entirely sound way to create the item if it doesn't exist
    //   other than by getting a table lock. Fortunately this will only be
    //   needed when the entry is created.

    SimplePageProperty prop = simplePageToolDao.findProperty("accessCryptoKey");
    if (prop == null) {
        try {
            sessionKey = KeyGenerator.getInstance("Blowfish").generateKey();
            // need string version to save in item
            byte[] keyBytes = ((SecretKeySpec) sessionKey).getEncoded();
            // set attribute to hex version of key
            prop = simplePageToolDao.makeProperty("accessCryptoKey",
                    DatatypeConverter.printHexBinary(keyBytes));
            simplePageToolDao.quickSaveItem(prop);
        } catch (Exception e) {
            System.out.println("unable to init cipher for session " + e);
            // in case of race condition, our save will fail, but we'll be able to get a value
            // saved by someone else
            simplePageToolDao.flush();
            prop = simplePageToolDao.findProperty("accessCryptoKey");
        }
    }

    if (prop != null) {
        String keyString = prop.getValue();
        byte[] keyBytes = DatatypeConverter.parseHexBinary(keyString);
        sessionKey = new SecretKeySpec(keyBytes, "Blowfish");
    }

}

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

/**
 * Prepare the document for encryption.//from  w w w.j av a 2  s.c  o m
 *
 * @param doc The document that will be encrypted.
 *
 * @throws CryptographyException If there is an error while encrypting.
 */
public void prepareDocumentForEncryption(PDDocument doc) throws CryptographyException {

    try {
        Security.addProvider(new BouncyCastleProvider());

        PDEncryptionDictionary dictionary = doc.getEncryptionDictionary();
        if (dictionary == null) {
            dictionary = new PDEncryptionDictionary();
        }

        dictionary.setFilter(FILTER);
        dictionary.setLength(this.keyLength);
        dictionary.setVersion(2);

        // remove CF, StmF, and StrF entries that may be left from a previous encryption
        dictionary.removeV45filters();

        dictionary.setSubFilter(SUBFILTER);

        byte[][] recipientsField = new byte[policy.getRecipientsNumber()][];

        // create the 20 bytes seed

        byte[] seed = new byte[20];

        KeyGenerator key = KeyGenerator.getInstance("AES");
        key.init(192, new SecureRandom());
        SecretKey sk = key.generateKey();
        System.arraycopy(sk.getEncoded(), 0, seed, 0, 20); // create the 20 bytes seed

        Iterator it = policy.getRecipientsIterator();
        int i = 0;

        while (it.hasNext()) {
            PublicKeyRecipient recipient = (PublicKeyRecipient) it.next();
            X509Certificate certificate = recipient.getX509();
            int permission = recipient.getPermission().getPermissionBytesForPublicKey();

            byte[] pkcs7input = new byte[24];
            byte one = (byte) (permission);
            byte two = (byte) (permission >>> 8);
            byte three = (byte) (permission >>> 16);
            byte four = (byte) (permission >>> 24);

            System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input

            pkcs7input[20] = four;
            pkcs7input[21] = three;
            pkcs7input[22] = two;
            pkcs7input[23] = one;

            DERObject obj = createDERForRecipient(pkcs7input, certificate);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            DEROutputStream k = new DEROutputStream(baos);

            k.writeObject(obj);

            recipientsField[i] = baos.toByteArray();

            i++;
        }

        dictionary.setRecipients(recipientsField);

        int sha1InputLength = seed.length;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            sha1InputLength += string.getBytes().length;
        }

        byte[] sha1Input = new byte[sha1InputLength];

        System.arraycopy(seed, 0, sha1Input, 0, 20);

        int sha1InputOffset = 20;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            System.arraycopy(string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length);
            sha1InputOffset += string.getBytes().length;
        }

        MessageDigest md = MessageDigest.getInstance("SHA-1");

        byte[] mdResult = md.digest(sha1Input);

        this.encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);

        doc.setEncryptionDictionary(dictionary);
        doc.getDocument().setEncryptionDictionary(dictionary.encryptionDictionary);

    } catch (NoSuchAlgorithmException ex) {
        throw new CryptographyException(ex);
    } catch (NoSuchProviderException ex) {
        throw new CryptographyException(ex);
    } catch (Exception e) {
        LOG.error(e, e);
        throw new CryptographyException(e);
    }

}

From source file:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyfile//from ww  w  .j a v  a2 s .  com
 * @param keysize
 * @param salter
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public final static void generateNewKeyFile(final File keyfile, final int keysize, final SecureRandom salter)
        throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
    if (keysize > Cipher.getMaxAllowedKeyLength(mytype))
        throw new InvalidKeySpecException(
                "You specified a key size not supported by your current cryptographic libraries, which currently have a max key size of "
                        + Cipher.getMaxAllowedKeyLength(mytype) + " for " + mytype);

    final FileOutputStream fos = new FileOutputStream(keyfile);
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance(mytype);
        kgen.init(keysize > mykeysizemax ? mykeysizemax : keysize, salter); // 192 and 256 bits may not be available
        final SecretKey sk = kgen.generateKey();
        fos.write(sk.getEncoded());
    } finally {
        fos.flush();
        fos.close();
        ;
    }
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 192 bit key that is
 * encrypted using a 3DES key.  Then reverse by decrypting 
 * EncryptedKey by hand/*from   www. j  a  v  a2  s .  c o  m*/
 */

public void testAES192ElementAES256KWCipher() 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 && haveKeyWraps) {

        source = toString(d);

        // Set up a Key Encryption Key
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        Key kek = keyFactory.generateSecret(keySpec);

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

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

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_192);
        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);

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

        EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee);

        if (encryptedData == null) {
            System.out.println("ed is null");
        } else if (encryptedData.getKeyInfo() == null) {
            System.out.println("ki is null");
        }
        EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0);

        if (ek != null) {
            XMLCipher keyCipher = XMLCipher.getInstance();
            keyCipher.init(XMLCipher.UNWRAP_MODE, kek);
            key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm());
        }

        // Create a new cipher just to be paranoid
        XMLCipher cipher3 = XMLCipher.getInstance();
        cipher3.init(XMLCipher.DECRYPT_MODE, key);
        dd = cipher3.doFinal(ed, ee);

        target = toString(dd);

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

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

/**
 * A test for signing using a KeyIdentifier to a Kerberos token
 *//*from  ww  w  .  java 2s . com*/
@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:com.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * /*from   ww w .  j av a  2 s  .  com*/
 * Create a new key with a custom keysize less-than equal to mykeysizemax,
 * specifying a custom salter
 * 
 * @param keyfile
 * @param keysize
 * @param salter
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws InvalidKeySpecException
 */
public final static void generateNewKeyFile(final File keyfile, final int keysize, final SecureRandom salter)
        throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
    if (keysize > Cipher.getMaxAllowedKeyLength(mytype))
        throw new InvalidKeySpecException(
                "You specified a key size not supported by your current cryptographic libraries, which currently have a max key size of "
                        + Cipher.getMaxAllowedKeyLength(mytype) + " for " + mytype);

    final FileOutputStream fos = new FileOutputStream(keyfile);
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance(mytype);
        kgen.init(keysize > mykeysizemax ? mykeysizemax : keysize, salter); // 192 and 256 bits may not be available
        final SecretKey sk = kgen.generateKey();
        fos.write(sk.getEncoded());
    } finally {
        if (fos != null) {
            fos.flush();
            fos.close();
        }
    }
}

From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

private boolean initialize() {
    try {/*from   www. ja  va 2s . c  o m*/
        encryptionReady = false;
        tokenRefreshRetryCount = TOKEN_REFRESH_RETRY_COUNT;
        if (Cipher.getMaxAllowedKeyLength("AES") < 256) {
            return setError(LxOfflineReason.INTERNAL_ERROR,
                    "Enable Java cryptography unlimited strength (see binding doc).");
        }
        // generate a random key for the session
        KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES");
        aesKeyGen.init(256);
        aesKey = aesKeyGen.generateKey();
        // generate an initialization vector
        secureRandom = new SecureRandom();
        secureRandom.nextBytes(initVector);
        IvParameterSpec ivSpec = new IvParameterSpec(initVector);
        // initialize aes cipher for command encryption
        aesEncryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec);
        // initialize aes cipher for response decryption
        aesDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesDecryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec);
        // get token value from configuration storage
        token = (String) configuration.get(SETTINGS_TOKEN);
        logger.debug("[{}] Retrieved token value: {}", debugId, token);
    } catch (InvalidParameterException e) {
        return setError(LxOfflineReason.INTERNAL_ERROR, "Invalid parameter: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        return setError(LxOfflineReason.INTERNAL_ERROR, "AES not supported on platform.");
    } catch (InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
        return setError(LxOfflineReason.INTERNAL_ERROR, "AES cipher initialization failed.");
    }
    return true;
}

From source file:com.tcs.ebw.security.EBWSecurity.java

/**
        //from w  w w .  jav a 2  s.c o  m
        
 * This method returns a key generated for using with Symmetric Crypto 
        
        
 * @return
        
        
 * @throws NoSuchAlgorithmException
        
        
 * @throws NoSuchPaddingException
        
        
 */

public Key generateKeyForSymmetric()

        throws NoSuchAlgorithmException, NoSuchPaddingException {

    /**Create a keygenerator for Symmetric Crypto **/

    if (symmetricKey == null) {

        keygen = KeyGenerator.getInstance(EBWConstants.ENCRYPTION_KEYGEN_ALGORITHM);

        symmetricKey = keygen.generateKey();

        try {

            //          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("d:/UBS/AES.key")));

            //          oos.writeObject(symmetricKey);

            //          oos.close();

            //          System.out.println("Key File written");

            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(new File(EBWConstants.SYMMETRIC_KEY_FILENAME)));

            Key symmetricKeyNew = (Key) ois.readObject();

            //oos.close(); 

            //System.out.println("Key File read");

            symmetricKey = symmetricKeyNew;

            /*ObjectWriter bw=new ObjectWriter(new FileWriter("d:/UBS/AES.key"));
                    
                    
            bw.write(symmetricKey.toString());
                    
                    
            bw.close();
                    
                    
            */

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    } else {

        //EBWLogger.logDebug(this,"Key Already set");

    }

    return symmetricKey;

}