PointyCastle / pointycastle

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

Cant construct RSA SHA-256 signer #184

Open shamblett opened 5 years ago

shamblett commented 5 years ago

When I construct an RSA SHA-256 signer,

var signer = new pointy.Signer('SHA-256/RSA');

passing a private key as the cipher params

pointy.PrivateKey privateKey = new pointy.RSAPrivateKey( rawKey.modulus, rawKey.privateExponent, rawKey.prime1, rawKey.prime2); pointy.PrivateKeyParameter privateKeyParams = new pointy.PrivateKeyParameter(privateKey);

I run into this error

type 'PrivateKeyParameter' is not a subtype of type 'AsymmetricKeyParameter' of 'params'

when calling

void init(bool forEncryption, covariant AsymmetricKeyParameter params)

in the RSAEngine class. I may be doing something wrong here but it seems that the init function won't allow the private key type. Is there a work around for this.

Radagan commented 5 years ago

@shamblett I just hit this same problem... I'm trying to connect to Google IoT using your mqtt_client. I searched around for a jwt library that worked and ended up with your fork of JustJwt without even realizing it at first. Any luck getting past the above problem?

hoylen commented 4 years ago

Since PrivateKeyParameter is a generic class, you create a correctly typed instance of it by specifying the generic type in < >:

new pointy.PrivateKeyParameter<RSAPrivateKey>(privateKey);

So the signing code is something like:

import 'package:pointycastle/pointycastle.dart' as pointy;

Uint8List signWithRSA(RSAPrivateKey privateKey, Uint8List bytesToSign) {
  final signer = pointy.Signer('SHA-256/RSA'); // with registry

  signer.init(true, PrivateKeyParameter<RSAPrivateKey>(privateKey);

  final sig = signer.generateSignature(bytesToSign);

  return sig.bytes;
}

Same with the PublicKeyParameter for verifying the signature:

  final verifier = Signer('SHA-256/RSA');

  verifier.init(false, PublicKeyParameter<RSAPublicKey>(myPublicKey));
  // forSigning=false makes it verify instead of sign and require a, RSA public key

  final verifiedOk = verifier.verifySignature(bytesThatWereSupposedlySigned, sig);