Encryption the string message with RSA OAEP React Native

Viewed 396

How can I encrypt a string message with RSA-OAEP in react native. I'm try many lib like react-native-rsa-native, react-native-rsa... but it working with RSA-PKCS1. I'm also try with this:

const str2ab = (str) => {
   const buf = new ArrayBuffer(str.length)
   const bufView = new Uint8Array(buf)

   for (let i = 0, strLen = str.length; i < strLen; i++) {
       bufView[i] = str.charCodeAt(i)
   }
   return buf
}

const importRsaKey = async(pem) => {
   const pemHeader = "-----BEGIN PUBLIC KEY-----"
   const pemFooter = "-----END PUBLIC KEY-----"

   const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length)
   // base64 decode the string to get the binary data
   const binaryDerString = window.atob(pemContents)
   // convert from a binary string to an ArrayBuffer
   const binaryDer = str2ab(binaryDerString)
   return window.crypto.subtle.importKey(
       "spki",
       binaryDer,
       {
           name: "RSA-OAEP",
           hash: "SHA-256",
       },
       true,
       ["encrypt"]
   )}

const encryptMessageByPublicKey = async (message, publicKey) => {
   let enc = new TextEncoder()
   let encoded = enc.encode(message)
       return window.crypto.subtle.encrypt(
           {
               name: "RSA-OAEP",
           },
           publicKey,
           encoded
       )
   }

const arrayBufferToBase64 = (buffer) => {
   let binary = ""
   let bytes = new Uint8Array(buffer)
   let len = bytes.byteLength

   for (let i = 0; i < len; i++) {
       binary += String.fromCharCode(bytes[i])
   }
return window.btoa(binary)
}

The Function encrypt:

const encryptRSA = async (message) => {
   let publicKeyConverted = await this.importRsaKey(my-keyRSA);
   let result = await this.encryptMessageByPublicKey(message, publicKeyConverted);
   let stringResult = this.arrayBufferToBase64(result)
   return stringResult
}

This snippet code above work on web. Not working on mobile, still work on debug mode, because the window object not working on mobile in these lines:

window.crypto.subtle.encrypt
window.crypto.subtle.importKey

Could anyone point out the mistake that I've made here or give some another suggest please?

0 Answers
Related