checkX509Signature static method

bool checkX509Signature(
  1. String pem, {
  2. String? parent,
})

Checks the signature of the given pem by using the public key from the given parent. If the parent parameter is null, the public key of the given pem will be used.

Both parameters pem and parent should represent a X509Certificate in PEM format.

Implementation

static bool checkX509Signature(String pem, {String? parent}) {
  var result = false;
  parent ??= pem;
  var data = x509CertificateFromPem(pem);
  var parentData = x509CertificateFromPem(parent);
  var algorithm = _getDigestFromOi(data.signatureAlgorithmReadableName ?? '');

  // Check if key and algorithm matches
  if (data.signatureAlgorithmReadableName!.toLowerCase().contains('rsa') &&
      parentData.tbsCertificate!.subjectPublicKeyInfo.algorithmReadableName!
          .contains('ecPublicKey')) {
    // Algorithm does not match
    return false;
  }
  if (data.signatureAlgorithmReadableName!.toLowerCase().contains('ec') &&
      parentData.tbsCertificate!.subjectPublicKeyInfo.algorithmReadableName!
          .contains('rsaEncryption')) {
    // Algorithm does not match
    return false;
  }

  if (data.signatureAlgorithmReadableName!.toLowerCase().contains('rsa')) {
    var publicKey = CryptoUtils.rsaPublicKeyFromDERBytes(_stringAsBytes(
        parentData.tbsCertificate!.subjectPublicKeyInfo.bytes!));
    result = CryptoUtils.rsaVerify(
      publicKey,
      base64.decode(data.tbsCertificateSeqAsString!),
      _stringAsBytes(data.signature!),
      algorithm: '$algorithm/RSA',
    );
  } else {
    var publicKey = CryptoUtils.ecPublicKeyFromDerBytes(_stringAsBytes(
        parentData.tbsCertificate!.subjectPublicKeyInfo.bytes!));
    var sigBytes = _stringAsBytes(data.signature!);
    if (sigBytes.first == 0) {
      sigBytes = sigBytes.sublist(1);
    }
    result = CryptoUtils.ecVerify(
      publicKey,
      base64.decode(data.tbsCertificateSeqAsString!),
      CryptoUtils.ecSignatureFromDerBytes(
        sigBytes,
      ),
      algorithm: '$algorithm/ECDSA',
    );
  }
  return result;
}