How to get publicKey in RSA_encrypt key-pair generation algorithm in STRING format in flutter

Viewed 1720

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 Answers

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.

Related