Example usage for javax.crypto Cipher doFinal

List of usage examples for javax.crypto Cipher doFinal

Introduction

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

Prototype

public final byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException 

Source Link

Document

Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation.

Usage

From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java

public static List<SecurityKeyData> loadUserKeys(AuthInfo userData, String challengeStoreAttribute,
        String encyrptionKeyName)
        throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    Attribute challengeAttr = userData.getAttribs().get(challengeStoreAttribute);
    Type t = new TypeToken<List<KeyHolder>>() {
    }.getType();/*from w  ww  . j  av a 2  s . com*/
    ArrayList<SecurityKeyData> devices = new ArrayList<SecurityKeyData>();

    if (challengeAttr != null) {
        SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName);
        if (key == null) {
            throw new Exception("Queue message encryption key not found");
        }

        EncryptedMessage msg = gson.fromJson(inflate(challengeAttr.getValues().get(0)), EncryptedMessage.class);
        IvParameterSpec spec = new IvParameterSpec(msg.getIv());
        Cipher cipher;

        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, spec);

        byte[] bytes = cipher.doFinal(msg.getMsg());
        String json = new String(bytes);
        java.util.List<KeyHolder> fromJSON = gson.fromJson(json, t);
        for (KeyHolder kh : fromJSON) {
            devices.add(new SecurityKeyData(kh.getEnrollmentTime(), kh.getKeyHandle(), kh.getPublicKey(), null,
                    kh.getCounter()));
        }

    }
    return devices;
}

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

public static String decodeKey(String encodedEncrypted) {
    String decoded = "";
    try {//from  ww w .j  a va2s  . 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:com.alliander.osgp.oslp.OslpUtils.java

private static boolean validateEncryptedHash(final byte[] message, final byte[] securityKey,
        final PublicKey publicKey) throws GeneralSecurityException {

    // Calculate hash of message
    final byte[] verifyHash = createHash(message);

    try {//  w w  w.  j a  v  a  2  s.c o m
        // Decrypt security key hash
        final Cipher cipher = Cipher.getInstance(FALLBACK_CIPHER);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        final byte[] messageHash = cipher.doFinal(securityKey);

        // Verify calculated and received hash
        return Arrays.equals(messageHash, verifyHash);
    } catch (final BadPaddingException e) {
        LOGGER.error("unexpected exception", e);
        return false;
    }
}

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static String rsaDecrypt(String[] string) throws Exception {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrivateKey privateKey = (PrivateKey) readKeyFromFile(Config.getProperty("escidoc.aa.private.key.file"),
            false);/*from   w  w  w .j a  va2s  .  co m*/
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    for (String part : string) {
        byte[] inArr = Base64.decodeBase64(part.getBytes("UTF-8"));
        baos.write(cipher.doFinal(inArr));
        baos.flush();
    }

    return new String(baos.toByteArray(), "UTF-8");

}

From source file:Componentes.EncryptionMD5.java

public static String Desencriptar(String encriptado) {
    System.out.println(encriptado);
    String secretKey = "qualityinfosolutions"; //llave para encriptar datos
    String base64EncryptedString = "";

    try {/*  ww w  . j a  va 2 s.  c o m*/
        System.out.println("h");
        byte[] message = Base64.decodeBase64(encriptado.getBytes("utf-8"));
        System.out.println("b");
        MessageDigest md = MessageDigest.getInstance("MD5");
        System.out.println("a");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        System.out.println("c");
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        System.out.println("g");
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        System.out.println("w");
        Cipher decipher = Cipher.getInstance("DESede");
        System.out.println("t");
        decipher.init(Cipher.DECRYPT_MODE, key);
        System.out.println("r");
        System.out.println(Arrays.toString(message));
        byte[] plainText = decipher.doFinal(message);
        System.out.println(Arrays.toString(plainText));
        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return base64EncryptedString;
}

From source file:com.wso2telco.cryptosystem.AESencrp.java

/**
 * Decrypt./*from ww w . java  2 s.c  om*/
 *
 * @param encryptedData the encrypted data
 * @return the string
 * @throws Exception the exception
 */
public static String decrypt(String encryptedData) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    //byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
    byte[] decordedValue = Base64.decodeBase64(encryptedData.getBytes());
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

From source file:com.cherong.mock.common.base.util.EncryptionUtil.java

/**
 * deskey/*  w w  w .ja v  a2 s  .  c  o m*/
 * 
 * @param content
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByDES(String content, String key) {
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey sk = skf.generateSecret(dks);
        Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM);
        cip.init(Cipher.ENCRYPT_MODE, sk);
        return cip.doFinal(content.getBytes());
    } catch (Exception e) {
        LOGGER.error("{}", e);
        return null;
    }

}

From source file:hudson.util.Secret.java

static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
    try {//w  w w  . j a  va2 s . c o m
        String plainText = new String(cipher.doFinal(in), "UTF-8");
        if (plainText.endsWith(MAGIC))
            return new Secret(plainText.substring(0, plainText.length() - MAGIC.length()));
        return null;
    } catch (GeneralSecurityException e) {
        return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
    }
}

From source file:Main.java

/**
 * More flexible AES encrypt that doesn't encode
 *
 * @param key     AES key typically 128, 192 or 256 bit
 * @param iv      Initiation Vector// w  w w .j  a  va 2  s . c o m
 * @param message in bytes (assumed it's already been decoded)
 * @return Encrypted cipher text (not encoded)
 * @throws GeneralSecurityException if something goes wrong during encryption
 */
public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
        throws GeneralSecurityException {
    final Cipher cipher = Cipher.getInstance(AES_MODE);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    //        cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(message);

    log("cipherText", cipherText);

    return cipherText;
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * //from w ww  .  j a  v  a  2s .  c  o  m
 * This method is used for encrypt by using Algorithm - AES
 * 
 * @param String
 * @return String
 * @throws Exception
 */
public static String encryptAES(String data) throws Exception {

    Key key = generateKeyAES(); // step 1

    Cipher c = Cipher.getInstance(AES_ALGO); // step 2
    c.init(Cipher.ENCRYPT_MODE, key); // step 3

    byte[] encVal = c.doFinal(data.getBytes()); // step 4
    String encryptedValue = new BASE64Encoder().encode(encVal); // step 5

    return encryptedValue;
}