Example usage for javax.crypto SecretKey getEncoded

List of usage examples for javax.crypto SecretKey getEncoded

Introduction

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

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Encrypt plain text using AES/*from w w w . j av  a  2  s.  c o  m*/
 *
 * @param plainText the String text to be encrypted in AES
 * @return the encrypted text String
 *
 */
public static String encrypt(String plainText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return new Base64().encodeAsString(encryptedTextBytes);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to encrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to encrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to encrypt a string. ");
    } catch (IllegalBlockSizeException e) {
        logger.error("IllegalBlockSizeException when attempting to encrypt a string. ");
    } catch (BadPaddingException e) {
        logger.error("BadPaddingException when attempting to encrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to encrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to encrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to encrypt a string. ");
    }
    return null;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Decrypt a string value/* w  w w  . ja  va 2 s.c o m*/
 *
 * @param encryptedText the text String to be decrypted
 * @return the decrypted String
 *
 */
public static String decrypt(String encryptedText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        byte[] encryptedTextBytes = Base64.decodeBase64(encryptedText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        // Decrypt the message, given derived key and initialization vector.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException e) {
            logger.error("IllegalBlockSizeException when attempting to decrypt a string.");
        } catch (BadPaddingException e) {
            logger.error("BadPaddingException when attempting to decrypt a string.");
        }
        if (decryptedTextBytes != null) {
            return new String(decryptedTextBytes);
        }

    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to decrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to decrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to decrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to decrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to decrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to decrypt a string. ");
    }
    return null;
}

From source file:com.ntsync.android.sync.client.ClientKeyHelper.java

private static void validateKey(byte[] check, SecretKey skey) throws InvalidKeyException {
    AEADBlockCipher cipher = CryptoHelper.getCipher();
    try {//www  .j a v  a 2 s  .c om
        // data, pos, IV_LEN)
        byte[] iv = new byte[CryptoHelper.IV_LEN];
        System.arraycopy(check, 0, iv, 0, CryptoHelper.IV_LEN);
        cipher.init(false, new AEADParameters(new KeyParameter(skey.getEncoded()), CryptoHelper.MAC_SIZE, iv));
        byte[] original = CryptoHelper.cipherData(cipher, check, IV_LENGTH, check.length - IV_LENGTH);

        String orgValue = new String(original, SyncDataHelper.DEFAULT_CHARSET_NAME);
        // Validate Checksum
        int res1 = calcUpcChecksum(orgValue);
        int len = orgValue.length();
        if (orgValue.length() == 0 || res1 != Integer.parseInt(orgValue.substring(len - 1, len))) {
            throw new InvalidKeyException("Invalid Key. Checksum error");
        }
    } catch (NumberFormatException ex) {
        throw new InvalidKeyException("Invalid Key. Data is not number.", ex);
    } catch (DataLengthException e) {
        throw new InvalidKeyException("Invalid Key", e);
    } catch (IllegalStateException e) {
        throw new InvalidKeyException("Invalid Key. Wrong Parameter.", e);
    } catch (InvalidCipherTextException e) {
        throw new InvalidKeyException("Invalid Key.", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("No support for UTF-8 available.", e);
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Encrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return encrypted string, bytes first encoded base64, IV separated with "|", then to string
 *//*  ww  w .  j a  va  2 s  .  c o m*/
public static String encryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException {
    Cipher cipher = Cipher.getInstance(AES_CIPHER);

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] salt = randomBytes(saltLength);
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] bytes = encodeStringToBase64Bytes(privateKey);
    byte[] encrypted = cipher.doFinal(bytes);

    byte[] iv = cipher.getIV();
    String encodedIV = encodeBytesToBase64String(iv);
    String encodedSalt = encodeBytesToBase64String(salt);
    String encodedEncryptedBytes = encodeBytesToBase64String(encrypted);

    return encodedEncryptedBytes + ivDelimiter + encodedIV + ivDelimiter + encodedSalt;
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key, IV separated with "|"
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return decrypted string/*  w  ww  .j a  v  a 2s  .  c  o m*/
 */
public static String decryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException, InvalidAlgorithmParameterException {

    // split up iv, salt
    String[] strings = privateKey.split(ivDelimiter);
    String realPrivateKey = strings[0];
    byte[] iv = decodeStringToBase64Bytes(strings[1]);
    byte[] salt = decodeStringToBase64Bytes(strings[2]);

    Cipher cipher = Cipher.getInstance(AES_CIPHER);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

    byte[] bytes = decodeStringToBase64Bytes(realPrivateKey);
    byte[] decrypted = cipher.doFinal(bytes);

    String pemKey = decodeBase64BytesToString(decrypted);

    return pemKey.replaceAll("\n", "").replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "");
}

From source file:com.ntsync.android.sync.client.ClientKeyHelper.java

private static byte[] createPwdCheck(SecretKey skey) throws InvalidKeyException, UnsupportedEncodingException {
    byte[] iv = new byte[IV_LENGTH];
    SecureRandom random = new SecureRandom();
    random.nextBytes(iv);/* www. j  a  va 2  s  .c  o m*/
    AEADBlockCipher ecipher = CryptoHelper.getCipher();
    byte[] checkData;
    try {
        ecipher.init(true, new AEADParameters(new KeyParameter(skey.getEncoded()), CryptoHelper.MAC_SIZE, iv));

        // create random integer with checksum (UPC-Format : 12 digits)
        String testValue = String.format("%011d", random.nextInt(Integer.MAX_VALUE)) + "0";
        int res1 = calcUpcChecksum(testValue);

        testValue = testValue.substring(0, UPC_NR_LEN) + res1;

        byte[] pwdCheck = CryptoHelper.cipherData(ecipher,
                testValue.getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));

        checkData = new byte[iv.length + pwdCheck.length];
        System.arraycopy(iv, 0, checkData, 0, iv.length);
        System.arraycopy(pwdCheck, 0, checkData, iv.length, pwdCheck.length);
    } catch (DataLengthException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    } catch (IllegalStateException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    } catch (InvalidCipherTextException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    }

    return checkData;
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * KEY?//www  .  java 2 s  . c  om
 * 
 * @param key
 * @param file
 *            ???
 * @return File,????
 */
public static File saveKey(SecretKey key, File file) {
    try {
        File f = IOUtils.escapeExistFile(file);
        IOUtils.saveAsFile(f, false, key.getEncoded());
        return f;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * @return null if failure, otherwise hex string version of key
 * @author Isaac Potoczny-Jones/*from  w w  w .j av a 2s.c o m*/
 */
public static String generateMasterKey() throws NoSuchAlgorithmException {
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        SecretKey genDesKey = keygen.generateKey();
        return toHexString(genDesKey.getEncoded());
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
        throw e;
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void printSecreyKey(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    String alias = loadOption(cmd, "alias", options);
    SecretKey key = (SecretKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
    String val = Base64.encode(key.getEncoded());
    logger.info(val);
}

From source file:com.jwm123.loggly.reporter.TripleDesCipher.java

private void getKey() throws NoSuchAlgorithmException, IOException {
    File keyFile = appDir.getFileDir(keyPath);
    if (keyFile.exists()) {
        key = Base64.decode(FileUtils.readFileToString(keyFile));
    } else {//from   w w  w  .  jav a2  s  .  co  m
        KeyGenerator generator = KeyGenerator.getInstance("DESede");
        SecretKey desKey = generator.generateKey();
        key = desKey.getEncoded();
        FileUtils.writeStringToFile(keyFile, new String(Base64.encode(key)));
    }

}