title: How to implement rsa encryption in Dart using encrypt
body: <p>I have a package written in Koltin and I want to rewrite it in Dart. I have been trying to use <a href="https://pub.dev/packages/encrypt" rel="nofollow noreferrer">encrypt</a> and <a href="https://pub.dev/packages/pointycastle" rel="nofollow noreferrer">pointycastle</a>. But I'm having problems</p>
  <p>How will I write this implementation in Dart.</p>
  <p>I have started off with try to encode the public key
  <code>var modulusBytes = base64.decode(publicKey!); </code></p>
  <pre><code>import android.util.Base64
  
  import java.security.KeyFactory
  import java.security.NoSuchAlgorithmException
  import java.security.PublicKey
  import java.security.spec.InvalidKeySpecException
  import java.security.spec.X509EncodedKeySpec
  
  import javax.crypto.Cipher
  
  
  
  object Crypto {
  
      private const val PUBLIC_KEY = &quot;MFwwDQYJKoZIhvcNAQEBBQADfafwfegRHqfkBiKGn/rrgrgrgrrgg&quot; +
              &quot;2wkeSokw2OJrCI+d6YGJPrHHx+nmb/Qn885/R01Gw6d7M824qofmCvkCAwEAAQ==&quot;
      private const val ALGORITHM = &quot;RSA&quot;
      private const val CIPHER = &quot;RSA/ECB/PKCS1Padding&quot;
  
      private fun encrypt(text: String, key: PublicKey): ByteArray? {
          var cipherText: ByteArray? = null
  
          try {
  
              // get an RSA cipher object
              val cipher = Cipher.getInstance(CIPHER)
  
              //init cipher and encrypt the plain text using the public key
              cipher.init(Cipher.ENCRYPT_MODE, key)
              cipherText = cipher.doFinal(text.toByteArray())
  
          } catch (e: Exception) {
  
              e.printStackTrace()
          }
  
          return cipherText
      }
   
      
  </code></pre>
  <p>How do I used Byte Arrays in Dart?</p>
  <h2>I have this also as part of trying to encrypt the data in Koltin.</h2>
  <pre><code>@Throws(SecurityException::class)
      fun encrypt(text: String): String {
          return String(Base64.encode(encrypt(text, getPublicKeyFromString(PUBLIC_KEY)), Base64.NO_WRAP))
      }
      
  
      @Throws(SecurityException::class)
      private fun getPublicKeyFromString(pubKey: String): PublicKey {
  
          val key: PublicKey
  
          try {
              //init keyFactory
              val kf = KeyFactory.getInstance(ALGORITHM)
  
              //decode the key into a byte array
              val keyBytes = Base64.decode(pubKey, Base64.NO_WRAP)
  
              //create spec
              val spec = X509EncodedKeySpec(keyBytes)
  
              //generate public key
              key = kf.generatePublic(spec)
          } catch (e: InvalidKeySpecException) {
              throw SecurityException(&quot;Invalid public key: &quot; + e.message)
          } catch (e: NoSuchAlgorithmException) {
              throw SecurityException(&quot;Invalid public key: &quot; + e.message)
          }
  
          return key
  
      }
  }
  </code></pre>