PointyCastle / pointycastle

Moved into the Bouncy Castle project: https://github.com/bcgit/pc-dart
MIT License
270 stars 76 forks source link

Help with encrypting a String with an RSA cipher #123

Open wilburx9 opened 6 years ago

wilburx9 commented 6 years ago

So I have this Android library that I am trying to port to Flutter but I got stuck on the encryption part. The way it works on Android is that a base64 encoded string is used to generate a public key. Then using the generated public key and an RSA cipher, a string is encoded.

import android.util.Base64;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

 private static String ALGORITHM = "RSA";
    private static String CIPHER = "RSA/ECB/PKCS1Padding";

    private static byte[] encrypt(String text, String publicKey) {
    byte[] cipherText = null;

    try {

       // Gerating Public Key
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM);

        //decode the key into a byte array
        byte[] keyBytes = Base64.decode(publicKey, Base64.NO_WRAP);

        //create spec
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

        //generate public key
        PublicKey key = kf.generatePublic(spec);

      // Using the generated key and RSA ciper to encrypt a string
      // get an RSA cipher object
      final Cipher 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.getBytes());

    } catch (Exception e) {

      e.printStackTrace();
    }
    return cipherText;
  }

I don't understand the pointycastle APIs well enough to port the above session to Flutter. Please, I need guidance on how to do it.

stevenroose commented 6 years ago

If you use the latest version of Flutter that uses Dart v2, Pointy Castle won't work until #122 is resolved.

stevenroose commented 6 years ago

Regarding the algorithms, you would create the key generator using

KeyGenerator generator = new KeyGenerator("RSA");

and the cipher using

Cipher cipher = new Cipher("RSA/ECB/PKCS1");

However, Pointy Castle only has support for PKCS7 padding for now.

wilburx9 commented 6 years ago

Thanks. Please, how do Cipher? Please, I mean the package for the Cipher class.