appsup-dart / jose

Javascript Object Signing and Encryption (JOSE) library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JsonWebKey.fromJson : How to convert PEM to JWK format?

Yowims opened this issue · comments

Hi,

I generated my own private/public key pair, and I wanna use it to encrypt data. But the only existing method is JsonWebKey.fromJson(), which accepts only JWK format and actually my key pair is in PEM format.
I don't want to use a third-part solution on Internet to convert it, so Is there an included method to convert my key?

Okay @rbellens I found you example using RS512 and that's kinda the method I wanted to use. But in this example you're using a method called "parsePem". Can you detail this method please?

JsonWebKey _readPrivateKeyFromFile(String path) {
  var v = parsePem(File(path).readAsStringSync()).first;
  var keyPair = (v is PrivateKeyInfo) ? v.keyPair : v as KeyPair;
  var pKey = keyPair.privateKey as RsaPrivateKey;
  print(pKey);

  String _bytesToBase64(List<int> bytes) {
    return base64Url.encode(bytes).replaceAll('=', '');
  }

  String _intToBase64(BigInt v) {
    return _bytesToBase64(v
        .toRadixString(16)
        .replaceAllMapped(RegExp('[0-9a-f]{2}'), (m) => '${m.group(0)},')
        .split(',')
        .where((v) => v.isNotEmpty)
        .map((v) => int.parse(v, radix: 16))
        .toList());
  }

 return JsonWebKey.fromJson({
    'kty': 'RSA',
    'n': _intToBase64(pKey.modulus),
    'd': _intToBase64(pKey.privateExponent),
    'p': _intToBase64(pKey.firstPrimeFactor),
    'q': _intToBase64(pKey.secondPrimeFactor),
    'alg': 'RS512',
    'kid': 'some_id'
  });
}

Okay "parsePem" is a method from x509 package. I'll try to use this code sample, and see if it's working.