Example usage for javax.crypto SecretKeyFactory getInstance

List of usage examples for javax.crypto SecretKeyFactory getInstance

Introduction

In this page you can find the example usage for javax.crypto SecretKeyFactory getInstance.

Prototype

public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecretKeyFactory object that converts secret keys of the specified algorithm.

Usage

From source file:DesEncrypter.java

private DesEncrypter(String passPhrase) {
    try {/*  ww  w  .j  av a2  s .co  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 (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
}

From source file:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Encrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToEncrypt - text to encrypt
 * @return an encrypted, Base64 encoded text
 *//*from  w w  w  .  j a v a2s.  c  om*/
public static String encryptString(String valueToEncrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        // begin encrypting...
        byte[] byteToEncrypt = valueToEncrypt.getBytes("UTF8");
        byte[] encrypted = cipher.doFinal(byteToEncrypt);
        output = new Base64().encodeToString(encrypted);
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:org.apache.xml.security.samples.encryption.Decrypter.java

private static SecretKey loadKeyEncryptionKey() throws Exception {

    String fileName = "kek";
    String jceAlgorithmName = "DESede";

    File kekFile = new File(fileName);

    DESedeKeySpec keySpec = new DESedeKeySpec(JavaUtils.getBytesFromFile(fileName));
    SecretKeyFactory skf = SecretKeyFactory.getInstance(jceAlgorithmName);
    SecretKey key = skf.generateSecret(keySpec);

    System.out.println("Key encryption key loaded from " + kekFile.toURL().toString());
    return key;//w  w  w .  j av a 2 s  . co  m
}

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 .  jav  a 2 s  .  c  o m
 */
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:net.sf.hajdbc.codec.crypto.CipherCodecFactoryTest.java

@Before
public void before() throws Exception {
    File file = File.createTempFile("ha-jdbc", "keystore");

    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    this.key = factory.generateSecret(new DESKeySpec(Base64.decodeBase64(KEY.getBytes())));
    KeyStore store = KeyStore.getInstance(CipherCodecFactory.Property.KEYSTORE_TYPE.defaultValue);
    store.load(null, null);/*  w  w  w.j  av a 2  s .co  m*/
    store.setKeyEntry(CipherCodecFactory.Property.KEY_ALIAS.defaultValue, this.key, KEY_PASSWORD.toCharArray(),
            null);

    FileOutputStream out = new FileOutputStream(file);
    try {
        store.store(out, STORE_PASSWORD.toCharArray());
    } finally {
        Resources.close(out);
    }

    System.setProperty(CipherCodecFactory.Property.KEYSTORE_FILE.name, file.getPath());
    System.setProperty(CipherCodecFactory.Property.KEYSTORE_PASSWORD.name, STORE_PASSWORD);
    System.setProperty(CipherCodecFactory.Property.KEY_PASSWORD.name, KEY_PASSWORD);
}

From source file:org.mayocat.security.DefaultCipher.java

private String crypt(String input, Mode mode) throws EncryptionException {
    if (Strings.isNullOrEmpty(this.configuration.getEncryptionKey())) {
        throw new EncryptionException("Invalid or missing cookie encryption key in configuration file. "
                + "You MUST specify a key in order to support cookie authentication.");
    }/*from   w ww  .j av  a  2 s  .  c  om*/

    try {
        byte[] in = input.getBytes();

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        byte[] keyBytes = this.configuration.getEncryptionKey().getBytes("UTF-8");
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKey key = keyFactory.generateSecret(desKeySpec);

        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding");
        IvParameterSpec spec = null;
        if (cipher.getParameters() != null) {
            spec = cipher.getParameters().getParameterSpec(IvParameterSpec.class);
        }

        switch (mode) {
        case CRYPT:
        default:
            if (spec != null) {
                cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, spec);
            } else {
                cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key);
            }
            byte[] encrypted = cipher.doFinal(in);
            return new String(Base64.encodeBase64(encrypted));
        case DECRYPT:
            if (spec != null) {
                cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, spec);
            } else {
                cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key);
            }
            byte[] decrypted = cipher.doFinal(Base64.decodeBase64(in));
            return new String(decrypted);
        }

    } catch (BadPaddingException e) {
        this.logger.warn("Bad padding when attempting to decipher cookies. Key changed ?");
        throw new EncryptionException(e);
    } catch (Exception e) {
        this.logger.error("Fail to perform cookie crypt or decrypt operation", e);
        throw new EncryptionException(e);
    }
}

From source file:com.seer.datacruncher.utils.CryptoUtil.java

public CryptoUtil() {
    try {//from  w ww . ja v  a  2  s.c om
        String myEncryptionKey = cryWorm(Reserved.ENCRYPTIONKEY, Reserved.CHECK, 0);
        String myEncryptionSchema = DESEDE_ENCRYPTION_SCHEMA;
        byte[] keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        KeySpec myKeySpec = new DESedeKeySpec(keyAsBytes);
        SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionSchema);
        cipher = Cipher.getInstance(myEncryptionSchema);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.blackcrowsys.sinscrypto.AesKeyGenerator.java

@Override
public SecretKey generateSecretKey(String password, String salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException, DecoderException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), Hex.decodeHex(salt.toCharArray()), ITERATION,
            KEYLENGTH);/*from   w  w w .j  a  v a 2 s . c o m*/
    SecretKey key = factory.generateSecret(spec);
    return new SecretKeySpec(key.getEncoded(), ENCRYPTION);
}

From source file:Crypt.java

private Crypt() {
    DESKeySpec dk;/*www .j a  v  a 2  s  .  c  o  m*/
    try {
        dk = new DESKeySpec(new Long(serialVersionUID).toString().getBytes());
        SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
        secretKey = kf.generateSecret(dk);
    } catch (Exception e) {
        log.error("", e);
    }
}

From source file:com.hypersocket.auth.PasswordEncryptionService.java

public byte[] getEncryptedPassword(char[] password, byte[] salt, PasswordEncryptionType type)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    KeySpec spec = new PBEKeySpec(password, salt, type.getIterations(), type.getKeyLength());

    SecretKeyFactory f = SecretKeyFactory.getInstance(type.toString());

    return f.generateSecret(spec).getEncoded();
}