1

I am currently working on encryption in my flutter app wherein I am using RSA key-pair generator to get public and private key using the following code-

import 'package:rsa_encrypt/rsa_encrypt.dart';
import 'package:pointycastle/api.dart' as crypto;

//Future to hold our KeyPair
Future<crypto.AsymmetricKeyPair> futureKeyPair;

//to store the KeyPair once we get data from our future
crypto.AsymmetricKeyPair keyPair;

Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair()
{
var helper = RsaKeyHelper();
return helper.computeRSAKeyPair(helper.getSecureRandom());
}

Now I want to get the keyPair.publicKey in string format but if i print keyPair.publicKey, it shows "Instance of RSA publicKey" . How can I get it in string format??

1 Answer 1

2

It is always best to use standardized formats when saving public keys. For RSA public keys you can store them in layers, much like a Matroesjka doll.

  1. Encode the public key in the ASN.1 / DER format specified in the PKCS#1 RSA standard;
  2. Encode that public key in a format called SubjectPublicKeyInfo which is part of the X.509 specifications - it indicates that this is indeed an RSA key;
  3. Apply so called PEM "ASCII armor", which consists of a header & footer line indicating the generic SubjectPublicKeyFormat (just PUBLIC KEY), with a multi-line base 64 encoding of the public key from step 2 in between.

Sounds like a lot of work, but if you look here you'll find handy methods called encodePublicKeyToPem and parsePublicKeyFromPem that do these 3 steps for you (it actually does both 1 and 2 in the same function, which is a bit of a shame but not that important).

These keys are rather portable and are also usable by e.g. OpenSSL or PGP.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for the answer! I found similar implementations for "encodePrivateKeyToPemPKCS1' mentioned in the docs https://pub.dev/packages/rsa_encrypt as the GitHub link of methods that you had sent in https://www.programmersought.com/article/18664973041/. That GitHub link of methods can also be used for reversing the instace->string :) conversion.
everyone refers to this gist but it's broken...
@AlbertoM Thanks for notifying me, but please explain why you think it is broken so we can investigate!
RsaKeyHelper().generateKeyPair(); throws Unhandled exception: type 'AsymmetricKeyPair<PublicKey, PrivateKey>' is not a subtype of type 'AsymmetricKeyPair<RSAPublicKey, RSAPrivateKey>'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.