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.openmrs.module.reportingsummary.api.io.download.DownloadProcessor.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception// w w w  . j a v  a  2 s .  com
 */
private Cipher initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(InputOutputConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey secretKey = factory.generateSecret(spec);

    SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), InputOutputConstants.KEY_SPEC);

    if (log.isDebugEnabled())
        log.debug("Encrypting with: " + secret.getAlgorithm());

    Cipher cipher = Cipher.getInstance(InputOutputConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    return cipher;
}

From source file:adminpassword.AESDemo.java

public String encrypt(String plainText) throws Exception {

    //get salt//from  w  w w . j  av  a 2 s  . co  m
    salt = generateSalt();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:enc_mods.aes.java

public void setKey() {
    try {//from   w  w  w.j ava 2s  .  c om
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(AES_Key_Size);
        SecretKey aeskey = kgen.generateKey();
        key = aeskey.getEncoded();
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.thewaffleshop.nimbus.api.EncryptionAPI.java

/**
 * Serialize a secret key//from   w  ww  .  j  av  a  2s  .  co  m
 *
 * @param sk
 * @return
 */
public byte[] serializeSecretKey(SecretKey sk) {
    return sk.getEncoded();
}

From source file:adminpassword.AESDemo.java

@SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {

    byte[] saltBytes = salt.getBytes("UTF-8");
    byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // Decrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {/*from   w ww . j  a v  a  2 s.c o m*/
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static String getEncryptedKey(final String certArn, final String certPem) throws AuthException {
    final ServerCertificate targetCert = lookupServerCertificate(certArn);
    // generate symmetric key
    final MessageDigest digest = Digest.SHA256.get();
    final byte[] salt = new byte[32];
    Crypto.getSecureRandomSupplier().get().nextBytes(salt);
    digest.update(salt);/*from   w  w w  .j a  v a2 s .c  om*/
    final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES");

    try {
        // encrypt the server pk using symm key
        Cipher cipher = Ciphers.AES_CBC.get();
        final byte[] iv = new byte[16];
        Crypto.getSecureRandomSupplier().get().nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv),
                Crypto.getSecureRandomSupplier().get());
        final byte[] cipherText = cipher.doFinal(Base64.encode(targetCert.getPrivateKey().getBytes()));
        final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText)));

        // encrypt the symmetric key using the certPem
        X509Certificate x509Cert = PEMFiles.getCert(B64.standard.dec(certPem));
        cipher = Ciphers.RSA_PKCS1.get();
        cipher.init(Cipher.ENCRYPT_MODE, x509Cert.getPublicKey(), Crypto.getSecureRandomSupplier().get());
        byte[] symmkey = cipher.doFinal(symmKey.getEncoded());
        final String b64SymKey = new String(Base64.encode(symmkey));

        return String.format("%s\n%s", b64SymKey, encPrivKey);
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:org.apache.nifi.processors.standard.util.crypto.AESKeyedCipherProvider.java

private boolean isValidKeyLength(SecretKey key) {
    return VALID_KEY_LENGTHS.contains(key.getEncoded().length * 8);
}

From source file:spacetraffic.kiv.zcu.cz.gameelement.MinigamePasswordHasher.java

/**
 * Method for generating key./*from  w w  w  .  j av  a 2s .com*/
 * @return key
 * @throws Exception
 */
private Key generateKey() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    char[] pdkbf2Password = PDKBF2_PASSWORD.toCharArray();
    byte[] salt = SALT.getBytes(CHARSET);

    KeySpec keySpec = new PBEKeySpec(pdkbf2Password, salt, 65536, 128);
    SecretKey secretKey = factory.generateSecret(keySpec);
    byte[] encodedKey = secretKey.getEncoded();

    return new SecretKeySpec(encodedKey, "AES");
}

From source file:org.matrix.security.crypto.encrypt.AesBytesEncryptor.java

public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator) {
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256);
    SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec);
    this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
    encryptor = newCipher(AES_ALGORITHM);
    decryptor = newCipher(AES_ALGORITHM);
    this.ivGenerator = ivGenerator != null ? ivGenerator : NULL_IV_GENERATOR;
}

From source file:Util.PassGen.java

private String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0) {
        throw new IllegalArgumentException("Empty passwords are not supported.");
    }//from  ww  w.  j  av  a  2 s  .c o m
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}