Java AES decrypt(String encryptedText, String key)

Here you can find the source of decrypt(String encryptedText, String key)

Description

decrypt

License

Apache License

Declaration

public static String decrypt(String encryptedText, String key) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import com.google.common.io.BaseEncoding;

public class Main {
    public static String decrypt(String encryptedText, String key) {
        try {//  w w w .  jav a2  s  . c  o m
            byte[] encrypted = BaseEncoding.base64Url().decode(encryptedText);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, getAesKey(key));
            byte[] plain = cipher.doFinal(encrypted);
            if (plain == null || plain.length <= 8) {
                throw new RuntimeException("wrong encrypted text.");
            }
            byte[] data = new byte[plain.length - 8];
            System.arraycopy(plain, 8, data, 0, data.length);
            return new String(data, "ISO-8859-1");
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private static SecretKeySpec getAesKey(String key) {
        final byte[] symKeyData = DatatypeConverter.parseHexBinary(key);
        return new SecretKeySpec(symKeyData, "AES");
    }
}

Related

  1. aesCrypt(byte[] content, Key key, int crypt)
  2. aesHandler(byte[] toBeHandleData, String password, boolean isEncrypt)
  3. aesKey(int keySize)
  4. aesStoreKeyToFile(Key secretKey, String path)
  5. createSessionKey()
  6. decrypt_aes(String key, String initVector, String encrypted)
  7. encryptAes(String value)
  8. encryptDecrypt(int mode, String data, String key, String salt, String iv)
  9. getAesKey(String key)