Example usage for javax.crypto SecretKey getAlgorithm

List of usage examples for javax.crypto SecretKey getAlgorithm

Introduction

In this page you can find the example usage for javax.crypto SecretKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:org.kitodo.data.encryption.DesEncrypter.java

private void initialise(String passPhrase) {
    int iterationCount = 19;

    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), defaultSalt, iterationCount);

    try {/*w ww .  j  ava  2  s.co  m*/
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        encryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        decryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(defaultSalt, iterationCount);
        encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
        decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
    } catch (InvalidKeySpecException e) {
        logger.info("Catched InvalidKeySpecException with message: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.info("Catched NoSuchAlgorithmException with message: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        logger.info("Catched NoSuchPaddingException with message: " + e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        logger.info("Catched InvalidAlgorithmParameterException with message: " + e.getMessage());
    } catch (InvalidKeyException e) {
        logger.info("Catched InvalidKeyException with message: " + e.getMessage());
    }
}

From source file:org.kitodo.production.security.password.SecurityPasswordEncoder.java

private void initialize(String passPhrase) {
    int iterationCount = 19;
    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), defaultSalt, iterationCount);
    try {//from w ww.j ava2s.com
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        encryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        decryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(defaultSalt, iterationCount);
        encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
        decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
    } catch (InvalidKeySpecException e) {
        logger.info("Catched InvalidKeySpecException with message: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.info("Catched NoSuchAlgorithmException with message: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        logger.info("Catched NoSuchPaddingException with message: " + e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        logger.info("Catched InvalidAlgorithmParameterException with message: " + e.getMessage());
    } catch (InvalidKeyException e) {
        logger.info("Catched InvalidKeyException with message: " + e.getMessage());
    }
}

From source file:org.mxupdate.eclipse.properties.ProjectProperties.java

/**
 * Returns encrypted/decrypted by salt password. Uses SHA-1 Message Digest
 * Algorithm as defined in NIST's FIPS 180-1. The output of this algorithm
 * is a 160-bit digest.//from  www  .ja  v  a 2  s.  c  o  m
 *
 * @param _password     password to encrypt / decrypt
 * @param _decrypt      <i>true</i> to decrypt or <i>false</i> to encrypt
 * @return decrypted / encrypted by salt password
 * @see #PDE_ALGORITHM
 * @see #PDE_PASSWORD
 * @see #PDE_SALT
 * @see #PDE_ITERATION
 */
private String decryptEncrypt(final String _password, final boolean _decrypt) {
    String ret = null;
    if (_password != null) {
        try {
            // create PBE parameter set
            final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(ProjectProperties.PDE_SALT,
                    ProjectProperties.PDE_ITERATION);
            final PBEKeySpec pbeKeySpec = new PBEKeySpec(ProjectProperties.PDE_PASSWORD,
                    ProjectProperties.PDE_SALT, ProjectProperties.PDE_ITERATION);
            final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ProjectProperties.PDE_ALGORITHM);
            final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

            final Cipher cipher = Cipher.getInstance(pbeKey.getAlgorithm());

            if (_decrypt) {
                cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
                // decode base64 to get bytes
                final byte[] dec = Base64.decodeBase64(_password.getBytes(ProjectProperties.ENCODING));
                // decrypt
                final byte[] ciphertext = cipher.doFinal(dec);

                ret = new String(ciphertext, ProjectProperties.ENCODING);

            } else {
                cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
                final byte[] pwdText = _password.getBytes(ProjectProperties.ENCODING);
                // encrypt the cleartext
                final byte[] ciphertext = cipher.doFinal(pwdText);

                ret = new String(Base64.encodeBase64(ciphertext), ProjectProperties.ENCODING);
            }
        } catch (final Exception e) {
            throw new Error(e);
        }
    }
    return ret;
}

From source file:org.nuxeo.common.codec.CryptoKeyStoreTest.java

@Override
public void setUp() throws Exception {
    super.setUp();
    Map<String, SecretKey> secretKeys = new HashMap<>();
    secretKeys.put(Crypto.AES, crypto.getSecretKey(Crypto.AES, secretKey));
    secretKeys.put(Crypto.DES, crypto.getSecretKey(Crypto.DES, secretKey));
    crypto.clear();//from  w  ww .  j  a  v a2s. c  o m

    // Generate a keystore where to store the key
    File keystoreFile = File.createTempFile("keystore", ".jceks",
            new File(System.getProperty("java.io.tmpdir")));
    keystoreFile.delete(); // ensure new keystore creation
    for (SecretKey key : secretKeys.values()) {
        Crypto.setKeyInKeyStore(keystoreFile.getPath(), keystorePass, keyAlias + key.getAlgorithm(), keyPass,
                key);
    }
    assertTrue(CollectionUtils.isEqualCollection(secretKeys.values(),
            Crypto.getKeysFromKeyStore(keystoreFile.getPath(), keystorePass, keyAlias, keyPass).values()));
    crypto = new Crypto(keystoreFile.getPath(), keystorePass, keyAlias, keyPass);
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception//from ww w  .j a v  a2  s.  c o m
 */
protected final void initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey tmp = factory.generateSecret(spec);

    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);

    if (log.isDebugEnabled())
        log.debug("Encrypting with: " + secret.getAlgorithm());

    cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
}

From source file:org.openmrs.module.reportingsummary.api.io.download.DownloadProcessor.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception/*from  w  w  w  .  j  a  v  a 2  s  . c  om*/
 */
private Cipher initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(InputOutputConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey secretKey = factory.generateSecret(spec);

    SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), InputOutputConstants.KEY_SPEC);

    if (log.isDebugEnabled())
        log.debug("Encrypting with: " + secret.getAlgorithm());

    Cipher cipher = Cipher.getInstance(InputOutputConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    return cipher;
}

From source file:org.orcid.core.crypto.DesEncrypter.java

private void initDesEncrypter(final String passPhrase) {
    try {/*from   w  w  w .  j a v a 2  s  . c o  m*/
        // Create the key
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        // Create the ciphers
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (GeneralSecurityException e) {
        LOGGER.trace("DesEncrypter.creation failed", e);
        throw new ApplicationException("DesEncrypter creation failed", e);
    }
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

public static TokenSearchResults searchTokenEntries(final KeyStore keyStore, final int startIndex,
        final int max, final QueryCriteria qc, final boolean includeData)
        throws CryptoTokenOfflineException, QueryException {
    final TokenSearchResults result;
    try {/*w ww  . j av a2  s  . c o  m*/
        final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>();
        final Enumeration<String> e = keyStore.aliases(); // We assume the order is the same for every call unless entries has been added or removed

        final long maxIndex = (long) startIndex + max;
        for (int i = 0; i < maxIndex && e.hasMoreElements();) {
            final String keyAlias = e.nextElement();

            final String type;
            if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) {
                type = TokenEntry.TYPE_PRIVATEKEY_ENTRY;
            } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
                type = TokenEntry.TYPE_SECRETKEY_ENTRY;
            } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) {
                type = TokenEntry.TYPE_TRUSTED_ENTRY;
            } else {
                type = null;
            }

            TokenEntry entry = new TokenEntry(keyAlias, type);

            if (shouldBeIncluded(entry, qc)) {
                if (i < startIndex) {
                    i++;
                    continue;
                }

                if (LOG.isDebugEnabled()) {
                    LOG.debug("checking keyAlias: " + keyAlias);
                }

                // Add additional data
                if (includeData) {
                    Map<String, String> info = new HashMap<String, String>();
                    try {
                        Date creationDate = keyStore.getCreationDate(keyAlias);
                        entry.setCreationDate(creationDate);
                    } catch (ProviderException ex) {
                    } // NOPMD: We ignore if it is not supported

                    if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) {
                        final Certificate[] chain = keyStore.getCertificateChain(keyAlias);
                        if (chain.length > 0) {
                            info.put(INFO_KEY_ALGORITHM,
                                    AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey()));
                            info.put(INFO_KEY_SPECIFICATION,
                                    AlgorithmTools.getKeySpecification(chain[0].getPublicKey()));
                        }
                        try {
                            entry.setParsedChain(chain);
                        } catch (CertificateEncodingException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
                        }
                    } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) {
                        Certificate certificate = keyStore.getCertificate(keyAlias);
                        try {
                            entry.setParsedTrustedCertificate(certificate);
                        } catch (CertificateEncodingException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
                        }
                    } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) {
                        try {
                            KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null);
                            SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey();

                            info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm());
                            //info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key specification support for secret keys
                        } catch (NoSuchAlgorithmException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
                        } catch (UnrecoverableEntryException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
                        }
                    }
                    entry.setInfo(info);
                }
                tokenEntries.add(entry);

                // Increase index
                i++;
            }
        }
        result = new TokenSearchResults(tokenEntries, e.hasMoreElements());
    } catch (KeyStoreException ex) {
        throw new CryptoTokenOfflineException(ex);
    }
    return result;
}

From source file:org.talend.daikon.security.CryptoHelper.java

/**
 * @param passPhrase the pass phrase used to encrypt and decrypt strings.
 *///from  w w  w . j  av a2  s  . c  om
public CryptoHelper(String passPhrase) {
    try {
        // Create the key
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); //$NON-NLS-1$
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        // Create the ciphers
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
        // do nothing
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private void writeDER(char[] password, PrivateKey privateKey, File file)
        throws IOException, GeneralSecurityException {
    byte[] bytes = null;
    if (password == null) {
        bytes = privateKey.getEncoded();
    } else {// w  w  w. ja va 2  s .c  o m
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        PBEKeySpec passwordSpec = new PBEKeySpec(password);
        SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedPrivateKey = cipher.doFinal(privateKey.getEncoded());
        EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(),
                encryptedPrivateKey);
        bytes = encryptedPrivateKeyInfo.getEncoded();
    }
    FileUtils.writeByteArrayToFile(file, bytes);
}