Example usage for javax.crypto.spec SecretKeySpec SecretKeySpec

List of usage examples for javax.crypto.spec SecretKeySpec SecretKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec SecretKeySpec SecretKeySpec.

Prototype

public SecretKeySpec(byte[] key, String algorithm) 

Source Link

Document

Constructs a secret key from the given byte array.

Usage

From source file:net.dbjorge.jthumbor.ThumborUtils.java

/**
 * Encrypts the given plaintext with the given key according to AES-128 in ECB mode.
 *
 * This function performs NO padding on either of the key or plaintext. It REQUIRES that both
 * key and plaintext be non-null, non-empty, and have sizes which are multiples of 16.
 *///ww w  .  ja v a  2  s  .com
public static byte[] aesEncrypt(String key, String plaintext) {
    try {
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
        mAesCipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return mAesCipher.doFinal(plaintext.getBytes());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static String completeJweFromSIM(String jweSIM) {
    // android.os.Debug.waitForDebugger();

    try {/*from   ww w .j  av  a2s  . com*/
        if (jweSIM != null && jweSIM.length() > 0) {
            String parts[] = jweSIM.split("\\.");
            ;
            if (parts != null && parts.length == 5) {
                // retrieve hmac key
                byte hmac_key[] = Base64.decode(parts[4], Base64.URL_SAFE);
                if (hmac_key != null && hmac_key.length == 16) {
                    // init hash instance
                    Mac hmac = Mac.getInstance("HmacSHA256", "SC");
                    hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));

                    byte[] aad = parts[0].getBytes();
                    long al = aad.length * 8;
                    byte[] iv_key = decodeB64(parts[2]);
                    byte[] cryptedBytes = decodeB64(parts[3]);

                    // build data to hash
                    byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
                    int offset = 0;
                    System.arraycopy(aad, offset, hmacData, 0, aad.length);
                    offset += aad.length;
                    System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
                    offset += iv_key.length;
                    System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
                    offset += cryptedBytes.length;
                    ByteBuffer buffer = ByteBuffer.allocate(8);
                    buffer.putLong(al);
                    System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

                    // compute hac value
                    byte[] hmacValue = hmac.doFinal(hmacData);
                    // authentication tag
                    byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
                    String auth_tag64 = encodeB64(auth_tag);

                    // A.2.7. Complete Representation
                    String finalString = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3] + "."
                            + auth_tag64;

                    //                  // just for verification
                    //                  byte jwt64 [] = decryptJWE(finalString, RsaKeyTim.privRsaKey);
                    //                  if(jwt64!=null) {
                    //                     String jws = new String(jwt64);
                    //                     Log.d("completeJweFromSIM", "jws verify Key TIM :"+verifyJWS(jws,RsaKeyTim.pubRsaKey));
                    //                  }

                    return finalString;
                }
            }
            // 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.brienwheeler.lib.security.HmacSha256.java

public static String base64HmacSha256(String secretKey, String signData) {
    try {/*www .jav a  2  s . c  om*/
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        hmacSha256.init(secretKeySpec);
        return Base64.encodeBase64String(hmacSha256.doFinal(signData.getBytes()));
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}

From source file:edu.wright.cs.sp16.ceg3120.util.PasswordEncryptionUtility.java

/**
 * Encrypts a given string using AES.//  w  ww . ja  v  a  2s  . com
 * 
 * @param value
 *            // String to encrypt.
 * @return // Returns encrypted string.
 */
public static String encrypt(String value) {
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
        System.out.println("encrypted string: " + Base64.encodeBase64String(encrypted));

        return Base64.encodeBase64String(encrypted);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:Logi.GSeries.Libraries.Encryption.java

public static String encrypt(String decryptedString, String password) {
    try {/*  www. j  av  a  2 s  .  c  o  m*/
        // build the initialization vector (randomly).
        SecureRandom random = new SecureRandom();
        byte initialVector[] = new byte[16];
        //generate random 16 byte IV AES is always 16bytes
        random.nextBytes(initialVector);
        IvParameterSpec ivspec = new IvParameterSpec(initialVector);
        SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
        byte[] encrypted = cipher.doFinal(decryptedString.getBytes());
        byte[] encryptedWithIV = new byte[encrypted.length + initialVector.length];
        System.arraycopy(encrypted, 0, encryptedWithIV, 0, encrypted.length);
        System.arraycopy(initialVector, 0, encryptedWithIV, encrypted.length, initialVector.length);
        return Base64.encodeBase64String(encryptedWithIV);
    } catch (Exception ex) {
        Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}

From source file:encrypt.algorithms.AESCBC.java

public String encrypt(String key1, String key2, String value) {
    try {/*from  w w w  .ja  v  a2s  .  c  o m*/
        IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));

        SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        // System.out.println("encrypted string:"
        //       + Base64.encodeBase64String(encrypted));
        return Base64.encodeBase64String(encrypted);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.sshutils.utils.CryptHelper.java

public static String encrypt(String strToEncrypt) {
    try {//ww w .j  av a  2  s . co  m

        Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE, "BC");
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        final String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
        return encryptedString;
    } catch (Exception e) {
        log.error("Error while encrypting", e);
    }
    return null;

}

From source file:Main.java

public static void encrypt(String fileIn, String fileOut, byte key[])
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    // Here you read the cleartext.
    FileInputStream fis = new FileInputStream(fileIn);
    // This stream write the encrypted text. This stream will be wrapped by another stream.
    FileOutputStream fos = new FileOutputStream(fileOut);

    // Length is 32 bytes
    //byte key[] = "1010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100001111000011".getBytes("UTF-8");
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    key = sha.digest(key);/*from   w  w  w.j  a  v  a2 s.  c o m*/
    SecretKeySpec sks = new SecretKeySpec(key, "AES");
    // Create cipher
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    }
    // Flush and close streams.
    cos.flush();
    cos.close();
    fis.close();
}

From source file:fi.ilmoeuro.membertrack.util.Crypto.java

public static String hash(String candidate, String salt) {
    try {/*  ww w .j av  a 2s. c  o m*/
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec ks = new PBEKeySpec(candidate.toCharArray(), salt.getBytes(StandardCharsets.US_ASCII), 1024,
                128);
        SecretKey sk = skf.generateSecret(ks);
        Key k = new SecretKeySpec(sk.getEncoded(), "AES");
        return Hex.encodeHexString(k.getEncoded());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new RuntimeException("Error while hashing", ex);
    }
}

From source file:cr.ac.uia.SistemaGC.utils.AES.java

public static String encrypt(Long cedula, String usuario, String contrasena) {
    //<editor-fold defaultstate="collapsed" desc="Mtodo para cifrar contraseas">
    /*/*  w w w  . j a  v  a 2s. co m*/
    * Inspirado en:
    * http://stackoverflow.com/questions/15554296/simple-java-aes-encrypt-decrypt-example
     */
    try {
        IvParameterSpec iv = new IvParameterSpec(fitString(usuario, 16).getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(fitString(cedula.toString(), 16).getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(contrasena.getBytes());
        return Base64.encodeBase64String(encrypted);
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException e) {
        e.printStackTrace();
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    return null;
    //</editor-fold>
}