1

I'm new to Java and encryption. I'm tying to figure out how to decrypt a base64 string using a 36bit GUID string as the secret. As I understand it, I need to convert the GUID passphrase into a 256bit key in order for this to work? Could someone point me in the right direction on how to do this? I've tried some standard AES decryption code like the below but I get a javax.crypto.BadPaddingException: Given final block not properly padded error.

public static String decrypt(String strToDecrypt, String secret) 
{
    try
    {
        setKey(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)), "UTF-8");
    } 
    catch (Exception e) 
    {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}

public static void setKey(String myKey) 
{
    MessageDigest sha = null;
    try {
        key = myKey.getBytes("UTF-8");
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16); 
        secretKey = new SecretKeySpec(key, "AES");
    } 
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } 
    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

UPDATE So after more digging the string is encrypted using the crypto-js library with the default AES encryption function. This question has an example to decrypt this and a good explanation of how crypto-js encrypts with AES.

nos9
  • 601
  • 2
  • 6
  • 16
  • If you have control over the input you should not be using ECB mode & consider that a GUID is not a truly random entity at all and therefore is a poor choice for a key (Look at something like `SecretKeyFactory` instead). You probably don't want to convert the GUID to bytes using a text decoder on it characters, rather you likely need to convert it into a byte array based on the values of its hexadecimally encoded bytes. – Alex K. Oct 18 '19 at 15:41
  • 1
    Don't use GUID's for encryption keys. They don't have the security needed for an encryption key. Firstly the format of a GUID only allows for 128 bit of information .. running them through a sha1 digest, don't make it stronger (e.g. 256 bit). Secondly, they are not required to be random, and might actually be somewhat predictable .. the version 1 & 2 UUID's are particular bad as they are time based .. – Ebbe M. Pedersen Oct 18 '19 at 16:10
  • I don't have control over the passphrase as I'm getting that back from a web service. So I just need to know how to decrypt with that. Unless I'm completely misunderstanding what you are both saying. – nos9 Oct 18 '19 at 16:20
  • As keys are normally not derived from GUID's there is no standard way of doing this that we can suggest. You need to get your hands on some documentation ... – Ebbe M. Pedersen Oct 18 '19 at 17:44

0 Answers0