Equivalent of nodejs crypto crypto.createSign in Python

Viewed 310

I want to get the same result with Python.

function generateSignature(baseString, privateKey, clientSecret) {
  var signWith = {
    key: (privateKey)
  }; // Provides private key

  if (!_.isUndefined(clientSecret) && !_.isEmpty(clientSecret)) _.set(signWith, "passphrase", clientSecret);

  // Load pem file containing the x509 cert & private key & sign the base string with it to produce the Digital Signature
  var signature = crypto.createSign('RSA-SHA256')
    .update(baseString)
    .sign(signWith, 'base64');

  return signature;
}

What I did in Python

    import base64
    from cryptography.hazmat.primitives.asymmetric import dsa, rsa
    from cryptography.hazmat.primitives.serialization import load_pem_private_key
    private_key = load_pem_private_key(
        str.encode(str_private_key),
        password=None)

    plain_text = b'abc'
    signature = private_key.sign(
        data=plain_text,
        padding=padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        algorithm=hashes.SHA256()

    )

    print(base64.b64encode(signature))

I do not know where to start. crypto documentation is quite short. How the passphrase is used in crypto ?

1 Answers

The NodeJS code uses PKCS#1 v1.5 padding, the Python code OAEPadding. To apply PKCS#1 v1.5 in Python as well, change the padding as follows:

signature = private_key.sign(
    data=plain_text,
    padding=PKCS1v15(),         # Fix: Apply PKCS#1 v1.5
    algorithm=hashes.SHA256()
)
Related