Example usage for javax.crypto Cipher getInstance

List of usage examples for javax.crypto Cipher getInstance

Introduction

In this page you can find the example usage for javax.crypto Cipher getInstance.

Prototype

public static final Cipher getInstance(String transformation)
        throws NoSuchAlgorithmException, NoSuchPaddingException 

Source Link

Document

Returns a Cipher object that implements the specified transformation.

Usage

From source file:Main.java

/**
 * Computes an Ephemeral ID.//w  w  w  . j  av a  2 s . co  m
 * @param key                 AES key (Advertiser Identity Key). The first 16 bytes are used.
 * @param timeCounter         Advertiser time counter
 * @param rotationExponent    Advertiser rotation exponent (0 to 15)
 * @return Final ephemeral key of 16 bytes, of which only the first 8 bytes should be used.
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@NonNull
public static byte[] computeEID(byte[] key, int timeCounter, byte rotationExponent)
        throws GeneralSecurityException {
    //        String transformation = "AES/CBC/PKCS5Padding";
    String transformation = "AES/ECB/NoPadding";
    @SuppressLint("GetInstance")
    // spec says it has to be ECB, ignore lint warning
    Cipher aes = Cipher.getInstance(transformation);
    aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, 0, 16, "AES"));

    byte[] tempKey = aes
            .doFinal(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0xff,
                    0x00, 0x00, (byte) ((timeCounter >>> 24) & 0xff), (byte) ((timeCounter >>> 16) & 0xff) });

    // clear K lowest bits
    timeCounter = timeCounter >>> rotationExponent << rotationExponent;

    // reset cipher with a new encryption key
    aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(tempKey, "AES"));
    return aes.doFinal(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            rotationExponent, (byte) ((timeCounter >>> 24) & 0xff), (byte) ((timeCounter >>> 16) & 0xff),
            (byte) ((timeCounter >>> 8) & 0xff), (byte) (timeCounter & 0xff) });
}

From source file:Main.java

public static String decryptData(String ciphertext, String password) throws Exception {
    int iterationCount = 100; //because polaroid
    int keyLength = 256;

    String[] fields = ciphertext.split("]");
    byte[] iv = Base64.decode(fields[0], 0);
    byte[] salt = Base64.decode(fields[1], 0);
    byte[] cipherBytes = Base64.decode(fields[2], 0);

    Log.d(TAG, "ciphertext: " + ciphertext + "\n" + "iv length is " + "\n" + iv.length);

    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
    byte[] plaintext = cipher.doFinal(cipherBytes);
    String plainStr = new String(plaintext, "UTF-8");

    return plainStr;
}

From source file:com.salesmanager.core.util.EncryptionUtil.java

public static String decryptFromExternal(String key, String value) throws Exception {

    if (value == null || value.equals(""))
        return "";

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] outText;
    outText = cipher.doFinal(hexToBytes(value));
    return new String(outText);

}

From source file:MainClass.java

static Cipher createCipher(int mode) throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec("test".toCharArray());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(keySpec);
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update("input".getBytes());
    byte[] digest = md.digest();
    byte[] salt = new byte[8];
    for (int i = 0; i < 8; ++i)
        salt[i] = digest[i];//w  ww .  j  ava2 s .  c  o m
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    cipher.init(mode, key, paramSpec);
    return cipher;
}

From source file:Main.java

private static String des(String id, String key) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    int index = 0;
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "DES");
    Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
    cipher.init(1, secretKeySpec);/* w  w  w  .j  av a  2 s . c  om*/
    int i = id.length();
    if (i < 8) {
        i = 8 - i;
    } else {
        i %= 8;
        i = i != 0 ? 8 - i : 0;
    }
    while (index < i) {
        id = String.valueOf(id) + "\u0000";
        index++;
    }
    return a(cipher.doFinal(id.getBytes()));
}

From source file:ec.edu.uce.medicina.seguimiento.util.EncryptionUtility.java

/**
 *Mtodo que permite la encriptacin de la contrasea.
 * @param cleartext/*from  w w w.j a  va  2 s .co m*/
 * @return
 * @throws java.lang.Exception
 */
public static String encrypt(String cleartext) throws Exception {
    String key = "02AE31B79CCCB2A3"; //llave
    String iv = "0123456789ABCDEF";
    Cipher cipher = Cipher.getInstance(cI);
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), alg);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] encrypted = cipher.doFinal(cleartext.getBytes());
    return new String(encodeBase64(encrypted));
}

From source file:clases.Seguridad.java

public static String desencriptar(String encrypted) throws Exception {
    Cipher cipher = Cipher.getInstance(CI);
    SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(), ALG);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
    byte[] enc = decodeBase64(encrypted);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decrypted = cipher.doFinal(enc);
    return new String(decrypted);
}

From source file:br.com.zeros.tipsandtricks.cryto.EncryptionStrings.java

public static String decrypt(String encryptedValue) throws Exception {
    Key key = generateKey();/*from  www  .  java 2 s  .c om*/
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = new Base64().decode(encryptedValue);
    byte[] decValue = c.doFinal(decordedValue);//////////LINE 50
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

From source file:Main.java

public static String encryptData(String password, String plaintextData) throws Exception {
    // Thank you Mr. Nelenkov
    String maybeThisHelps = "http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html";
    Log.v(TAG, maybeThisHelps);//from  w w w.j  a va  2 s .  com
    int iterationCount = 100; //because Polaroid
    int keyLength = 256;
    int saltLength = keyLength;

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[saltLength];
    random.nextBytes(salt);
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[cipher.getBlockSize()];
    random.nextBytes(iv);

    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
    byte[] ciphertext = cipher.doFinal(plaintextData.getBytes("UTF-8"));

    String ivToString = new String(Base64.encode(iv, 0));
    String saltToString = new String(Base64.encode(salt, 0));
    String ciphertextToString = new String(Base64.encode(ciphertext, 0));

    Log.d(TAG, ivToString + "]" + saltToString + "]" + ciphertextToString);
    return (ivToString + "]" + saltToString + "]" + ciphertextToString).replace("\n", "");
}

From source file:Main.java

public static byte[] encipherAes256(byte[] clearText, String keyString) throws NullPointerException {
    if (keyString == null || keyString.length() == 0) {
        throw new NullPointerException("Please give Password");
    }/*from  ww w.ja  v a 2 s.  co m*/

    if (clearText == null || clearText.length <= 0) {
        throw new NullPointerException("Please give clearText");
    }

    try {
        SecretKeySpec skeySpec = getKey(keyString);

        // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
        final byte[] iv = new byte[16];
        Arrays.fill(iv, (byte) 0x00);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // Cipher is not thread safe
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

        return cipher.doFinal(clearText);

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}