1 year ago

#332714

test-img

a693673

Python equivalent to java encryption

In my company, we have java class for encrypt/decrypt-ing small strings such as passwords.

Running the java code through a debugger, I can get the encrypted string, and the decrypted string. I then feed the encrypted string into my python code, and look at the decrypted string.

What I find is that the two decrypted strings do not match. The python decrypted string must equal the one produced by java.

I am a complete newbie to encryption. So, I'm hoping I can get some help. I have isolated the code below. Now, I can't change the java code, b/c I don't own it. I'm wondering what I can do to the python code to produce the same output given the inputs.

Obviously, I've changed the values for the encrypt/decrypt strings.

Thanks.

Right now, I am focused on the decrypt side. Here's the extracted java code:

import java.io.IOException;
import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;


import org.apache.commons.codec.binary.Base64;


class SecurityTool {

    private final String BYTE_MODE = "UTF-8";
    private String securityKey = "";
    private String vector = "ABCD";

    public SecurityTool(String secKeyVal) {
        securityKey = secKeyVal;
        vector = "ABCD";
    }


    public Cipher getCipherObject(String mode) {
        Cipher cipher = null;
        // This is utf-8
        String default_charset = Charset.defaultCharset().toString();
        try {
            SecretKeySpec skeySpec = null;
            GCMParameterSpec gcmParameterSpec = null;
            if (securityKey != null && vector != null) {
                skeySpec = new SecretKeySpec(securityKey.getBytes(BYTE_MODE), "AES");
                gcmParameterSpec = new GCMParameterSpec(16 * 8, vector.getBytes(BYTE_MODE));
            }
            cipher = Cipher.getInstance("AES/GCM/NoPADDING");
            if (mode.equalsIgnoreCase("ENCRYPT")) {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, gcmParameterSpec);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, gcmParameterSpec);
            }

        } catch (Exception e) {
            System.out.println("EXCEPTION: Exception while instantiating Cipher security. Error=>" + e.getMessage());
        }

        return cipher;
    }

    public String encrypt(String tobeEncrypted) {
        String retval = null;
        byte[] encrypted = null;
        try {
            Cipher cipher = getCipherObject("ENCRYPT");
            if (null != cipher) {
                encrypted = cipher.doFinal(tobeEncrypted.getBytes());
            }
            retval = Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            System.out.println("EXCEPTION: Exception while encrypting string. Error=>" + e.getMessage());
        }
        return retval;
    }

    public String decrypt(String tobeDecrypted) {
        String retval = null;
        byte[] originalText = null;
        try {
            Cipher cipher = getCipherObject("DECRYPT");
            if (null != cipher) {
                originalText = cipher.doFinal(Base64.decodeBase64(tobeDecrypted));
            }
            retval = new String(originalText);
        } catch (Exception e) {
            System.out.println("EXCEPTION: Exception while decrypting string. Error=>" + e.getMessage());
        }
        return retval;
    }
}


public class Main {

    public static void main(String[] args) {
        String encrypted_vault_auth_password = "<encrypted-password-string>";
        String expected_decrypted_text = "<decrypted-password-expected>";
        String securityKey = "<the-security-key>";
        SecurityTool security_tool = new SecurityTool(securityKey);

        String decrypted_text = security_tool.decrypt(encrypted_vault_auth_password);

        boolean bmatch = expected_decrypted_text.equals(decrypted_text);

        System.out.println("Text matches: " + bmatch);
    }
}

Now here's my python attempt at the same decryption:

from Crypto.Cipher import AES
import base64

def decrypt_attempt():
    vault_auth_password = "<encrypted-password-string>"
    sec_key_val = "<the-security-key>".encode('utf-8')
    vector = base64.b64encode("ABCD".encode('utf-8'))
    decrypt_me = base64.b64encode(vault_auth_password.encode('utf-8'))

    expected_text = "<decrypted-password-expected>"

    try:
        cipher_object = AES.new(
            sec_key_val,
            mode=AES.MODE_GCM,
            nonce=vector)

        original_text = cipher_object.decrypt(decrypt_me)
        # original_text = base64.b64decode(original_text)
        original_text = original_text.decode('utf-8')

        if original_text != expected_text:
            raise Exception(
                f"Decrypted password does not match: decrypt = {original_text}, expected = {expected_text}")
    except Exception as e:
        print(f"Exception: {e}")
        raise
    else:
        print(f"Success!")

if __name__ == '__main__':
    decrypt_attempt()

python

java

encryption

pycryptodome

javax.crypto

0 Answers

Your Answer

Accepted video resources