No inverse error during encryption (node-rsa)

243 Views Asked by At

I am trying to convert https://clover.app.box.com/s/rz18bni3bpmdrc8wc92xm4w8h9grrtty from Java to node.js

I am using the node-rsa package and getting error:0306E06C:bignum routines:BN_mod_inverse:no inverse when trying to encrypt using an imported public key.

According to the clover example, I want to

  • Parse the Base64 public key string (returned by the CDN). Obtain the modulus and exponent.
  • Generate an RSA public key using the modulus and exponent values.
  • Prepend the prefix value to the card number.
  • Using the public key, encrypt the combined prefix and card number.
  • Base64 encode the resulting encrypted data into a string.

I was able to get the modulus and exponent, and it matches the result in Java:

modulus: 24130287975021244042702223805688721202041521798556826651085672609155097623636349771918006235309701436638877260677191655500886975872679820355397440672922966114867081224266610192869324297514124544273216940817802300465149818663693299511097403105193694390420041695022375597863889602539348837984499566822859405785094021038882988619692110445776031330831112388738257159574572412058904373392173474311363017975036752132291687352767767085957596076340458420658040735725435536120045045686926201660857778184633632435163609220055250478625974096455522280609375267155256216043291335838965519403970406995613301546002859220118001163241

exponent: 415029

Now I want to create a public key with it, and encrypt a message:

    const key = new NodeRSA();

    // generate RSA public key using mod and exp values
    key.importKey({
        n: Buffer.from('24130287975021244042702223805688721202041521798556826651085672609155097623636349771918006235309701436638877260677191655500886975872679820355397440672922966114867081224266610192869324297514124544273216940817802300465149818663693299511097403105193694390420041695022375597863889602539348837984499566822859405785094021038882988619692110445776031330831112388738257159574572412058904373392173474311363017975036752132291687352767767085957596076340458420658040735725435536120045045686926201660857778184633632435163609220055250478625974096455522280609375267155256216043291335838965519403970406995613301546002859220118001163241', 'hex'),
        e: Buffer.from('415029', 'hex')
    }, 'components-public');
    
    // using public key, encrypt message
    // base64 encode encrypted data to string
    const encryptedString = key.encrypt(Buffer.from('message', 'hex'), 'base64', 'hex'); 

However, I am getting the no inverse error mentioned above. It seems to be caused by the modulus. If I change it to something shorter, the error goes away.

0

There are 0 best solutions below