bcgit / pc-dart

Pointy Castle - Dart Derived Bouncy Castle APIs
MIT License
237 stars 122 forks source link

How use public key which is in string format? #101

Open oleg-ilechko opened 3 years ago

oleg-ilechko commented 3 years ago

I have this Java code which encrypts data with public key:

publicKeyBytes = Base64.decode(encodedPublicKey, Base64.URL_SAFE);
KeyFactory factoryKey = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedKey = new X509EncodedKeySpec(publicKeyBytes);
PublicKey keyPublic = factoryKey.generatePublic(encodedKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(1, keyPublic, paramSpec);
byte[] abData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.encodeToString(abData, Base64.URL_SAFE + Base64.NO_WRAP + Base64.NO_PADDING);

Is it possible to implement such thing with PointyCastle? My main issue is how should I use my public key which I receive as string to perform encryption with PointyCastle API

AKushWarrior commented 3 years ago

Yes, it's possible. You need the dart:convert library:

// at the top of your file
import 'dart:convert';

// in your method or whatever
String encryptFromKey(String encodedPublicKey) {
    var bytes = base64Url.decode(encodedPublicKey);
    // then do the encryption with your bytes... you should be able to figure out the rest.
}
oleg-ilechko commented 3 years ago

My bytes should be converted to RSAPublicKey object in some way? I see it is used in every example

oleg-ilechko commented 3 years ago

So I don't understand how to convert this lines into Dart:

KeyFactory factoryKey = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedKey = new X509EncodedKeySpec(publicKeyBytes);
PublicKey keyPublic = factoryKey.generatePublic(encodedKey);
Justinjj10 commented 2 years ago

@oleg-ilechko I am facing the same issue here. Did you get any solution? Appreciate it if you share the code here. I had tried the pointycastle code, but it won't work properly

String encrypt(String plaintext, String publicKey) {

 var pem =   '-----BEGIN RSA PUBLIC KEY-----\n$publickey\n-----END RSA PUBLIC KEY-----';
 var public = CryptoUtils.rsaPublicKeyFromPem(pem);

/// Initalizing Cipher
var cipher = PKCS1Encoding(RSAEngine());
cipher.init(true, PublicKeyParameter<RSAPublicKey>(public));

/// Converting into a [Unit8List] from List<int>
/// Then Encoding into Base64
Uint8List output =
    cipher.process(Uint8List.fromList(utf8.encode(plaintext)));
var base64EncodedText = base64Encode(output);

return base64EncodedText;
 }