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.connorbrezinsky.msg.security.Hash.java

private static String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0)
        throw new IllegalArgumentException("Empty passwords are not supported.");
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}

From source file:cl.niclabs.tscrypto.common.messages.EncryptedData.java

private static SecretKeySpec generateAESKey() {
    SecretKeySpec skeySpec = null;
    try {/*from   w  ww. ja  va2s  . c o  m*/
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(KEYSIZE_AES);

        // Generate the secret key specs.
        SecretKey secretKey = keyGen.generateKey();

        skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return skeySpec;
}

From source file:org.b3log.latke.util.Crypts.java

/**
 * Encrypts by AES.//from   w  w  w  .  j av  a2  s. c o  m
 *
 * @param content the specified content to encrypt
 * @param key     the specified key
 * @return encrypted content
 * @see #decryptByAES(java.lang.String, java.lang.String)
 */
public static String encryptByAES(final String content, final String key) {
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        final SecretKey secretKey = kgen.generateKey();
        final byte[] enCodeFormat = secretKey.getEncoded();
        final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        final byte[] byteContent = content.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(byteContent);

        return Hex.encodeHexString(result);
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Encrypt failed", e);

        return null;
    }
}

From source file:org.b3log.latke.util.Crypts.java

/**
 * Decrypts by AES./*from   ww  w.ja v  a 2  s .  c  om*/
 *
 * @param content the specified content to decrypt
 * @param key     the specified key
 * @return original content
 * @see #encryptByAES(java.lang.String, java.lang.String)
 */
public static String decryptByAES(final String content, final String key) {
    try {
        final byte[] data = Hex.decodeHex(content.toCharArray());
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        final SecretKey secretKey = kgen.generateKey();
        final byte[] enCodeFormat = secretKey.getEncoded();
        final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(data);

        return new String(result, "UTF-8");
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Decrypt failed");

        return null;
    }
}

From source file:org.fejoa.library.crypto.UserKeyParameters.java

static public SecretKey deriveUserKey(SecretKey baseKey, UserKeyParameters settings) throws CryptoException {
    byte[] baseKeyBytes = baseKey.getEncoded();
    assert baseKeyBytes.length == 32;
    ByteArrayOutputStream combinedKey = new ByteArrayOutputStream();
    try {/*from ww w . java 2 s.co  m*/
        combinedKey.write(baseKeyBytes);
        combinedKey.write(settings.userKeySalt);
    } catch (IOException e) {
        e.printStackTrace();
        // should not happen
        assert false;
    }

    MessageDigest messageDigest;
    try {
        messageDigest = getMessageDigest(settings.hashAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(e);
    }
    byte[] out = CryptoHelper.hash(combinedKey.toByteArray(), messageDigest);
    return CryptoHelper.secretKey(out, baseKey.getAlgorithm());
}

From source file:org.atricore.idbus.kernel.main.authn.util.CipherUtil.java

/**
 * This generates a 128 AES key./*from   w ww  . j av  a2 s . co  m*/
 *
 * @throws NoSuchAlgorithmException
 */
public static SecretKeySpec generateAESKey() throws NoSuchAlgorithmException {

    SecretKeySpec skeySpec;

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey = kgen.generateKey();
    byte[] key = skey.getEncoded();

    skeySpec = new SecretKeySpec(key, "AES");

    return skeySpec;
}

From source file:org.openchain.certification.utility.PasswordUtil.java

private static String hash(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = factory
            .generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLength));
    return Base64.encodeBase64String(key.getEncoded());
}

From source file:com.joyent.manta.config.IntegrationTestConfigContext.java

private static <T> SettableConfigContext<T> enableTestEncryption(final SettableConfigContext<T> context,
        final boolean usingEncryption, final String encryptionCipher) {
    if (usingEncryption) {
        context.setClientEncryptionEnabled(true);
        context.setEncryptionKeyId("integration-test-key");
        context.setEncryptionAuthenticationMode(EncryptionAuthenticationMode.Optional);

        SupportedCipherDetails cipherDetails = SupportedCiphersLookupMap.INSTANCE.getOrDefault(encryptionCipher,
                DefaultsConfigContext.DEFAULT_CIPHER);

        context.setEncryptionAlgorithm(cipherDetails.getCipherId());
        SecretKey key = SecretKeyUtils.generate(cipherDetails);
        context.setEncryptionPrivateKeyBytes(key.getEncoded());

        System.out.printf("Unique secret key used for test (base64):\n%s\n",
                Base64.getEncoder().encodeToString(key.getEncoded()));
    }/*from  w  w  w.ja v  a2 s.  co  m*/

    return context;
}

From source file:org.apache.juddi.webconsole.AES.java

/**
 * generates an AES based off of the selected key size
 *
 * @param keysize/*from  ww w .  j  a v a  2  s . c om*/
 * @return may return null if the key is not of a supported size by the
 * current jdk
 */
public static String GEN(int keysize) {
    KeyGenerator kgen;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(keysize);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return Base64.encodeBase64String(raw);
    } catch (Exception ex) {
        log.fatal("error generating key", ex);
    }
    return null;
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *///ww  w.  j  a v  a2s  .c om
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}