Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password) 

Source Link

Document

Constructor that takes a password.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    Key sharedKey = kg.generateKey();

    String password = "password";
    byte[] salt = "salt1234".getBytes();
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey passwordKey = kf.generateSecret(keySpec);
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
    c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
    byte[] wrappedKey = c.wrap(sharedKey);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, sharedKey);
    byte[] input = "input".getBytes();
    byte[] encrypted = c.doFinal(input);

    c = Cipher.getInstance("PBEWithMD5AndDES");

    c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
    Key unwrappedKey = c.unwrap(wrappedKey, "DESede", Cipher.SECRET_KEY);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.DECRYPT_MODE, unwrappedKey);
    System.out.println(new String(c.doFinal(encrypted)));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x73, 0x2f, 0x2d, 0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75,
            0x6c, (byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03, (byte) 0xdd, (byte) 0xd9,
            0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e };
    byte[] ivBytes = new byte[] { (byte) 0xb0, 0x7b, (byte) 0xf5, 0x22, (byte) 0xc8, (byte) 0xd6, 0x08,
            (byte) 0xb8 };

    // encrypt the data using precalculated keys

    Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");

    cEnc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(ivBytes));

    byte[] out = cEnc.doFinal(input);

    // decrypt the data using PBE

    char[] password = "password".toCharArray();
    byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
    int iterationCount = 2048;
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");

    Cipher cDec = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");
    Key sKey = keyFact.generateSecret(pbeSpec);

    cDec.init(Cipher.DECRYPT_MODE, sKey, new PBEParameterSpec(salt, iterationCount));

    System.out.println("cipher : " + new String(out));
    System.out.println("gen key: " + new String(sKey.getEncoded()));
    System.out.println("gen iv : " + new String(cDec.getIV()));
    System.out.println("plain  : " + new String(cDec.doFinal(out)));
}

From source file:Main.java

/**
 * Generates a SecretKey.//from   w  w w.j a  v  a  2 s  .  c o  m
 */
public static SecretKey newSecretKey(String algorithm, String password) {
    return newSecretKey(algorithm, new PBEKeySpec(password.toCharArray()));
}

From source file:MainClass.java

private static String encrypt(char[] password, String plaintext) throws Exception {

    byte[] salt = new byte[8];
    Random random = new Random();
    random.nextBytes(salt);/*  w  w  w  .ja va  2 s .  c  o m*/

    PBEKeySpec keySpec = new PBEKeySpec(password);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");

    SecretKey key = keyFactory.generateSecret(keySpec);

    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 1000);

    Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
    cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

    byte[] ciphertext = cipher.doFinal(plaintext.getBytes());

    BASE64Encoder encoder = new BASE64Encoder();

    String saltString = encoder.encode(salt);
    String ciphertextString = encoder.encode(ciphertext);

    return saltString + ciphertextString;
}

From source file:MainClass.java

static Cipher createCipher(int mode) throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec("test".toCharArray());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(keySpec);
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update("input".getBytes());
    byte[] digest = md.digest();
    byte[] salt = new byte[8];
    for (int i = 0; i < 8; ++i)
        salt[i] = digest[i];//from w  w w. jav  a  2s .  c om
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    cipher.init(mode, key, paramSpec);
    return cipher;
}

From source file:MainClass.java

private static String decrypt(char[] password, String text) throws Exception {
    String salt = text.substring(0, 12);
    String ciphertext = text.substring(12, text.length());
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] saltArray = decoder.decodeBuffer(salt);
    byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);

    PBEKeySpec keySpec = new PBEKeySpec(password);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");

    SecretKey key = keyFactory.generateSecret(keySpec);

    PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, 1000);

    Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
    cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

    return new String(cipher.doFinal(ciphertextArray));
}

From source file:MainClass.java

private static byte[] passwordEncrypt(char[] password, byte[] plaintext) throws Exception {
    int MD5_ITERATIONS = 1000;
    byte[] salt = new byte[8];
    SecureRandom random = new SecureRandom();
    random.nextBytes(salt);//  w ww . ja v a2 s.  c  o  m

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
    SecretKey key = keyFactory.generateSecret(keySpec);
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, MD5_ITERATIONS);
    Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
    cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

    byte[] ciphertext = cipher.doFinal(plaintext);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(salt);
    baos.write(ciphertext);
    return baos.toByteArray();
}

From source file:Main.java

private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey)
        throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {//from  www .ja  va2 s  . co  m
        epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
        // Probably not an encrypted key.
        return null;
    }

    char[] password = System.console().readPassword("Password for the private key file: ");

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(password));
    Arrays.fill(password, '\0');

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
        return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
        System.err.println("Password may be bad.");
        throw ex;
    }
}

From source file:ch.helmchen.camlapse.user.control.Encryption.java

/**
 * Verschlsselt den bergebenen String./*from   www.j  a  va2 s.c  o  m*/
 * 
 * @param aString zu verschlsselnder String.
 */
public static String encrypt(final String aString) throws GeneralSecurityException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    return base64Encode(pbeCipher.doFinal(aString.getBytes()));
}

From source file:org.opentravel.pubs.config.PasswordHelper.java

/**
 * Encrypts the given password./*ww w.  j  a va2  s.c  om*/
 * 
 * @param clearTextPassword  the clear-text password to encrypt
 * @return String
 */
public static String encrypt(String clearTextPassword) {
    try {
        String encryptionPassword = ConfigSettingsFactory.getConfig().getEncryptionPassword();
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(encryptionPassword.toCharArray()));
        Cipher pbeCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);

        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(new Base64().encode(pbeCipher.doFinal(clearTextPassword.getBytes("UTF-8"))));

    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
        throw new RuntimeException("Error during password encryption.", e);
    }
}