JsonWebKey.fromCryptoKeys constructor

JsonWebKey.fromCryptoKeys({
  1. PublicKey? publicKey,
  2. PrivateKey? privateKey,
  3. String? keyId,
})

Creates a JsonWebKey from a PublicKey and/or PrivateKey

Implementation

factory JsonWebKey.fromCryptoKeys({
  PublicKey? publicKey,
  PrivateKey? privateKey,
  String? keyId,
}) {
  if (publicKey == null && privateKey == null) {
    throw ArgumentError('Either publicKey or privateKey should be non null');
  }

  if (privateKey is RsaPrivateKey) {
    if (publicKey != null && publicKey is! RsaPublicKey) {
      throw ArgumentError.value(
          publicKey, 'publicKey', 'should be an RsaPublicKey');
    }

    return JsonWebKey.rsa(
      modulus: privateKey.modulus,
      exponent: (publicKey as RsaPublicKey?)?.exponent,
      privateExponent: privateKey.privateExponent,
      firstPrimeFactor: privateKey.firstPrimeFactor,
      secondPrimeFactor: privateKey.secondPrimeFactor,
      keyId: keyId,
    );
  }

  String toCurveName(Identifier? curve) {
    return curvesByName.entries
        .firstWhere((element) => element.value == curve)
        .key;
  }

  if (privateKey is EcPrivateKey) {
    if (publicKey != null && publicKey is! EcPublicKey) {
      throw ArgumentError.value(
          publicKey, 'publicKey', 'should be an EcPublicKey');
    }

    return JsonWebKey.ec(
      curve: toCurveName(privateKey.curve),
      privateKey: privateKey.eccPrivateKey,
      xCoordinate: (publicKey as EcPublicKey?)?.xCoordinate,
      yCoordinate: publicKey?.yCoordinate,
      keyId: keyId,
    );
  }

  if (privateKey != null) {
    throw UnsupportedError(
        'Private key of type ${privateKey.runtimeType} not supported');
  }

  if (publicKey is RsaPublicKey) {
    return JsonWebKey.rsa(
      modulus: publicKey.modulus,
      exponent: publicKey.exponent,
      keyId: keyId,
    );
  }

  if (publicKey is EcPublicKey) {
    return JsonWebKey.ec(
        curve: toCurveName(publicKey.curve),
        xCoordinate: publicKey.xCoordinate,
        yCoordinate: publicKey.yCoordinate,
        keyId: keyId);
  }

  throw UnsupportedError(
      'Public key of type ${publicKey.runtimeType} not supported');
}