Search code examples
reactjsencryptionrsaencryption-asymmetricnode-forge

RSA Decryption Issue on React JS for different locale


I am working on RSA encryption and decryption for my React JS project. I am stuck on some problem on RSA decryption when I changed the language of app settings. The decryption is fine for English language, when I change to other language like Russian then there is random value which is not readable for humans. It works perfectly on mobile side and it is in live mode and tested by real users. But when I try to work on web and implement RSA then I have this problem. enter image description here

I used node-forge library for RSA encrypt - decrypt.

import forge from "node-forge"
// import JSEncrypt from "jsencrypt"
export const encrypt = (plainText, key) => {
  const publicKey = forge.pki.publicKeyFromPem(key)
  return forge.util.encode64(
    publicKey.encrypt(plainText, "RSA-OAEP", {
      md: forge.md.sha256.create(),
    })
  )
}

export const decrypt = (cipherText, key) => {
  const privateKey = forge.pki.privateKeyFromPem(key)
  return privateKey.decrypt(forge.util.decode64(cipherText), "RSA-OAEP", {
    md: forge.md.sha256.create()
  })
}

Decrypt code for the Android application (works perfectly for all languages and can decrypt to human readable text). Decrypt code : Android


Solution

  • add this line

    import forge from "node-forge"
    // import JSEncrypt from "jsencrypt"
    export const encrypt = (plainText, key) => {
      const publicKey = forge.pki.publicKeyFromPem(key)
    
      return forge.util.encode64(
        publicKey.encrypt(forge.util.encodeUtf8(plainText), "RSA-OAEP", {
          md: forge.md.sha256.create(),
        })
      )
    }
    
    export const decrypt = (cipherText, key) => {
      const privateKey = forge.pki.privateKeyFromPem(key)
    
      return forge.util.decodeUtf8(
        privateKey.decrypt(forge.util.decode64(cipherText), "RSA-OAEP", {
          md: forge.md.sha256.create(),
        })
      )
    }
    

    for more details https://github.com/digitalbazaar/forge/issues/136