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:org.chililog.server.common.CryptoUtils.java

/**
 * <p>/*from  www  .  ja  va 2s.co m*/
 * Decrypt an encrypted text string using AES. The output is the plain text string.
 * </p>
 * 
 * @param encryptedText
 *            encrypted text returned by <code>encrypt</code>
 * @param password
 *            password used at the time of encryption
 * @return decrypted plain text string
 * @throws ChiliLogException
 */
public static String decryptAES(String encryptedText, String password) throws ChiliLogException {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        Base64 decoder = new Base64(1000, new byte[] {}, false);
        byte[] encryptedTextBytes = decoder.decode(encryptedText);

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, paramSpec);
        byte[] plainTextBytes = cipher.doFinal(encryptedTextBytes);

        return new String(plainTextBytes, "UTF-8");
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to decrpt. " + ex.getMessage());
    }
}

From source file:org.chililog.server.common.CryptoUtils.java

/**
 * <p>/*from   w ww. ja  va2s  .  c  o  m*/
 * Encrypt a plain text string using AES. The output is an encrypted plain text string. See
 * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413
 * </p>
 * <p>
 * The algorithm used is <code>base64(aes(plainText))</code>
 * </p>
 * 
 * 
 * @param plainText
 *            text to encrypt
 * @param password
 *            password to use for encryption
 * @return encrypted text
 * @throws ChiliLogException
 */
public static String encryptAES(String plainText, String password) throws ChiliLogException {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        byte[] plainTextBytes = plainText.getBytes("UTF-8");

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, paramSpec);
        byte[] cipherText = cipher.doFinal(plainTextBytes);

        // Convert hash to string
        Base64 encoder = new Base64(1000, new byte[] {}, false);
        return encoder.encodeToString(cipherText);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to encrypt. " + ex.getMessage());
    }
}

From source file:com.cloudant.sync.datastore.encryption.DPKEncryptionUtil.java

/**
 * Decrypt an AES encrypted byte array/*from   w w w  .j a v a 2s .  c om*/
 *
 * @param key            The encryption key
 * @param iv             The iv
 * @param encryptedBytes The data to decrypt
 * @return The decrypted data
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static byte[] decryptAES(SecretKey key, byte[] iv, byte[] encryptedBytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameter = new IvParameterSpec(iv);
    // see http://stackoverflow.com/a/11506343
    Key encryptionKey = new SecretKeySpec(key.getEncoded(), "AES");
    aesCipher.init(Cipher.DECRYPT_MODE, encryptionKey, ivParameter);
    return aesCipher.doFinal(encryptedBytes);
}

From source file:com.cloudant.sync.datastore.encryption.DPKEncryptionUtil.java

/**
 * AES Encrypt a byte array/*from  w  ww  . j a  v  a2  s  .co  m*/
 *
 * @param key              The encryption key
 * @param iv               The iv
 * @param unencryptedBytes The data to encrypt
 * @return The encrypted data
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static byte[] encryptAES(SecretKey key, byte[] iv, byte[] unencryptedBytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameter = new IvParameterSpec(iv);
    // see http://stackoverflow.com/a/11506343
    Key encryptionKey = new SecretKeySpec(key.getEncoded(), "AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, encryptionKey, ivParameter);
    return aesCipher.doFinal(unencryptedBytes);
}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

static String encrypt(final Cipher aesCipher, final Cipher rsaCipher, final String plainText)
        throws BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException {
    SecretKey aesKey = aesKey(256);
    byte[] iv = iv(CSE_RANDOM, 12);
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
    byte[] encrypted = aesCipher.doFinal(plainText.getBytes());

    byte[] result = new byte[iv.length + encrypted.length];
    System.arraycopy(iv, 0, result, 0, iv.length);
    System.arraycopy(encrypted, 0, result, iv.length, encrypted.length);

    byte[] encryptedAESKey;
    try {/*from  w ww  .j av  a2  s  . c o  m*/
        encryptedAESKey = rsaCipher.doFinal(aesKey.getEncoded());
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new InvalidKeyException(e.getMessage());
    }
    return String.format("%s%s%s%s%s%s", CSE_PREFIX, CSE_VERSION, CSE_SEPARATOR,
            Base64.encodeBase64String(encryptedAESKey), CSE_SEPARATOR, Base64.encodeBase64String(result));
}

From source file:eap.util.EDcodeUtil.java

private static byte[] genHmacKey(String algorithm) {
    try {/*from   w ww  . j av a2 s. c om*/
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm, provider);
        SecretKey secretKey = keyGenerator.generateKey();

        return secretKey.getEncoded();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
    }
}

From source file:io.stallion.utils.Encrypter.java

private static SecretKeySpec makeKeySpec(String password, String salt) {
    byte[] saltBytes = new byte[0];
    try {//from   ww w.java2  s . c om
        saltBytes = Hex.decodeHex(salt.toCharArray());
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, ITERATIONS, KEY_LENGTH);
    SecretKey secretKey;
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        secretKey = factory.generateSecret(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Not a valid encryption algorithm", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Not a valid secret key", e);
    }
    SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    return skeySpec;
}

From source file:eap.util.EDcodeUtil.java

private static byte[] aes(byte[] data, byte[] key, int keyLen, int opMode) {
    try {//from   w  ww .  ja v a 2  s .  c  o m
        KeyGenerator kgen = KeyGenerator.getInstance("AES", provider);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // provider
        secureRandom.setSeed(key);
        kgen.init(keyLen, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");

        /* mode:   ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128<br/> 
        * padding: Nopadding/PKCS5Padding/ISO10126Padding
        */
        Cipher cipher = Cipher.getInstance("AES", provider); // ECB/PKCS5Padding
        cipher.init(opMode, keySpec);

        return cipher.doFinal(data);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }

    //      // we're using Bouncy Castle
    //       Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider())
    //
    //       // create our key specification
    //       val secretKeySpec = new SecretKeySpec(hexStringToByteArray(hexEncodedKey), "AES")
    //        
    //       // create an AES engine in CTR mode (no padding)
    //       val aes = Cipher.getInstance("AES/CTR/NoPadding", BouncyCastleProvider.PROVIDER_NAME)
    //        
    //       // initialize the AES engine in encrypt mode with the key and IV
    //       aes.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(hexStringToByteArray(hexEncodedIv)))
    //        
    //       // encrypt the message and return the encrypted byte array
    //       aes.doFinal(hexStringToByteArray(hexEncodedMessage))
}

From source file:com.microsoft.azure.storage.util.KeyVaultUtility.java

/**
 * Creates a secret in Azure Key Vault and returns its ID.
 * // www  .j ava2  s. co  m
 * @param secretName
 *            The name of the secret to create
 * @return The ID of the created secret
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws NoSuchAlgorithmException
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String SetUpKeyVaultSecret(String secretName) throws InterruptedException, ExecutionException,
        NoSuchAlgorithmException, URISyntaxException, MalformedURLException {
    KeyVaultClient cloudVault = GetKeyVaultClient();

    if (Utility.vaultURL == null || Utility.vaultURL.isEmpty()) {
        throw new IllegalArgumentException("No Keyvault URL specified.");
    }

    try {
        // Delete the secret if it exists.
        cloudVault.deleteSecretAsync(Utility.vaultURL, secretName).get();
    } catch (ExecutionException ex) {
        boolean keyNotFound = false;
        if (ex.getCause().getClass() == ServiceException.class) {
            ServiceException serviceException = (ServiceException) ex.getCause();
            if (serviceException.getHttpStatusCode() == 404) {
                keyNotFound = true;
            }
        }

        if (!keyNotFound) {
            System.out.println(
                    "Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
            System.out.println(
                    "Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
            System.out.println("Press any key to exit");
            Scanner input = new Scanner(System.in);
            input.nextLine();
            input.close();
            throw ex;
        }
    }

    // Create a 256bit symmetric key and convert it to Base64.
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256); // Note that we cannot use SymmetricKey.KeySize256,
                      // because this resolves to '0x20'.
    SecretKey wrapKey = keyGen.generateKey();

    // Store the Base64 of the key in the key vault. Note that the
    // content-type of the secret must
    // be application/octet-stream or the KeyVaultKeyResolver will not load
    // it as a key.
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/octet-stream");
    Secret cloudSecret = cloudVault.setSecretAsync(Utility.vaultURL, secretName,
            Base64.encodeBase64String(wrapKey.getEncoded()), "application/octet-stream", null, null).get();

    // Return the base identifier of the secret. This will be resolved to
    // the current version of the secret.
    return cloudSecret.getSecretIdentifier().getBaseIdentifier();
}

From source file:com.aegiswallet.utils.WalletUtils.java

private static String getRawKey(SecretKey key) {
    if (key == null) {
        return null;
    }/*from  w w  w  .j av a  2 s .c o m*/

    return Crypto.toHex(key.getEncoded());
}