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.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java

private SecretKey generateDataEncryptionKey() {
    try {//from  w  w w .ja v  a 2s  .c o  m
        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:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a string using a random session key
 *
 * @param plaintext//  w  w w  . j  a  va2s . c  om
 * @return encrypted String
 * @throws Exception
 * @author Peli
 */
public String encryptWithSessionKey(String plaintext) throws CryptoHelperException {
    if (debug) {
        Log.i(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }
    byte[] cipherSessionKey = {};
    byte[] ciphertext = {};

    // First create a session key
    SecretKey sessionKey = null;
    byte[] sessionKeyEncoded = null;
    String sessionKeyString = null;
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256); // needs 96 bytes
        //keygen.init(128); // needs 64 bytes
        sessionKey = keygen.generateKey();
        sessionKeyEncoded = sessionKey.getEncoded();
        sessionKeyString = new String(sessionKeyEncoded);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
    }

    // Convert this to a Pbe key
    PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(sessionKeyString.toCharArray());
    SecretKey sessionPbeKey = null;
    try {
        sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "setPassword(): " + e.toString());
    }

    // Encrypt the session key using the master key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
    }

    // Now encrypt the text using the session key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, sessionPbeKey, pbeParamSpec);
        ciphertext = pbeCipher.doFinal(plaintext.getBytes());
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey2(): " + e.toString());
    }

    String stringCipherVersion = "A";
    String stringCipherSessionKey = toHexString(cipherSessionKey);
    String stringCiphertext = toHexString(ciphertext);
    if (debug) {
        Log.i(TAG, "Length: " + stringCipherSessionKey.length() + ", " + stringCipherSessionKey);
    }

    StringBuilder sb = new StringBuilder(
            stringCipherVersion.length() + stringCipherSessionKey.length() + stringCiphertext.length());
    sb.append(stringCipherVersion);
    sb.append(stringCipherSessionKey);
    sb.append(stringCiphertext);
    return sb.toString();
}

From source file:com.data.pack.Util.java

public static void copyFile(InputStream in, OutputStream out, int flag) throws IOException {
    byte[] buffer = new byte[1024];
    int read;// ww  w.j  a v a2s .  co m

    try {

        Cipher encipher = null;
        try {
            encipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Cipher decipher = null;
        try {
            decipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] keyStart = "fitnesSbridge".getBytes();
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        // byte key[] =
        // {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
        skey = kgen.generateKey();
        // Lgo
        try {
            encipher.init(Cipher.ENCRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherInputStream cis = new CipherInputStream(in, encipher);
        try {
            decipher.init(Cipher.DECRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherOutputStream cos = new CipherOutputStream(out, decipher);

        try {

            if (flag == 2) {
                cos = new CipherOutputStream(out, encipher);
            } else {
                cos = new CipherOutputStream(out, decipher);
            }
            while ((read = in.read()) != -1) {
                cos.write(read);
                cos.flush();
            }

            cos.flush();
            cos.close();
            in.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

    //
    // byte[] keyStart = "this is a key".getBytes();
    // KeyGenerator kgen = KeyGenerator.getInstance("AES");
    // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    // sr.setSeed(keyStart);
    // kgen.init(128, sr); // 192 and 256 bits may not be available
    // SecretKey skey = kgen.generateKey();
    // byte[] key = skey.getEncoded();
    //
    //
    // byte[] b = baos.toByteArray();
    // while ((read = in.read(buffer)) != -1) {
    //
    // // decrypt
    // byte[] decryptedData = Util.decrypt(key,buffer);
    // out.write(decryptedData, 0, read);
    // }
    // } catch (NoSuchAlgorithmException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // catch (Exception e) {
    // // TODO: handle exception
    // }
    //
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Generates a new key. Should be used manually and only when creating a new
 * key is necessary. WARNING: If the keys in the KeyStore files are replaced
 * then we will not be able to decrypt passwords that were encrypted with
 * the old keys./*from   w  w w .  j a  v a2  s.c  om*/
 *
 * @param keypass
 *            char[] with the keypass that will gain access to the key
 *            (currently hard coded in)
 * @throws IOException
 */
@SuppressWarnings("unused")
private static Key setKey(final char[] keypass, final File keyFile) throws Exception {

    Key key = null;
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(keyFile.getCanonicalPath());
        key = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM).generateKey();
        final KeyStore keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(null, null);
        keystore.setKeyEntry(KEY_ALIAS, key, keypass, null);
        keystore.store(output, keypass);
    } finally {
        if (output != null) {
            output.close();
        }
    }

    return key;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void generateKey(KeyStore keyStore) throws SecureLocalStorageException {

    try {//ww  w.j ava2s. c  o m
        _key = null;

        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            try {
                oos.writeObject(key);
            } finally {
                oos.close();
            }
        } finally {
            bos.close();
        }

        // store key encrypted with keystore key pair
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore
                .getEntry(SECURELOCALSTORAGEALIAS, null);

        Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        input.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEKEY,
                Context.MODE_PRIVATE);
        try {
            CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input);
            try {
                cipherOutputStream.write(bos.toByteArray());
            } finally {
                cipherOutputStream.close();
            }
        } finally {
            fos.close();
        }

    } catch (Exception e) {
        Log.e("SecureStorage", "Read", e);
        throw new SecureLocalStorageException("Error generating key", e);
    }
}

From source file:org.tolven.security.password.PasswordHolder.java

private void generateSecretKey(File secretKeyFile) {
    if (getSecretKeyFile().exists()) {
        throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath());
    }//from w  w w .j av  a 2 s. c om
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(112);
        secretKey = keyGenerator.generateKey();
        String alias = getKeyStore().aliases().nextElement();
        Certificate adminCert = getKeyStore().getCertificate(alias);
        PublicKey publicKey = adminCert.getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] encryptedSecretKey = cipher.wrap(secretKey);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(secretKeyFile);
            out.write(Base64.encodeBase64(encryptedSecretKey));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex);
    }
}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Adds encrypted assertions to a SAML2 Response
 *
 * @param encryptionCert the X509 certificate to use for encrypting the assertions
 * @param assertionDoc the assertions to encrypt
 * @param responseDoc the SAML2 Response to add the encrypted assertions to
 * @throws GuanxiException if an error occurs
 *//*from www  . j a  va  2s.  c o  m*/
protected void addEncryptedAssertionsToResponse(X509Certificate encryptionCert, AssertionDocument assertionDoc,
        ResponseDocument responseDoc) throws GuanxiException {
    try {
        PublicKey keyEncryptKey = encryptionCert.getPublicKey();

        // Generate a secret key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();

        XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP);
        keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptKey);

        Document domAssertionDoc = (Document) assertionDoc.newDomNode(xmlOptions);
        EncryptedKey encryptedKey = keyCipher.encryptKey(domAssertionDoc, secretKey);

        Element elementToEncrypt = domAssertionDoc.getDocumentElement();

        XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
        xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);

        // Add KeyInfo to the EncryptedData element
        EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
        KeyInfo keyInfo = new KeyInfo(domAssertionDoc);
        keyInfo.add(encryptedKey);
        encryptedDataElement.setKeyInfo(keyInfo);

        // Encrypt the assertion
        xmlCipher.doFinal(domAssertionDoc, elementToEncrypt, false);

        // Go back into XMLBeans land...
        EncryptedDataDocument encryptedDataDoc = EncryptedDataDocument.Factory.parse(domAssertionDoc);
        // ...and add the encrypted assertion to the response
        responseDoc.getResponse().addNewEncryptedAssertion()
                .setEncryptedData(encryptedDataDoc.getEncryptedData());

        // Look for the Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey node...
        EncryptedDataType encryptedData = responseDoc.getResponse().getEncryptedAssertionArray(0)
                .getEncryptedData();
        NodeList nodes = encryptedData.getKeyInfo().getDomNode().getChildNodes();
        Node encryptedKeyNode = null;
        for (int c = 0; c < nodes.getLength(); c++) {
            encryptedKeyNode = nodes.item(c);
            if (encryptedKeyNode.getLocalName() != null) {
                if (encryptedKeyNode.getLocalName().equals("EncryptedKey"))
                    break;
            }
        }

        // ...get a new KeyInfo ready...
        KeyInfoDocument keyInfoDoc = KeyInfoDocument.Factory.newInstance();
        X509DataType x509Data = keyInfoDoc.addNewKeyInfo().addNewX509Data();

        // ...and a useable version of the SP's encryption certificate...
        StringWriter sw = new StringWriter();
        PEMWriter pemWriter = new PEMWriter(sw);
        pemWriter.writeObject(encryptionCert);
        pemWriter.close();
        String x509 = sw.toString();
        x509 = x509.replaceAll("-----BEGIN CERTIFICATE-----", "");
        x509 = x509.replaceAll("-----END CERTIFICATE-----", "");

        // ...add the encryption cert to the new KeyInfo...
        x509Data.addNewX509Certificate().setStringValue(x509);

        // ...and insert it into Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey
        encryptedKeyNode.appendChild(
                encryptedKeyNode.getOwnerDocument().importNode(keyInfoDoc.getKeyInfo().getDomNode(), true));
    } catch (NoSuchAlgorithmException nsae) {
        logger.error("AES encryption not available");
        throw new GuanxiException(nsae);
    } catch (XMLEncryptionException xea) {
        logger.error("RSA_OAEP error with WRAP_MODE");
        throw new GuanxiException(xea);
    } catch (Exception e) {
        logger.error("Error encyrpting the assertion");
        throw new GuanxiException(e);
    }
}

From source file:org.apache.hadoop.crypto.key.KeyProvider.java

/**
 * Generates a key material./*from  w w  w  .  j  a v a 2  s .co  m*/
 *
 * @param size length of the key.
 * @param algorithm algorithm to use for generating the key.
 * @return the generated key.
 * @throws NoSuchAlgorithmException
 */
protected byte[] generateKey(int size, String algorithm) throws NoSuchAlgorithmException {
    algorithm = getAlgorithm(algorithm);
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
    keyGenerator.init(size);
    byte[] key = keyGenerator.generateKey().getEncoded();
    return key;
}

From source file:com.feilong.tools.security.symmetric.SymmetricEncryption.java

/**
 * ?.//from ww  w .  j ava2 s .  c  o  m
 * 
 * @param _keyString
 *            
 * @return Key
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @see <a href="http://blog.csdn.net/hbcui1984/article/details/5753083">Linux?AES</a>
 * @see KeyGenerator
 * @see SecureRandom
 */
private Key getKey(String _keyString) throws NoSuchAlgorithmException {
    // KeyGenerator ????????? KeyGenerator ??
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

    // SHA1PRNG: It is just ensuring the random number generated is as close to "truly random" as possible.
    // Easily guessable random numbers break encryption.

    // ???? (RNG) ???
    //TODO
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

    // SecureRandom??getInstance?setSeed
    //  :windowslinux?
    // javax.crypto.BadPaddingException: Given final block not properly padded
    secureRandom.setSeed(_keyString.getBytes());

    keyGenerator.init(secureRandom);

    Key _key = keyGenerator.generateKey();
    keyGenerator = null;
    return _key;
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

protected KeyStore getKeyStore(String username, char[] password) {
    try {/*from  w w w. ja va  2s.  com*/
        File keyStoreFile = new File(secretsFolder, username + ".jks");
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        if (keyStoreFile.exists()) {
            keyStore.load(new FileInputStream(keyStoreFile), password);
            return keyStore;
        } else {
            KeyGenerator gen = KeyGenerator.getInstance("Blowfish");
            SecretKey key = gen.generateKey();

            keyStore.load(null, password);
            keyStore.setEntry(username, new SecretKeyEntry(key), new KeyStore.PasswordProtection(password));

            keyStore.store(new FileOutputStream(keyStoreFile), password);

            return keyStore;
        }
    } catch (Exception ex) {
        // TODO: better exception handling
        Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex);
        throw new RuntimeException(ex);
    }
}