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, Provider provider)
        throws NoSuchAlgorithmException, NoSuchPaddingException 

Source Link

Document

Returns a Cipher object that implements the specified transformation.

Usage

From source file:com.sirius.utils.encrypt.DESEncryptor.java

@Override
public byte[] decrypt(Object key, byte[] data) throws EncryptException {
    try {//from w  w w .j a  v a2 s.  co m
        Cipher cipher = Cipher.getInstance(ALGORITHM, security_provider);
        cipher.init(Cipher.DECRYPT_MODE, getKey(key));
        return cipher.doFinal(data);
    } catch (Exception e) {
        throw new EncryptException(e);
    }
}

From source file:com.cloud.utils.crypt.RSAHelper.java

public static String encryptWithSSHPublicKey(String sshPublicKey, String content) {
    String returnString = null;//from   w ww .j av  a 2  s  . com
    try {
        RSAPublicKey publicKey = readKey(sshPublicKey);
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
        byte[] encrypted = cipher.doFinal(content.getBytes());
        returnString = Base64.encodeBase64String(encrypted);
    } catch (Exception e) {
    }

    return returnString;
}

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

public static String encrypt(String key, String toEncrypt) throws Exception {
    Key skeySpec = generateKeySpec(key);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider());
    String abc = RandomStringUtils.randomAlphanumeric(16);
    System.out.println(abc);/*from  w  w w  . j a  va 2  s.c  o m*/
    byte[] ivBytes = abc.getBytes();
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
    byte[] encryptedValue;
    encryptedValue = Base64.encodeBase64(encrypted);
    String result = new String();
    result += new String(encryptedValue);
    result = abc + result;
    System.out.println(result);
    return result;
}

From source file:com.iterzp.momo.utils.RSAUtils.java

/**
 * //from   w w  w .  j a  v  a 2s  . c  om
 * 
 * @param privateKey
 *            ?
 * @param data
 *            ?
 * @return ??
 */
public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
    Assert.notNull(privateKey);
    Assert.notNull(data);
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

static byte[] decryptJWE(String jwe, Key privRsaKey) {
    // Log.d("","decryptJWE");

    try {//from w w w  . j a  v a2s .  co  m
        // split jwe string
        StringTokenizer tokens = new StringTokenizer(jwe, ".");
        int count = tokens.countTokens();
        // Log.d("","parts.length: "+count);

        if (count != 5)
            return null;

        String jweProtectedHeader64 = tokens.nextToken();
        String jweEncrypted64 = tokens.nextToken();
        String jweInitVector64 = tokens.nextToken();
        String cryptedBytes64 = tokens.nextToken();
        String auth_tag64 = tokens.nextToken();

        // decrypt cek using private rsa key
        byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey);

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;

        int keySize = cek.length / 2;
        Log.d("", "Decryption AES: " + keySize * 8);

        // build aes_key and hmac_key
        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // decode initialization vector
        byte[] iv_key = decodeB64(jweInitVector64);

        Log.d("", "hmac_key: " + bytesToHex(hmac_key));
        Log.d("", "aes_key:  " + bytesToHex(aes_key));
        Log.d("", "iv_key:   " + bytesToHex(iv_key));

        // decrypt content using aes_key and iv_key
        byte[] cryptedBytes = decodeB64(cryptedBytes64);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");
        decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] decryptedBytes = decrypt.doFinal(cryptedBytes);

        Log.d("", "decryptedBytes:");
        Log.d("", bytesToHex(decryptedBytes));

        // validation verification
        byte[] aad = jweProtectedHeader64.getBytes();
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        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 hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // pick authentication tag
        byte[] authTag = Arrays.copyOf(hmacValue, 16);

        // validate authentication tag
        byte[] authTagRead = decodeB64(auth_tag64);
        for (int i = 0; i < 16; i++) {
            if (authTag[i] != authTagRead[i]) {
                Log.d("", "validation failed");
                return decryptedBytes;
            }
        }

        Log.d("", "validation success");

        // validation success
        return decryptedBytes;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.jk.security.JKEncDec.java

/**
 * Decrypt.//w ww .jav a 2s  .  c o m
 *
 * @param cipherText
 *            the cipher text
 * @return the string
 */
public static String decrypt(String cipherText) {
    try {
        byte[] cipherBytes = toBytes(cipherText);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
        return new String(cipher.doFinal(cipherBytes), "UTF-8").trim();
    } catch (Exception e) {
        throw new JKSecurityException(e);
    }
}

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * @param privateKey/*  w ww  . j a  va 2s.  c  o  m*/
 * @param provider
 */
public JCECrypto(PrivateKey privateKey, Provider provider) {
    this.provider = provider;
    this.privateKey = privateKey;

    // Test out the provider and key
    try {
        Cipher rsaDecryptCipher = Cipher.getInstance(RSA_CRYPTO_CIPHER, provider);
        rsaDecryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        getSha256withRSA();
        Cipher.getInstance(AES_CRYPTO_CIPHER, provider);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Provider does not provide required cipher: RSA/ECB/OAEPWithSHA1",
                e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalArgumentException("Provider does not provide required padding: MGF1", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("Invalid private key provided", e);
    }
}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

public static Cipher aesCipher()
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
    return Cipher.getInstance("AES/CCM/NoPadding", "BC");
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicenseFactory.java

@Override
public T loadLicense(String data, PrivateKey senderEncryptionKey, PublicKey senderSignatureKey)
        throws BadLicenseException, SystemStateException, OperationException {
    byte[] decodedLicense;

    decodedLicense = Base64.decodeBase64(data);

    byte[] encryptedSymKey = new byte[symkeySize];
    byte[] encryptedLicense = new byte[decodedLicense.length - symkeySize];
    byte[] decryptedSymKey;
    byte[] decryptedLicense;
    Key symkey;//from  w w  w  .j a  v  a  2 s.c  om

    System.arraycopy(decodedLicense, 0, encryptedSymKey, 0, symkeySize);
    System.arraycopy(decodedLicense, symkeySize, encryptedLicense, 0, decodedLicense.length - symkeySize);

    Cipher asymetriccipher;
    try {
        asymetriccipher = Cipher.getInstance(AbstractSerializationBasedLicense.asymmetricEncoding,
                AbstractSerializationBasedLicense.provider);
        asymetriccipher.init(Cipher.DECRYPT_MODE, senderEncryptionKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) {
        throw new SystemStateException("The specified encryption provider or algorithm was not found", ex);
    }

    try {
        decryptedSymKey = asymetriccipher.doFinal(encryptedSymKey);
        symkey = new SecretKeySpec(decryptedSymKey, "AES");
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        throw new SystemStateException("Could not decode the symkey for the license", ex);
    }

    Cipher symmetriccipher;
    try {
        symmetriccipher = Cipher.getInstance(AbstractSerializationBasedLicense.symmetricEncoding,
                AbstractSerializationBasedLicense.provider);
        symmetriccipher.init(Cipher.DECRYPT_MODE, symkey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) {
        throw new SystemStateException("The specified encryption provider or algorithm was not found", ex);
    }

    try {
        decryptedLicense = symmetriccipher.doFinal(encryptedLicense);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        throw new SystemStateException("Could not encode to base64", ex);
    }
    T license;
    try {
        license = getDeserializedObject(decryptedLicense);
    } catch (IOException | ClassNotFoundException ex) {
        throw new SystemStateException("An error occurred while reading the license from the input byte array.",
                ex);
    }
    if (license.verifyLicense(senderSignatureKey)) {
        return license;
    } else
        throw new BadLicenseException(license,
                "The license could not be verified with the specified signature decryption key");

}

From source file:Crypto.ChiffreDES.java

@Override
public String crypte(String plainTextObj) // passer un String et return des bytes
{
    Security.addProvider(new BouncyCastleProvider());
    String plainText = (String) plainTextObj;
    String textCr = null;//w  w  w  . j a v a 2  s.c om
    byte[] texteCrypte = null;
    byte[] encodedBytes = null;
    try {
        Cipher chiffrement = Cipher.getInstance("DES/ECB/PKCS5Padding", "BC");
        chiffrement.init(Cipher.ENCRYPT_MODE, this.Cle.getSecretKey());
        byte[] texteClair = plainText.getBytes();
        byte[] ciphertext = chiffrement.doFinal(texteClair);
        encodedBytes = Base64.encodeBase64(ciphertext);
        System.out.println("EncodedBytes" + new String(encodedBytes));
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    }

    return new String(encodedBytes);
}