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.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static boolean isValid(String plainText, String HMAC, String key) {
    try {// w w w .j a v  a  2  s .c  o m
        System.out.println("HMAC on = " + plainText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(plainText.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        String check = new String(hexBytes, "UTF-8");
        System.out.println("Checking = " + check);
        return check.equals(HMAC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static String hmacSha256(String key, String value) {
    try {/*from   w w  w  .  jav  a  2s  .c  o m*/
        //System.out.println(Base64.getEncoder().encodeToString(keyBytes));
        // Get an hmac_sha256 key from the raw key bytes
        System.out.println("First HMAC on = " + value);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");

        // Get an hmac_sha256 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.fengduo.bee.commons.security.Digests.java

/**
 * ??/*from w w w .  jav a  2 s  .  c o  m*/
 * 
 * @param algorithm 
 * @return 
 * @throws RuntimeException  {@link java.security.NoSuchAlgorithmException} ?
 */
private static byte[] getHmacKey(String algorithm) {
    // ?KeyGenerator
    KeyGenerator keyGenerator = null;
    try {
        keyGenerator = KeyGenerator.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage());
    }
    // 
    SecretKey secretKey = keyGenerator.generateKey();
    // 
    return secretKey.getEncoded();
}

From source file:org.javaweb.utils.EncryptUtils.java

/**
 * ?AES /*  w w w.  j  ava 2  s.c  om*/
 *
 * @param length
 * @return
 * @throws NoSuchAlgorithmException
 */
public static String getAESKey(int length) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(length);
    SecretKey secretKey = keyGenerator.generateKey();

    return HexUtils.bytes2HexString(secretKey.getEncoded());
}

From source file:com.ro.ssc.app.client.licensing.TrialKeyValidator.java

public static String decodeKey(String encodedEncrypted) {
    String decoded = "";
    try {/*from   w  w  w  .j a v  a  2 s  . c o m*/
        byte[] saltDecrypt = SALT_DECRYPT.getBytes(StandardCharsets.UTF_8);
        SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        SecretKey tmp2 = factoryKeyDecrypt.generateSecret(
                new PBEKeySpec(PASS_DECRYPT.toCharArray(), saltDecrypt, ITERATIONS_DECRYPT, KEY_LENGTH));
        SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), ALGORITHM);
        Cipher aesCipherDecrypt = Cipher.getInstance(CIPHER);
        aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
        byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
        byte[] eBytes = Base64.decodeBase64(e64bytes);
        byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
        decoded = StringUtils.newStringUtf8(cipherDecode);
    } catch (Exception e) {
        LOGGER.error("Error while decoding the trial key", e);
    }
    return decoded;
}

From source file:org.fejoa.library.messages.PublicCryptoEnvelope.java

static public InputStream encrypt(InputStream data, boolean isRawData, KeyId keyId, PublicKey key,
        FejoaContext context) throws JSONException, CryptoException, IOException {
    JSONObject object = new JSONObject();
    object.put(Envelope.PACK_TYPE_KEY, CRYPTO_TYPE);
    if (isRawData)
        object.put(Envelope.CONTAINS_DATA_KEY, 1);

    ICryptoInterface crypto = context.getCrypto();
    CryptoSettings.Asymmetric pubKeySettings = context.getCryptoSettings().publicKey;
    CryptoSettings.Symmetric symSettings = context.getCryptoSettings().symmetric;
    byte[] iv = crypto.generateInitializationVector(symSettings.ivSize);
    String base64IV = DatatypeConverter.printBase64Binary(iv);
    SecretKey symKey = crypto.generateSymmetricKey(symSettings);

    // encrypt the key
    byte[] encSymKey = crypto.encryptAsymmetric(symKey.getEncoded(), key, pubKeySettings);
    String base64EncSymKey = DatatypeConverter.printBase64Binary(encSymKey);

    object.put(PUBLIC_KEY_ID_KEY, keyId.getKeyId());
    object.put(PUBLIC_KEY_SETTINGS_KEY, JsonCryptoSettings.toJson(pubKeySettings));
    object.put(IV_KEY, base64IV);/*from  ww w.  j av a  2 s .  co  m*/
    object.put(ENC_SYMMETRIC_KEY_KEY, base64EncSymKey);
    object.put(SYMMETRIC_SETTINGS_KEY, JsonCryptoSettings.toJson(symSettings));
    String header = object.toString() + "\n";

    InputStream crytoStream = crypto.encryptSymmetric(data, symKey, iv, symSettings);
    return new SequenceInputStream(new ByteArrayInputStream(header.getBytes()), crytoStream);
}

From source file:org.fejoa.library.messages.PublicCryptoEnvelope.java

static public byte[] encrypt(byte[] data, boolean isRawData, KeyId keyId, PublicKey key, FejoaContext context)
        throws JSONException, CryptoException, IOException {
    JSONObject object = new JSONObject();
    object.put(Envelope.PACK_TYPE_KEY, CRYPTO_TYPE);
    if (isRawData)
        object.put(Envelope.CONTAINS_DATA_KEY, 1);

    ICryptoInterface crypto = context.getCrypto();
    CryptoSettings.Asymmetric pubKeySettings = context.getCryptoSettings().publicKey;
    CryptoSettings.Symmetric symSettings = context.getCryptoSettings().symmetric;
    byte[] iv = crypto.generateInitializationVector(symSettings.ivSize);
    String base64IV = DatatypeConverter.printBase64Binary(iv);
    SecretKey symKey = crypto.generateSymmetricKey(symSettings);

    // encrypt the key
    byte[] encSymKey = crypto.encryptAsymmetric(symKey.getEncoded(), key, pubKeySettings);
    String base64EncSymKey = DatatypeConverter.printBase64Binary(encSymKey);

    object.put(PUBLIC_KEY_ID_KEY, keyId.getKeyId());
    object.put(PUBLIC_KEY_SETTINGS_KEY, JsonCryptoSettings.toJson(pubKeySettings));
    object.put(IV_KEY, base64IV);//w ww  . ja va2 s . c o m
    object.put(ENC_SYMMETRIC_KEY_KEY, base64EncSymKey);
    object.put(SYMMETRIC_SETTINGS_KEY, JsonCryptoSettings.toJson(symSettings));
    String header = object.toString() + "\n";

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write(header.getBytes());
    OutputStream crytoStream = crypto.encryptSymmetric(outStream, symKey, iv, symSettings);
    crytoStream.write(data);
    crytoStream.flush();
    return outStream.toByteArray();
}

From source file:org.silverpeas.core.security.encryption.ContentEncryptionServiceTest.java

/**
 * Generates a key for an AES enciphering.
 * @return the key in hexadecimal./*w  ww  .  j  a v  a  2  s. c o m*/
 * @throws Exception if the key cannot be generated.
 */
public static String generateAESKey() throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(256);
    SecretKey skey = keyGenerator.generateKey();
    return EncodingUtil.asHex(skey.getEncoded());
}

From source file:org.openTwoFactor.clientExt.edu.internet2.middleware.morphString.Crypto.java

/**
 * Generate a key.//  w w  w. j a va  2s . c  om
 * @param cipherName the name of the cipher, if null will default to "AES"
 * @param keybits the number of bits in the key, if null will default to 128
 * @return the bytes comprising the key
 */
public static byte[] generateKeyBytes(String cipherName, Integer keybits) {
    KeyGenerator keyGenerator = null;
    cipherName = cipherName == null ? "AES" : cipherName;
    try {
        keyGenerator = KeyGenerator.getInstance(cipherName);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to create KeyGenerator for cipherName=" + cipherName, e);
    }
    keyGenerator.init(keybits == null ? 128 : keybits); // 192 and 256 bits may not be available

    // Generate the secret key specs.
    SecretKey secretKey = keyGenerator.generateKey();
    byte[] keyBytes = secretKey.getEncoded();

    return keyBytes;
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Creates a new {@link FileEncryptionProvider} instance that provides encryption/decryption
 * capabilities based on the specified password.
 * @param password encryption/decryption password.
 * @return a new {@link FileEncryptionProvider} instance.
 * @throws Exception if an error occurs in the execution of the operation.
 *//*from   w w  w .ja va  2s.  c o m*/
public static FileEncryptionProvider getInstance(final String password) throws Exception {
    checkArgument(StringUtils.isNotBlank(password), "Uninitialized or invalid password");
    // generate key from password
    final byte[] salt = generateSalt();
    LOGGER.trace("Generated salt: " + Hex.encodeHexString(salt));
    final SecretKey secret = generateKey(password, salt);
    LOGGER.trace("Generated key: " + Hex.encodeHexString(secret.getEncoded()));
    // create encryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encryptCipher.init(Cipher.ENCRYPT_MODE, secret);
    // initialization vector needed by the CBC mode
    final AlgorithmParameters params = encryptCipher.getParameters();
    final byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    // create decryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    decryptCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
    LOGGER.trace(String.format("Encryption/decryption ciphers were created - %s",
            encryptCipher.getProvider().getInfo()));
    return new FileEncryptionProvider(encryptCipher, decryptCipher);
}