From d107f9b8e6a703b6cd902e3a8eedb27d22fcc64e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 16:55:07 +0000 Subject: [PATCH 1/6] Initial plan From 4016134adaec13c06bef86e3d63fec8d5f849640 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 17:03:16 +0000 Subject: [PATCH 2/6] Add ECDSA-SHA256 signature support Agent-Logs-Url: https://github.com/rikulo/xml-crypto/sessions/e8be92a4-c274-47cd-b52b-d60474de8c21 Co-authored-by: scribetw <6398934+scribetw@users.noreply.github.com> --- README.md | 3 +- lib/src/signed_xml.dart | 425 ++++++++++++++++++++++++-------- pubspec.yaml | 5 +- test/ecdsa_test.dart | 59 +++++ test/static/ecdsa_private.pem | 5 + test/static/ecdsa_public.pem | 4 + test/static/ecdsa_signature.xml | 1 + 7 files changed, 403 insertions(+), 99 deletions(-) create mode 100644 test/ecdsa_test.dart create mode 100644 test/static/ecdsa_private.pem create mode 100644 test/static/ecdsa_public.pem create mode 100644 test/static/ecdsa_signature.xml diff --git a/README.md b/README.md index 1928b0d..bcd3c4f 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Install: * RSA-SHA1 http://www.w3.org/2000/09/xmldsig#rsa-sha1 * RSA-SHA256 http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 * RSA-SHA512 http://www.w3.org/2001/04/xmldsig-more#rsa-sha512 +* ECDSA-SHA256 http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256 HMAC-SHA1 is also available but it is disabled by default * HMAC-SHA1 http://www.w3.org/2000/09/xmldsig#hmac-sha1 @@ -487,4 +488,4 @@ This project is licensed under the [MIT License](https://opensource.org/licenses ## Who Uses -* [Quire](https://quire.io) - a simple, collaborative, multi-level task management tool. \ No newline at end of file +* [Quire](https://quire.io) - a simple, collaborative, multi-level task management tool. diff --git a/lib/src/signed_xml.dart b/lib/src/signed_xml.dart index 74cbe16..bb17f6a 100644 --- a/lib/src/signed_xml.dart +++ b/lib/src/signed_xml.dart @@ -6,9 +6,11 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; +import 'package:basic_utils/basic_utils.dart' show CryptoUtils; import 'package:crypto/crypto.dart'; import 'package:ninja/asymmetric/rsa/encoder/emsaPkcs1v15.dart'; import 'package:ninja/ninja.dart'; +import 'package:pointycastle/ecc/api.dart'; import 'package:rsa_pkcs/rsa_pkcs.dart' show RSAPKCSParser; import 'package:xml/xml.dart' hide XmlNamespace; @@ -17,8 +19,8 @@ import 'enveloped_signature.dart'; import 'exclusive_canonicalization.dart'; import 'utils.dart'; -typedef CalculateSignatureCallback = void Function( - Error? e, String signatureValue); +typedef CalculateSignatureCallback = + void Function(Error? e, String signatureValue); typedef ValidateSignatureCallback = void Function(Error? e, bool valid); typedef ComputeSignatureCallback = void Function(Error? e, SignedXml? instance); @@ -79,8 +81,10 @@ String _findNSPrefix(XmlNode subset) { return subset is XmlElement ? (subset.namespacePrefix ?? '') : ''; } -List _collectAncestorNamespaces(XmlNode node, - [List? nsArray]) { +List _collectAncestorNamespaces( + XmlNode node, [ + List? nsArray, +]) { nsArray ??= []; var parent = node.parent; @@ -122,6 +126,7 @@ class SignedXml { 'http://www.w3.org/2000/09/xmldsig#rsa-sha1': RSASHA1(), 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256': RSASHA256(), 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512': RSASHA512(), + 'http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256': ECDSASHA256(), // Disabled by default due to key confusion concerns. // 'http://www.w3.org/2000/09/xmldsig#hmac-sha1': HMACSHA1, }; @@ -156,7 +161,8 @@ class SignedXml { /// [idMode]. Value of "wssecurity" will create/validate id's with the ws-security namespace /// [options]. Initial configurations SignedXml([this.idMode = '', this.options = const {}]) { - signatureAlgorithm = options['signatureAlgorithm'] as String? ?? + signatureAlgorithm = + options['signatureAlgorithm'] as String? ?? 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; canonicalizationAlgorithm = options['canonicalizationAlgorithm'] as String? ?? @@ -185,7 +191,8 @@ class SignedXml { if (keyInfoProvider == null) { final err = ArgumentError( - 'cannot validate signature since no key info resolver was provided'); + 'cannot validate signature since no key info resolver was provided', + ); if (callback == null) { throw err; } else { @@ -197,7 +204,8 @@ class SignedXml { signingKey = keyInfoProvider!.getKey(keyInfo); if (signingKey == null) { final err = ArgumentError( - 'key info provider could not resolve key info $keyInfo'); + 'key info provider could not resolve key info $keyInfo', + ); if (callback == null) { throw err; } else { @@ -222,14 +230,16 @@ class SignedXml { } // unsigned, verify later to keep with consistent callback behavior - final parsedUnverifiedSignedInfo = - parseFromString(unverifiedSignedInfoCanon); + final parsedUnverifiedSignedInfo = parseFromString( + unverifiedSignedInfoCanon, + ); final unverifiedSignedInfoDoc = parsedUnverifiedSignedInfo.document; if (unverifiedSignedInfoDoc == null) { if (callback != null) { callback( ArgumentError('Could not parse signedInfoCanon into a document'), - false); + false, + ); return false; } @@ -271,7 +281,8 @@ class SignedXml { _validateSignatureValue(doc, (Error? err, bool isValidSignature) { if (err != null) { validationErrors.add( - 'invalid signature: the signature value $signatureValue is incorrect'); + 'invalid signature: the signature value $signatureValue is incorrect', + ); callback(err, false); } else { callback(null, isValidSignature); @@ -292,7 +303,8 @@ class SignedXml { } if (signedInfo.length > 1) { throw ArgumentError( - 'could not get canonicalized signed info for a signature that contains multiple SignedInfo nodes'); + 'could not get canonicalized signed info for a signature that contains multiple SignedInfo nodes', + ); } // Since in Dart the doc is always a XmlDocument @@ -312,7 +324,10 @@ class SignedXml { 'ancestorNamespaces': ancestorNamespaces, }; return _getCanonXml( - [canonicalizationAlgorithm], signedInfo.first, c14nOptions); + [canonicalizationAlgorithm], + signedInfo.first, + c14nOptions, + ); } String _getCanonReferenceXml(XmlDocument doc, _Reference ref, XmlNode node) { @@ -331,25 +346,37 @@ class SignedXml { return _getCanonXml(ref.transforms, node, c14nOptions); } - bool _validateSignatureValue(XmlDocument doc, - [ValidateSignatureCallback? callback]) { + bool _validateSignatureValue( + XmlDocument doc, [ + ValidateSignatureCallback? callback, + ]) { final signedInfoCanon = _getCanonSignedInfoXml(doc); final signer = _findSignatureAlgorithm(signatureAlgorithm); final res = signer.verifySignature( - signedInfoCanon, signingKey!, signatureValue, callback); + signedInfoCanon, + signingKey!, + signatureValue, + callback, + ); if (!res && callback == null) { validationErrors.add( - 'invalid signature: the signature value $signatureValue is incorrect'); + 'invalid signature: the signature value $signatureValue is incorrect', + ); } return res; } - void _calculateSignatureValue(XmlDocument doc, - [CalculateSignatureCallback? callback]) { + void _calculateSignatureValue( + XmlDocument doc, [ + CalculateSignatureCallback? callback, + ]) { final signedInfoCanon = _getCanonSignedInfoXml(doc); final signer = _findSignatureAlgorithm(signatureAlgorithm); - signatureValue = - signer.getSignature(signedInfoCanon, signingKey!, callback); + signatureValue = signer.getSignature( + signedInfoCanon, + signingKey!, + callback, + ); } SignatureAlgorithm _findSignatureAlgorithm(String name) { @@ -367,7 +394,8 @@ class SignedXml { return algo; } else { throw UnsupportedError( - 'canonicalization algorithm $name is not supported'); + 'canonicalization algorithm $name is not supported', + ); } } @@ -404,8 +432,9 @@ class SignedXml { if (numElementsForId > 1) { throw ArgumentError( 'Cannot validate a document which contains multiple elements with the ' - 'same value for the ID / Id / Id attributes, in order to prevent ' - 'signature wrapping attack.'); + 'same value for the ID / Id / Id attributes, in order to prevent ' + 'signature wrapping attack.', + ); } ref.xpath = elemXpath; @@ -414,7 +443,8 @@ class SignedXml { if (elem.isEmpty) { validationErrors.add( 'invalid signature: the signature references an element' - ' with uri ${ref.uri} but could not find such element in the xml'); + ' with uri ${ref.uri} but could not find such element in the xml', + ); return false; } @@ -422,9 +452,11 @@ class SignedXml { final hash = _findHashAlgorithm(ref.digestAlgorithm); final digest = hash.getHash(canonXml); if (!_validateDigestValue(digest, ref.digestValue)) { - validationErrors.add('invalid signature: for uri ${ref.uri}' + validationErrors.add( + 'invalid signature: for uri ${ref.uri}' ' calculated digest is $digest' - ' but the xml to validate supplies digest ${ref.digestValue}'); + ' but the xml to validate supplies digest ${ref.digestValue}', + ); return false; } } @@ -444,8 +476,9 @@ class SignedXml { void loadSignature(dynamic signatureNode) { if (signatureNode is String) { - _signatureNode = - signatureNode = parseFromString(signatureNode).rootElement; + _signatureNode = signatureNode = parseFromString( + signatureNode, + ).rootElement; } else { _signatureNode = signatureNode; } @@ -462,7 +495,8 @@ class SignedXml { } if (signedInfoNodes.length > 1) { throw ArgumentError( - 'could not load signature that contains multiple SignedInfo nodes'); + 'could not load signature that contains multiple SignedInfo nodes', + ); } final canonicalizationMethodNodes = findChilds( @@ -514,12 +548,12 @@ class SignedXml { "http://www.w3.org/2001/10/xml-exc-c14n#"; } - final temporaryCanonSignedInfo = _getCanonXml( - [canonicalizationAlgorithmForSignedInfo], - signedInfoNodes.first, + final temporaryCanonSignedInfo = _getCanonXml([ + canonicalizationAlgorithmForSignedInfo, + ], signedInfoNodes.first); + final temporaryCanonSignedInfoXml = parseFromString( + temporaryCanonSignedInfo, ); - final temporaryCanonSignedInfoXml = - parseFromString(temporaryCanonSignedInfo); final signedInfoDoc = temporaryCanonSignedInfoXml.rootElement; this.references.clear(); @@ -560,7 +594,8 @@ class SignedXml { final attr = findAttr(digestAlgoNode, 'Algorithm'); if (attr == null) { throw ArgumentError( - 'could not find Algorithm attribute in node $digestAlgoNode'); + 'could not find Algorithm attribute in node $digestAlgoNode', + ); } final digestAlgo = attr.value; @@ -571,7 +606,8 @@ class SignedXml { if (nodes.length > 1) { throw ArgumentError( - 'could not load reference for a node that contains multiple DigestValue nodes: $ref'); + 'could not load reference for a node that contains multiple DigestValue nodes: $ref', + ); } final digestValue = nodes.first.innerText; @@ -593,16 +629,19 @@ class SignedXml { transforms.add(findAttr(trans, 'Algorithm')?.value ?? ''); } - final inclusiveNamespaces = - findChilds(transformsAll.last, 'InclusiveNamespaces'); + final inclusiveNamespaces = findChilds( + transformsAll.last, + 'InclusiveNamespaces', + ); //Should really only be one prefix list, but maybe there's some circumstances where more than one to lets handle it for (final inclusiveNamespace in inclusiveNamespaces) { if (inclusiveNamespacesPrefixList != null) { inclusiveNamespacesPrefixList += ' ${inclusiveNamespace.getAttribute('PrefixList') ?? ''}'; } else { - inclusiveNamespacesPrefixList = - inclusiveNamespace.getAttribute('PrefixList'); + inclusiveNamespacesPrefixList = inclusiveNamespace.getAttribute( + 'PrefixList', + ); } } } @@ -628,8 +667,15 @@ class SignedXml { } final refUri = ref.getAttribute('URI'); - addReference(null, transforms, digestAlgo, refUri, digestValue, - inclusiveNamespacesPrefixList, false); + addReference( + null, + transforms, + digestAlgo, + refUri, + digestValue, + inclusiveNamespacesPrefixList, + false, + ); } void addReference( @@ -670,8 +716,11 @@ class SignedXml { /// contain a XPath expression, an `action` key which /// should contain one of the following values: /// `append`, `prepend`, `before`, `after` - void computeSignature(String xml, - {Map? opts, ComputeSignatureCallback? callback}) { + void computeSignature( + String xml, { + Map? opts, + ComputeSignatureCallback? callback, + }) { final doc = parseFromString(xml); var xmlNsAttr = 'xmlns'; final signatureAttrs = []; @@ -701,7 +750,8 @@ class SignedXml { if (!validActions.contains(location['action'])) { final err = ArgumentError( 'location.action option has an invalid action: ${location['action']},' - 'must be any of the following values: ${validActions.join(', ')}'); + 'must be any of the following values: ${validActions.join(', ')}', + ); if (callback == null) { throw err; } else { @@ -752,7 +802,8 @@ class SignedXml { final referenceNodeQuery = findNodes(doc, location['reference']!); if (referenceNodeQuery.isEmpty) { final err = ArgumentError( - 'the following xpath cannot be used because it was not found: ${location['reference']}'); + 'the following xpath cannot be used because it was not found: ${location['reference']}', + ); if (callback == null) { throw err; } else { @@ -785,8 +836,9 @@ class SignedXml { _signatureNode = signatureDoc; final signedInfoNodeQuery = findChilds(_signatureNode!, 'SignedInfo'); if (signedInfoNodeQuery.isEmpty) { - final err = - ArgumentError('could not find SignedInfo element in the message'); + final err = ArgumentError( + 'could not find SignedInfo element in the message', + ); if (callback == null) { throw err; } else { @@ -877,7 +929,9 @@ class SignedXml { } if (nodes.isEmpty) { - throw ArgumentError('the following xpath cannot be signed because it was not found: ${ref.xpath}'); + throw ArgumentError( + 'the following xpath cannot be signed because it was not found: ${ref.xpath}', + ); } } @@ -893,13 +947,15 @@ class SignedXml { for (final trans in ref.transforms) { final transform = _findCanonicalizationAlgorithm(trans); res.write( - '<${prefix}Transform Algorithm="${transform.algorithmName}"'); + '<${prefix}Transform Algorithm="${transform.algorithmName}"', + ); final prefixList = ref.inclusiveNamespacesPrefixList; if (prefixList?.isNotEmpty == true) { res ..write('>') ..write( - '') + '', + ) ..write(''); } else { res.write(' />'); @@ -911,17 +967,22 @@ class SignedXml { res ..write('') ..write( - '<${prefix}DigestMethod Algorithm="${digestAlgorithm.algorithmName}" />') + '<${prefix}DigestMethod Algorithm="${digestAlgorithm.algorithmName}" />', + ) ..write( - '<${prefix}DigestValue>${digestAlgorithm.getHash(canonXml)}') + '<${prefix}DigestValue>${digestAlgorithm.getHash(canonXml)}', + ) ..write(''); } } return res.toString(); } - String _getCanonXml(List transforms, XmlNode node, - [Map? options]) { + String _getCanonXml( + List transforms, + XmlNode node, [ + Map? options, + ]) { options = options ?? {}; if (options['defaultNsForPrefix'] == null) { options['defaultNsForPrefix'] = defaultNsForPrefix; @@ -987,19 +1048,22 @@ class SignedXml { final res = StringBuffer('<${currentPrefix}SignedInfo>') ..write( - '<${currentPrefix}CanonicalizationMethod Algorithm="${transform.algorithmName}"'); + '<${currentPrefix}CanonicalizationMethod Algorithm="${transform.algorithmName}"', + ); if (inclusiveNamespacesPrefixList.isNotEmpty) { res ..write('>') ..write( - '') + '', + ) ..write(''); } else { res.write(' />'); } res ..write( - '<${currentPrefix}SignatureMethod Algorithm="${algo.algorithmName}" />') + '<${currentPrefix}SignatureMethod Algorithm="${algo.algorithmName}" />', + ) ..write(_createReference(doc, prefix)) ..write(''); return res.toString(); @@ -1055,14 +1119,16 @@ class FileKeyInfo implements KeyInfoProvider { @override String getKeyInfo(Uint8List? signingKey, String? prefix) { var currentPrefix = prefix ?? ''; - currentPrefix = - currentPrefix.isNotEmpty ? '$currentPrefix:' : currentPrefix; + currentPrefix = currentPrefix.isNotEmpty + ? '$currentPrefix:' + : currentPrefix; final signingCert = StringBuffer(); if (signingKey != null) { final certArray = [signingKey]; for (var cert in certArray) { signingCert.write( - "<${currentPrefix}X509Certificate>${base64Encode(cert)}"); + "<${currentPrefix}X509Certificate>${base64Encode(cert)}", + ); } } return '<${currentPrefix}X509Data>${signingCert.toString()}'; @@ -1117,11 +1183,18 @@ class SHA512 implements HashAlgorithm { abstract class SignatureAlgorithm { String get algorithmName; - String getSignature(String xml, Uint8List signingKey, - [CalculateSignatureCallback? callback]); - - bool verifySignature(String xml, Uint8List key, String signatureValue, - [ValidateSignatureCallback? callback]); + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]); + + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]); } class RSASHA1 implements SignatureAlgorithm { @@ -1129,25 +1202,37 @@ class RSASHA1 implements SignatureAlgorithm { String get algorithmName => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; @override - String getSignature(String xml, Uint8List signingKey, - [CalculateSignatureCallback? callback]) { + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = - rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), hasher: EmsaHasher.sha1); + final raw = rsa.signSsaPkcs1v15ToBase64( + utf8.encode(xml), + hasher: EmsaHasher.sha1, + ); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature(String xml, Uint8List key, String signatureValue, - [ValidateSignatureCallback? callback]) { + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = - rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha1); + final res = rsa.verifySsaPkcs1v15( + signatureValue, + xml, + hasher: EmsaHasher.sha1, + ); if (callback != null) callback(null, res); return res; } @@ -1159,25 +1244,37 @@ class RSASHA256 implements SignatureAlgorithm { 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'; @override - String getSignature(String xml, Uint8List signingKey, - [CalculateSignatureCallback? callback]) { + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), - hasher: EmsaHasher.sha256); + final raw = rsa.signSsaPkcs1v15ToBase64( + utf8.encode(xml), + hasher: EmsaHasher.sha256, + ); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature(String xml, Uint8List key, String signatureValue, - [ValidateSignatureCallback? callback]) { + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = - rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha256); + final res = rsa.verifySsaPkcs1v15( + signatureValue, + xml, + hasher: EmsaHasher.sha256, + ); if (callback != null) callback(null, res); return res; } @@ -1189,25 +1286,85 @@ class RSASHA512 implements SignatureAlgorithm { 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'; @override - String getSignature(String xml, Uint8List signingKey, - [CalculateSignatureCallback? callback]) { + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), - hasher: EmsaHasher.sha512); + final raw = rsa.signSsaPkcs1v15ToBase64( + utf8.encode(xml), + hasher: EmsaHasher.sha512, + ); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature(String xml, Uint8List key, String signatureValue, - [ValidateSignatureCallback? callback]) { + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = - rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha512); + final res = rsa.verifySsaPkcs1v15( + signatureValue, + xml, + hasher: EmsaHasher.sha512, + ); + if (callback != null) callback(null, res); + return res; + } +} + +class ECDSASHA256 implements SignatureAlgorithm { + @override + String get algorithmName => + 'http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256'; + + @override + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]) { + final privateKey = CryptoUtils.ecPrivateKeyFromPem(utf8.decode(signingKey)); + final rawSignature = CryptoUtils.ecSign( + privateKey, + Uint8List.fromList(utf8.encode(xml)), + algorithmName: 'SHA-256/DET-ECDSA', + ); + final res = _encodeEcSignatureBase64( + rawSignature, + privateKey.parameters!.n, + ); + if (callback != null) callback(null, res); + return res; + } + + @override + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]) { + final publicKey = CryptoUtils.ecPublicKeyFromPem(utf8.decode(key)); + final rawSignature = _decodeEcSignatureBase64( + signatureValue, + publicKey.parameters!.n, + ); + final res = CryptoUtils.ecVerify( + publicKey, + Uint8List.fromList(utf8.encode(xml)), + rawSignature, + algorithm: 'SHA-256/ECDSA', + ); if (callback != null) callback(null, res); return res; } @@ -1218,20 +1375,87 @@ class HMACSHA1 implements SignatureAlgorithm { String get algorithmName => 'http://www.w3.org/2000/09/xmldsig#hmac-sha1'; @override - String getSignature(String xml, Uint8List signingKey, - [CalculateSignatureCallback? callback]) { + String getSignature( + String xml, + Uint8List signingKey, [ + CalculateSignatureCallback? callback, + ]) { final hmac = Hmac(sha1, signingKey); return base64Encode(hmac.convert(utf8.encode(xml)).bytes); } @override - bool verifySignature(String xml, Uint8List key, String signatureValue, - [ValidateSignatureCallback? callback]) { + bool verifySignature( + String xml, + Uint8List key, + String signatureValue, [ + ValidateSignatureCallback? callback, + ]) { final hmac = Hmac(sha1, key); return base64Encode(hmac.convert(utf8.encode(xml)).bytes) == signatureValue; } } +String _encodeEcSignatureBase64(ECSignature signature, BigInt order) { + final componentLength = (order.bitLength + 7) ~/ 8; + final rawSignature = Uint8List(componentLength * 2) + ..setRange( + 0, + componentLength, + _encodeBigIntToFixedLength(signature.r, componentLength), + ) + ..setRange( + componentLength, + componentLength * 2, + _encodeBigIntToFixedLength(signature.s, componentLength), + ); + return base64Encode(rawSignature); +} + +ECSignature _decodeEcSignatureBase64(String signatureValue, BigInt order) { + final rawSignature = base64Decode(signatureValue); + final expectedComponentLength = (order.bitLength + 7) ~/ 8; + final componentLength = rawSignature.length == expectedComponentLength * 2 + ? expectedComponentLength + : rawSignature.length ~/ 2; + if (rawSignature.length.isOdd || componentLength == 0) { + throw ArgumentError('Invalid ECDSA signature value'); + } + return ECSignature( + _decodeBigInt(rawSignature.sublist(0, componentLength)), + _decodeBigInt(rawSignature.sublist(componentLength)), + ); +} + +Uint8List _encodeBigIntToFixedLength(BigInt value, int length) { + final bytes = _encodeBigInt(value); + if (bytes.length > length) { + throw ArgumentError('Value is too large to fit in $length bytes'); + } + + return Uint8List(length)..setRange(length - bytes.length, length, bytes); +} + +Uint8List _encodeBigInt(BigInt value) { + final hex = value.toRadixString(16).padLeft(2, '0'); + final normalizedHex = hex.length.isOdd ? '0$hex' : hex; + return Uint8List.fromList([ + for (var i = 0; i < normalizedHex.length; i += 2) + int.parse(normalizedHex.substring(i, i + 2), radix: 16), + ]); +} + +BigInt _decodeBigInt(List bytes) { + if (bytes.isEmpty) { + return BigInt.zero; + } + + final hex = bytes + .map((byte) => byte.toRadixString(16).padLeft(2, '0')) + .join(); + return BigInt.parse(hex, radix: 16); +} + class _Reference { String? xpath; final List transforms; @@ -1242,6 +1466,13 @@ class _Reference { final bool isEmptyUri; List? ancestorNamespaces; - _Reference(this.xpath, this.transforms, this.digestAlgorithm, this.uri, - this.digestValue, this.inclusiveNamespacesPrefixList, this.isEmptyUri); + _Reference( + this.xpath, + this.transforms, + this.digestAlgorithm, + this.uri, + this.digestValue, + this.inclusiveNamespacesPrefixList, + this.isEmptyUri, + ); } diff --git a/pubspec.yaml b/pubspec.yaml index e3e597f..d4d80e4 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -14,6 +14,8 @@ dependencies: crypto: ^3.0.7 rsa_pkcs: ^2.1.0 ninja: ^3.0.8 + basic_utils: ^5.8.2 + pointycastle: ^4.0.0 dev_dependencies: lints: ^6.1.0 @@ -21,4 +23,5 @@ dev_dependencies: false_secrets: - /example/client.pem - - /test/static/client.pem \ No newline at end of file + - /test/static/client.pem + - /test/static/ecdsa_private.pem diff --git a/test/ecdsa_test.dart b/test/ecdsa_test.dart new file mode 100644 index 0000000..01e2c57 --- /dev/null +++ b/test/ecdsa_test.dart @@ -0,0 +1,59 @@ +import 'dart:io'; + +import 'package:test/test.dart'; +import 'package:xml_crypto/xml_crypto.dart'; +import 'package:xml_crypto/src/utils.dart'; + +void main() { + group('ECDSA tests', () { + test('validates an external ecdsa-sha256 signature', () { + final xml = File('./test/static/ecdsa_signature.xml').readAsStringSync(); + final doc = parseFromString(xml); + final signature = findFirstOrNull( + doc, + "/*/*[local-name()='Signature' and namespace-uri()='http://www.w3.org/2000/09/xmldsig#']", + ); + + final sig = SignedXml(); + sig.keyInfoProvider = FileKeyInfo('./test/static/ecdsa_public.pem'); + sig.loadSignature(signature); + + expect(sig.checkSignature(xml), isTrue); + expect( + sig.signatureAlgorithm, + 'http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256', + ); + }); + + test('creates and validates an ecdsa-sha256 signature', () { + const xml = 'Harry Potter'; + final sig = SignedXml() + ..signingKey = File('./test/static/ecdsa_private.pem').readAsBytesSync() + ..signatureAlgorithm = + 'http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256' + ..addReference("//*[local-name()='book']", [ + 'http://www.w3.org/2001/10/xml-exc-c14n#', + ], 'http://www.w3.org/2001/04/xmlenc#sha256'); + + sig.computeSignature(xml); + + final signedDoc = parseFromString(sig.signedXml); + final signature = findFirstOrNull( + signedDoc, + "/*/*[local-name()='Signature' and namespace-uri()='http://www.w3.org/2000/09/xmldsig#']", + ); + + final verify = SignedXml(); + verify.keyInfoProvider = FileKeyInfo('./test/static/ecdsa_public.pem'); + verify.loadSignature(signature); + + expect(verify.checkSignature(sig.signedXml), isTrue); + expect( + sig.signatureXml, + contains( + 'Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"', + ), + ); + }); + }); +} diff --git a/test/static/ecdsa_private.pem b/test/static/ecdsa_private.pem new file mode 100644 index 0000000..a057566 --- /dev/null +++ b/test/static/ecdsa_private.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIPPibSN4pzvDrKRK2l3vhC19uI7LG3Nmy/6m9qT01vuRoAoGCCqGSM49 +AwEHoUQDQgAEkn5uPRBoP/rwNB7ejf5X8vh44/i1hAqd/u0t18dAKtGOT2h14itL +9yP5y683RdvEcMyV1qCQD9yD34ScGcusZw== +-----END EC PRIVATE KEY----- diff --git a/test/static/ecdsa_public.pem b/test/static/ecdsa_public.pem new file mode 100644 index 0000000..5ed8ddc --- /dev/null +++ b/test/static/ecdsa_public.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEkn5uPRBoP/rwNB7ejf5X8vh44/i1 +hAqd/u0t18dAKtGOT2h14itL9yP5y683RdvEcMyV1qCQD9yD34ScGcusZw== +-----END PUBLIC KEY----- diff --git a/test/static/ecdsa_signature.xml b/test/static/ecdsa_signature.xml new file mode 100644 index 0000000..e4fccfd --- /dev/null +++ b/test/static/ecdsa_signature.xml @@ -0,0 +1 @@ +Harry Potter4yiUiRBI4b7+cyg+0dWWdL8xbN5y9cuVZR2Mz6no8qA=KQE1gsa4/qqEF4IDdbWwVLcg2tfGS0+/k5Eom55ehL/fd4/GQQSvw3Vjjj5QzkTPHI7pIoURJkTSRR7yN4RKzQ==BJJ+bj0QaD/68DQe3o3+V/L4eOP4tYQKnf7tLdfHQCrRjk9odeIrS/cj+cuvN0XbxHDMldagkA/cg9+EnBnLrGc= \ No newline at end of file From 4665fac3f2e9894b4d04ae761f8172d6f89f80e8 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 17:04:31 +0000 Subject: [PATCH 3/6] Reduce signed_xml diff scope Agent-Logs-Url: https://github.com/rikulo/xml-crypto/sessions/e8be92a4-c274-47cd-b52b-d60474de8c21 Co-authored-by: scribetw <6398934+scribetw@users.noreply.github.com> --- lib/src/signed_xml.dart | 361 ++++++++++++---------------------------- 1 file changed, 110 insertions(+), 251 deletions(-) diff --git a/lib/src/signed_xml.dart b/lib/src/signed_xml.dart index bb17f6a..fb9121b 100644 --- a/lib/src/signed_xml.dart +++ b/lib/src/signed_xml.dart @@ -19,8 +19,8 @@ import 'enveloped_signature.dart'; import 'exclusive_canonicalization.dart'; import 'utils.dart'; -typedef CalculateSignatureCallback = - void Function(Error? e, String signatureValue); +typedef CalculateSignatureCallback = void Function( + Error? e, String signatureValue); typedef ValidateSignatureCallback = void Function(Error? e, bool valid); typedef ComputeSignatureCallback = void Function(Error? e, SignedXml? instance); @@ -81,10 +81,8 @@ String _findNSPrefix(XmlNode subset) { return subset is XmlElement ? (subset.namespacePrefix ?? '') : ''; } -List _collectAncestorNamespaces( - XmlNode node, [ - List? nsArray, -]) { +List _collectAncestorNamespaces(XmlNode node, + [List? nsArray]) { nsArray ??= []; var parent = node.parent; @@ -161,8 +159,7 @@ class SignedXml { /// [idMode]. Value of "wssecurity" will create/validate id's with the ws-security namespace /// [options]. Initial configurations SignedXml([this.idMode = '', this.options = const {}]) { - signatureAlgorithm = - options['signatureAlgorithm'] as String? ?? + signatureAlgorithm = options['signatureAlgorithm'] as String? ?? 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; canonicalizationAlgorithm = options['canonicalizationAlgorithm'] as String? ?? @@ -191,8 +188,7 @@ class SignedXml { if (keyInfoProvider == null) { final err = ArgumentError( - 'cannot validate signature since no key info resolver was provided', - ); + 'cannot validate signature since no key info resolver was provided'); if (callback == null) { throw err; } else { @@ -204,8 +200,7 @@ class SignedXml { signingKey = keyInfoProvider!.getKey(keyInfo); if (signingKey == null) { final err = ArgumentError( - 'key info provider could not resolve key info $keyInfo', - ); + 'key info provider could not resolve key info $keyInfo'); if (callback == null) { throw err; } else { @@ -230,16 +225,14 @@ class SignedXml { } // unsigned, verify later to keep with consistent callback behavior - final parsedUnverifiedSignedInfo = parseFromString( - unverifiedSignedInfoCanon, - ); + final parsedUnverifiedSignedInfo = + parseFromString(unverifiedSignedInfoCanon); final unverifiedSignedInfoDoc = parsedUnverifiedSignedInfo.document; if (unverifiedSignedInfoDoc == null) { if (callback != null) { callback( ArgumentError('Could not parse signedInfoCanon into a document'), - false, - ); + false); return false; } @@ -281,8 +274,7 @@ class SignedXml { _validateSignatureValue(doc, (Error? err, bool isValidSignature) { if (err != null) { validationErrors.add( - 'invalid signature: the signature value $signatureValue is incorrect', - ); + 'invalid signature: the signature value $signatureValue is incorrect'); callback(err, false); } else { callback(null, isValidSignature); @@ -303,8 +295,7 @@ class SignedXml { } if (signedInfo.length > 1) { throw ArgumentError( - 'could not get canonicalized signed info for a signature that contains multiple SignedInfo nodes', - ); + 'could not get canonicalized signed info for a signature that contains multiple SignedInfo nodes'); } // Since in Dart the doc is always a XmlDocument @@ -324,10 +315,7 @@ class SignedXml { 'ancestorNamespaces': ancestorNamespaces, }; return _getCanonXml( - [canonicalizationAlgorithm], - signedInfo.first, - c14nOptions, - ); + [canonicalizationAlgorithm], signedInfo.first, c14nOptions); } String _getCanonReferenceXml(XmlDocument doc, _Reference ref, XmlNode node) { @@ -346,37 +334,25 @@ class SignedXml { return _getCanonXml(ref.transforms, node, c14nOptions); } - bool _validateSignatureValue( - XmlDocument doc, [ - ValidateSignatureCallback? callback, - ]) { + bool _validateSignatureValue(XmlDocument doc, + [ValidateSignatureCallback? callback]) { final signedInfoCanon = _getCanonSignedInfoXml(doc); final signer = _findSignatureAlgorithm(signatureAlgorithm); final res = signer.verifySignature( - signedInfoCanon, - signingKey!, - signatureValue, - callback, - ); + signedInfoCanon, signingKey!, signatureValue, callback); if (!res && callback == null) { validationErrors.add( - 'invalid signature: the signature value $signatureValue is incorrect', - ); + 'invalid signature: the signature value $signatureValue is incorrect'); } return res; } - void _calculateSignatureValue( - XmlDocument doc, [ - CalculateSignatureCallback? callback, - ]) { + void _calculateSignatureValue(XmlDocument doc, + [CalculateSignatureCallback? callback]) { final signedInfoCanon = _getCanonSignedInfoXml(doc); final signer = _findSignatureAlgorithm(signatureAlgorithm); - signatureValue = signer.getSignature( - signedInfoCanon, - signingKey!, - callback, - ); + signatureValue = + signer.getSignature(signedInfoCanon, signingKey!, callback); } SignatureAlgorithm _findSignatureAlgorithm(String name) { @@ -394,8 +370,7 @@ class SignedXml { return algo; } else { throw UnsupportedError( - 'canonicalization algorithm $name is not supported', - ); + 'canonicalization algorithm $name is not supported'); } } @@ -432,9 +407,8 @@ class SignedXml { if (numElementsForId > 1) { throw ArgumentError( 'Cannot validate a document which contains multiple elements with the ' - 'same value for the ID / Id / Id attributes, in order to prevent ' - 'signature wrapping attack.', - ); + 'same value for the ID / Id / Id attributes, in order to prevent ' + 'signature wrapping attack.'); } ref.xpath = elemXpath; @@ -443,8 +417,7 @@ class SignedXml { if (elem.isEmpty) { validationErrors.add( 'invalid signature: the signature references an element' - ' with uri ${ref.uri} but could not find such element in the xml', - ); + ' with uri ${ref.uri} but could not find such element in the xml'); return false; } @@ -452,11 +425,9 @@ class SignedXml { final hash = _findHashAlgorithm(ref.digestAlgorithm); final digest = hash.getHash(canonXml); if (!_validateDigestValue(digest, ref.digestValue)) { - validationErrors.add( - 'invalid signature: for uri ${ref.uri}' + validationErrors.add('invalid signature: for uri ${ref.uri}' ' calculated digest is $digest' - ' but the xml to validate supplies digest ${ref.digestValue}', - ); + ' but the xml to validate supplies digest ${ref.digestValue}'); return false; } } @@ -476,9 +447,8 @@ class SignedXml { void loadSignature(dynamic signatureNode) { if (signatureNode is String) { - _signatureNode = signatureNode = parseFromString( - signatureNode, - ).rootElement; + _signatureNode = + signatureNode = parseFromString(signatureNode).rootElement; } else { _signatureNode = signatureNode; } @@ -495,8 +465,7 @@ class SignedXml { } if (signedInfoNodes.length > 1) { throw ArgumentError( - 'could not load signature that contains multiple SignedInfo nodes', - ); + 'could not load signature that contains multiple SignedInfo nodes'); } final canonicalizationMethodNodes = findChilds( @@ -548,12 +517,12 @@ class SignedXml { "http://www.w3.org/2001/10/xml-exc-c14n#"; } - final temporaryCanonSignedInfo = _getCanonXml([ - canonicalizationAlgorithmForSignedInfo, - ], signedInfoNodes.first); - final temporaryCanonSignedInfoXml = parseFromString( - temporaryCanonSignedInfo, + final temporaryCanonSignedInfo = _getCanonXml( + [canonicalizationAlgorithmForSignedInfo], + signedInfoNodes.first, ); + final temporaryCanonSignedInfoXml = + parseFromString(temporaryCanonSignedInfo); final signedInfoDoc = temporaryCanonSignedInfoXml.rootElement; this.references.clear(); @@ -594,8 +563,7 @@ class SignedXml { final attr = findAttr(digestAlgoNode, 'Algorithm'); if (attr == null) { throw ArgumentError( - 'could not find Algorithm attribute in node $digestAlgoNode', - ); + 'could not find Algorithm attribute in node $digestAlgoNode'); } final digestAlgo = attr.value; @@ -606,8 +574,7 @@ class SignedXml { if (nodes.length > 1) { throw ArgumentError( - 'could not load reference for a node that contains multiple DigestValue nodes: $ref', - ); + 'could not load reference for a node that contains multiple DigestValue nodes: $ref'); } final digestValue = nodes.first.innerText; @@ -629,19 +596,16 @@ class SignedXml { transforms.add(findAttr(trans, 'Algorithm')?.value ?? ''); } - final inclusiveNamespaces = findChilds( - transformsAll.last, - 'InclusiveNamespaces', - ); + final inclusiveNamespaces = + findChilds(transformsAll.last, 'InclusiveNamespaces'); //Should really only be one prefix list, but maybe there's some circumstances where more than one to lets handle it for (final inclusiveNamespace in inclusiveNamespaces) { if (inclusiveNamespacesPrefixList != null) { inclusiveNamespacesPrefixList += ' ${inclusiveNamespace.getAttribute('PrefixList') ?? ''}'; } else { - inclusiveNamespacesPrefixList = inclusiveNamespace.getAttribute( - 'PrefixList', - ); + inclusiveNamespacesPrefixList = + inclusiveNamespace.getAttribute('PrefixList'); } } } @@ -667,15 +631,8 @@ class SignedXml { } final refUri = ref.getAttribute('URI'); - addReference( - null, - transforms, - digestAlgo, - refUri, - digestValue, - inclusiveNamespacesPrefixList, - false, - ); + addReference(null, transforms, digestAlgo, refUri, digestValue, + inclusiveNamespacesPrefixList, false); } void addReference( @@ -716,11 +673,8 @@ class SignedXml { /// contain a XPath expression, an `action` key which /// should contain one of the following values: /// `append`, `prepend`, `before`, `after` - void computeSignature( - String xml, { - Map? opts, - ComputeSignatureCallback? callback, - }) { + void computeSignature(String xml, + {Map? opts, ComputeSignatureCallback? callback}) { final doc = parseFromString(xml); var xmlNsAttr = 'xmlns'; final signatureAttrs = []; @@ -750,8 +704,7 @@ class SignedXml { if (!validActions.contains(location['action'])) { final err = ArgumentError( 'location.action option has an invalid action: ${location['action']},' - 'must be any of the following values: ${validActions.join(', ')}', - ); + 'must be any of the following values: ${validActions.join(', ')}'); if (callback == null) { throw err; } else { @@ -802,8 +755,7 @@ class SignedXml { final referenceNodeQuery = findNodes(doc, location['reference']!); if (referenceNodeQuery.isEmpty) { final err = ArgumentError( - 'the following xpath cannot be used because it was not found: ${location['reference']}', - ); + 'the following xpath cannot be used because it was not found: ${location['reference']}'); if (callback == null) { throw err; } else { @@ -836,9 +788,8 @@ class SignedXml { _signatureNode = signatureDoc; final signedInfoNodeQuery = findChilds(_signatureNode!, 'SignedInfo'); if (signedInfoNodeQuery.isEmpty) { - final err = ArgumentError( - 'could not find SignedInfo element in the message', - ); + final err = + ArgumentError('could not find SignedInfo element in the message'); if (callback == null) { throw err; } else { @@ -929,9 +880,7 @@ class SignedXml { } if (nodes.isEmpty) { - throw ArgumentError( - 'the following xpath cannot be signed because it was not found: ${ref.xpath}', - ); + throw ArgumentError('the following xpath cannot be signed because it was not found: ${ref.xpath}'); } } @@ -947,15 +896,13 @@ class SignedXml { for (final trans in ref.transforms) { final transform = _findCanonicalizationAlgorithm(trans); res.write( - '<${prefix}Transform Algorithm="${transform.algorithmName}"', - ); + '<${prefix}Transform Algorithm="${transform.algorithmName}"'); final prefixList = ref.inclusiveNamespacesPrefixList; if (prefixList?.isNotEmpty == true) { res ..write('>') ..write( - '', - ) + '') ..write(''); } else { res.write(' />'); @@ -967,22 +914,17 @@ class SignedXml { res ..write('') ..write( - '<${prefix}DigestMethod Algorithm="${digestAlgorithm.algorithmName}" />', - ) + '<${prefix}DigestMethod Algorithm="${digestAlgorithm.algorithmName}" />') ..write( - '<${prefix}DigestValue>${digestAlgorithm.getHash(canonXml)}', - ) + '<${prefix}DigestValue>${digestAlgorithm.getHash(canonXml)}') ..write(''); } } return res.toString(); } - String _getCanonXml( - List transforms, - XmlNode node, [ - Map? options, - ]) { + String _getCanonXml(List transforms, XmlNode node, + [Map? options]) { options = options ?? {}; if (options['defaultNsForPrefix'] == null) { options['defaultNsForPrefix'] = defaultNsForPrefix; @@ -1048,22 +990,19 @@ class SignedXml { final res = StringBuffer('<${currentPrefix}SignedInfo>') ..write( - '<${currentPrefix}CanonicalizationMethod Algorithm="${transform.algorithmName}"', - ); + '<${currentPrefix}CanonicalizationMethod Algorithm="${transform.algorithmName}"'); if (inclusiveNamespacesPrefixList.isNotEmpty) { res ..write('>') ..write( - '', - ) + '') ..write(''); } else { res.write(' />'); } res ..write( - '<${currentPrefix}SignatureMethod Algorithm="${algo.algorithmName}" />', - ) + '<${currentPrefix}SignatureMethod Algorithm="${algo.algorithmName}" />') ..write(_createReference(doc, prefix)) ..write(''); return res.toString(); @@ -1119,16 +1058,14 @@ class FileKeyInfo implements KeyInfoProvider { @override String getKeyInfo(Uint8List? signingKey, String? prefix) { var currentPrefix = prefix ?? ''; - currentPrefix = currentPrefix.isNotEmpty - ? '$currentPrefix:' - : currentPrefix; + currentPrefix = + currentPrefix.isNotEmpty ? '$currentPrefix:' : currentPrefix; final signingCert = StringBuffer(); if (signingKey != null) { final certArray = [signingKey]; for (var cert in certArray) { signingCert.write( - "<${currentPrefix}X509Certificate>${base64Encode(cert)}", - ); + "<${currentPrefix}X509Certificate>${base64Encode(cert)}"); } } return '<${currentPrefix}X509Data>${signingCert.toString()}'; @@ -1183,18 +1120,11 @@ class SHA512 implements HashAlgorithm { abstract class SignatureAlgorithm { String get algorithmName; - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]); + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]); - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]); + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]); } class RSASHA1 implements SignatureAlgorithm { @@ -1202,37 +1132,25 @@ class RSASHA1 implements SignatureAlgorithm { String get algorithmName => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; @override - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]) { + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = rsa.signSsaPkcs1v15ToBase64( - utf8.encode(xml), - hasher: EmsaHasher.sha1, - ); + final raw = + rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), hasher: EmsaHasher.sha1); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]) { + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = rsa.verifySsaPkcs1v15( - signatureValue, - xml, - hasher: EmsaHasher.sha1, - ); + final res = + rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha1); if (callback != null) callback(null, res); return res; } @@ -1244,37 +1162,25 @@ class RSASHA256 implements SignatureAlgorithm { 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'; @override - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]) { + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = rsa.signSsaPkcs1v15ToBase64( - utf8.encode(xml), - hasher: EmsaHasher.sha256, - ); + final raw = rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), + hasher: EmsaHasher.sha256); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]) { + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = rsa.verifySsaPkcs1v15( - signatureValue, - xml, - hasher: EmsaHasher.sha256, - ); + final res = + rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha256); if (callback != null) callback(null, res); return res; } @@ -1286,37 +1192,25 @@ class RSASHA512 implements SignatureAlgorithm { 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'; @override - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]) { + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]) { final rsa = RSAPrivateKey.fromPEM(utf8.decode(signingKey)); - final raw = rsa.signSsaPkcs1v15ToBase64( - utf8.encode(xml), - hasher: EmsaHasher.sha512, - ); + final raw = rsa.signSsaPkcs1v15ToBase64(utf8.encode(xml), + hasher: EmsaHasher.sha512); final res = normalizeRsaSignatureBase64(raw, rsa.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]) { + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { final parser = RSAPKCSParser(); final puk = parser.parsePEM(utf8.decode(key)).public; if (puk == null) throw ArgumentError('Invalid public key'); final rsa = RSAPublicKey(puk.modulus, BigInt.from(puk.publicExponent)); - final res = rsa.verifySsaPkcs1v15( - signatureValue, - xml, - hasher: EmsaHasher.sha512, - ); + final res = + rsa.verifySsaPkcs1v15(signatureValue, xml, hasher: EmsaHasher.sha512); if (callback != null) callback(null, res); return res; } @@ -1328,37 +1222,25 @@ class ECDSASHA256 implements SignatureAlgorithm { 'http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256'; @override - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]) { + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]) { final privateKey = CryptoUtils.ecPrivateKeyFromPem(utf8.decode(signingKey)); final rawSignature = CryptoUtils.ecSign( privateKey, Uint8List.fromList(utf8.encode(xml)), algorithmName: 'SHA-256/DET-ECDSA', ); - final res = _encodeEcSignatureBase64( - rawSignature, - privateKey.parameters!.n, - ); + final res = _encodeEcSignatureBase64(rawSignature, privateKey.parameters!.n); if (callback != null) callback(null, res); return res; } @override - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]) { + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { final publicKey = CryptoUtils.ecPublicKeyFromPem(utf8.decode(key)); - final rawSignature = _decodeEcSignatureBase64( - signatureValue, - publicKey.parameters!.n, - ); + final rawSignature = + _decodeEcSignatureBase64(signatureValue, publicKey.parameters!.n); final res = CryptoUtils.ecVerify( publicKey, Uint8List.fromList(utf8.encode(xml)), @@ -1375,22 +1257,15 @@ class HMACSHA1 implements SignatureAlgorithm { String get algorithmName => 'http://www.w3.org/2000/09/xmldsig#hmac-sha1'; @override - String getSignature( - String xml, - Uint8List signingKey, [ - CalculateSignatureCallback? callback, - ]) { + String getSignature(String xml, Uint8List signingKey, + [CalculateSignatureCallback? callback]) { final hmac = Hmac(sha1, signingKey); return base64Encode(hmac.convert(utf8.encode(xml)).bytes); } @override - bool verifySignature( - String xml, - Uint8List key, - String signatureValue, [ - ValidateSignatureCallback? callback, - ]) { + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { final hmac = Hmac(sha1, key); return base64Encode(hmac.convert(utf8.encode(xml)).bytes) == signatureValue; } @@ -1399,16 +1274,10 @@ class HMACSHA1 implements SignatureAlgorithm { String _encodeEcSignatureBase64(ECSignature signature, BigInt order) { final componentLength = (order.bitLength + 7) ~/ 8; final rawSignature = Uint8List(componentLength * 2) - ..setRange( - 0, - componentLength, - _encodeBigIntToFixedLength(signature.r, componentLength), - ) - ..setRange( - componentLength, - componentLength * 2, - _encodeBigIntToFixedLength(signature.s, componentLength), - ); + ..setRange(0, componentLength, + _encodeBigIntToFixedLength(signature.r, componentLength)) + ..setRange(componentLength, componentLength * 2, + _encodeBigIntToFixedLength(signature.s, componentLength)); return base64Encode(rawSignature); } @@ -1446,13 +1315,10 @@ Uint8List _encodeBigInt(BigInt value) { } BigInt _decodeBigInt(List bytes) { - if (bytes.isEmpty) { - return BigInt.zero; - } + if (bytes.isEmpty) return BigInt.zero; - final hex = bytes - .map((byte) => byte.toRadixString(16).padLeft(2, '0')) - .join(); + final hex = + bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); return BigInt.parse(hex, radix: 16); } @@ -1466,13 +1332,6 @@ class _Reference { final bool isEmptyUri; List? ancestorNamespaces; - _Reference( - this.xpath, - this.transforms, - this.digestAlgorithm, - this.uri, - this.digestValue, - this.inclusiveNamespacesPrefixList, - this.isEmptyUri, - ); + _Reference(this.xpath, this.transforms, this.digestAlgorithm, this.uri, + this.digestValue, this.inclusiveNamespacesPrefixList, this.isEmptyUri); } From 033088b2c8f3af3d7afccfdf28ab72b914134a5e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 17:07:13 +0000 Subject: [PATCH 4/6] Polish ECDSA helper documentation Agent-Logs-Url: https://github.com/rikulo/xml-crypto/sessions/e8be92a4-c274-47cd-b52b-d60474de8c21 Co-authored-by: scribetw <6398934+scribetw@users.noreply.github.com> --- lib/src/signed_xml.dart | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/lib/src/signed_xml.dart b/lib/src/signed_xml.dart index fb9121b..92369b6 100644 --- a/lib/src/signed_xml.dart +++ b/lib/src/signed_xml.dart @@ -1245,7 +1245,7 @@ class ECDSASHA256 implements SignatureAlgorithm { publicKey, Uint8List.fromList(utf8.encode(xml)), rawSignature, - algorithm: 'SHA-256/ECDSA', + algorithm: 'SHA-256/DET-ECDSA', ); if (callback != null) callback(null, res); return res; @@ -1271,8 +1271,10 @@ class HMACSHA1 implements SignatureAlgorithm { } } +/// Encodes an ECDSA signature into the XMLDSIG raw `r || s` format, padding +/// both components to the byte length of the curve order. String _encodeEcSignatureBase64(ECSignature signature, BigInt order) { - final componentLength = (order.bitLength + 7) ~/ 8; + final componentLength = _ecComponentLength(order); final rawSignature = Uint8List(componentLength * 2) ..setRange(0, componentLength, _encodeBigIntToFixedLength(signature.r, componentLength)) @@ -1281,14 +1283,19 @@ String _encodeEcSignatureBase64(ECSignature signature, BigInt order) { return base64Encode(rawSignature); } +/// Decodes an XMLDSIG raw `r || s` ECDSA signature. It also tolerates +/// non-standard inputs that omit leading zero octets from each component. ECSignature _decodeEcSignatureBase64(String signatureValue, BigInt order) { final rawSignature = base64Decode(signatureValue); - final expectedComponentLength = (order.bitLength + 7) ~/ 8; + final expectedComponentLength = _ecComponentLength(order); + // Some implementations omit leading zero octets from the raw r || s value. + // Accept those values by falling back to splitting the signature in half. final componentLength = rawSignature.length == expectedComponentLength * 2 ? expectedComponentLength : rawSignature.length ~/ 2; if (rawSignature.length.isOdd || componentLength == 0) { - throw ArgumentError('Invalid ECDSA signature value'); + throw ArgumentError( + 'Invalid ECDSA signature: signature must have even length with non-zero component size'); } return ECSignature( _decodeBigInt(rawSignature.sublist(0, componentLength)), @@ -1296,24 +1303,28 @@ ECSignature _decodeEcSignatureBase64(String signatureValue, BigInt order) { ); } +/// Encodes a BigInt as a fixed-length big-endian byte array with leading zero +/// padding when required by XMLDSIG. Uint8List _encodeBigIntToFixedLength(BigInt value, int length) { - final bytes = _encodeBigInt(value); + final hex = value.toRadixString(16); + final normalizedHex = hex.length.isOdd ? '0$hex' : hex; + final bytes = Uint8List.fromList([ + for (var i = 0; i < normalizedHex.length; i += 2) + int.parse(normalizedHex.substring(i, i + 2), radix: 16), + ]); if (bytes.length > length) { - throw ArgumentError('Value is too large to fit in $length bytes'); + throw ArgumentError( + 'Value requires ${bytes.length} bytes but only $length bytes are allowed'); } return Uint8List(length)..setRange(length - bytes.length, length, bytes); } -Uint8List _encodeBigInt(BigInt value) { - final hex = value.toRadixString(16).padLeft(2, '0'); - final normalizedHex = hex.length.isOdd ? '0$hex' : hex; - return Uint8List.fromList([ - for (var i = 0; i < normalizedHex.length; i += 2) - int.parse(normalizedHex.substring(i, i + 2), radix: 16), - ]); -} +/// Returns the fixed byte length of an ECDSA signature component for the given +/// curve order. +int _ecComponentLength(BigInt order) => (order.bitLength + 7) ~/ 8; +/// Decodes a big-endian byte array into a BigInt. BigInt _decodeBigInt(List bytes) { if (bytes.isEmpty) return BigInt.zero; From b1862a8ecca68571a8b8ae4c920f640b67a6b01e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 17:08:32 +0000 Subject: [PATCH 5/6] Tighten ECDSA signature helpers Agent-Logs-Url: https://github.com/rikulo/xml-crypto/sessions/e8be92a4-c274-47cd-b52b-d60474de8c21 Co-authored-by: scribetw <6398934+scribetw@users.noreply.github.com> --- lib/src/signed_xml.dart | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/lib/src/signed_xml.dart b/lib/src/signed_xml.dart index 92369b6..798a44b 100644 --- a/lib/src/signed_xml.dart +++ b/lib/src/signed_xml.dart @@ -1230,9 +1230,10 @@ class ECDSASHA256 implements SignatureAlgorithm { Uint8List.fromList(utf8.encode(xml)), algorithmName: 'SHA-256/DET-ECDSA', ); - final res = _encodeEcSignatureBase64(rawSignature, privateKey.parameters!.n); - if (callback != null) callback(null, res); - return res; + final encodedSignature = + _encodeEcSignatureBase64(rawSignature, privateKey.parameters!.n); + if (callback != null) callback(null, encodedSignature); + return encodedSignature; } @override @@ -1241,14 +1242,14 @@ class ECDSASHA256 implements SignatureAlgorithm { final publicKey = CryptoUtils.ecPublicKeyFromPem(utf8.decode(key)); final rawSignature = _decodeEcSignatureBase64(signatureValue, publicKey.parameters!.n); - final res = CryptoUtils.ecVerify( + final isValid = CryptoUtils.ecVerify( publicKey, Uint8List.fromList(utf8.encode(xml)), rawSignature, algorithm: 'SHA-256/DET-ECDSA', ); - if (callback != null) callback(null, res); - return res; + if (callback != null) callback(null, isValid); + return isValid; } } @@ -1293,9 +1294,13 @@ ECSignature _decodeEcSignatureBase64(String signatureValue, BigInt order) { final componentLength = rawSignature.length == expectedComponentLength * 2 ? expectedComponentLength : rawSignature.length ~/ 2; - if (rawSignature.length.isOdd || componentLength == 0) { + if (rawSignature.length.isOdd) { throw ArgumentError( - 'Invalid ECDSA signature: signature must have even length with non-zero component size'); + 'Invalid ECDSA signature: signature must have an even length'); + } + if (componentLength == 0) { + throw ArgumentError( + 'Invalid ECDSA signature: signature components must be non-empty'); } return ECSignature( _decodeBigInt(rawSignature.sublist(0, componentLength)), @@ -1306,6 +1311,9 @@ ECSignature _decodeEcSignatureBase64(String signatureValue, BigInt order) { /// Encodes a BigInt as a fixed-length big-endian byte array with leading zero /// padding when required by XMLDSIG. Uint8List _encodeBigIntToFixedLength(BigInt value, int length) { + if (value.isNegative) { + throw ArgumentError('ECDSA signature components must be non-negative'); + } final hex = value.toRadixString(16); final normalizedHex = hex.length.isOdd ? '0$hex' : hex; final bytes = Uint8List.fromList([ From 80070c9302328309531670065fd9a76bddc845a1 Mon Sep 17 00:00:00 2001 From: Scribe Huang Date: Sat, 9 May 2026 09:48:58 +0800 Subject: [PATCH 6/6] Apply suggestions from code review Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- lib/src/signed_xml.dart | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/lib/src/signed_xml.dart b/lib/src/signed_xml.dart index 798a44b..e93b92c 100644 --- a/lib/src/signed_xml.dart +++ b/lib/src/signed_xml.dart @@ -10,7 +10,7 @@ import 'package:basic_utils/basic_utils.dart' show CryptoUtils; import 'package:crypto/crypto.dart'; import 'package:ninja/asymmetric/rsa/encoder/emsaPkcs1v15.dart'; import 'package:ninja/ninja.dart'; -import 'package:pointycastle/ecc/api.dart'; +import 'package:pointycastle/ecc/api.dart' show ECSignature; import 'package:rsa_pkcs/rsa_pkcs.dart' show RSAPKCSParser; import 'package:xml/xml.dart' hide XmlNamespace; @@ -1239,17 +1239,33 @@ class ECDSASHA256 implements SignatureAlgorithm { @override bool verifySignature(String xml, Uint8List key, String signatureValue, [ValidateSignatureCallback? callback]) { - final publicKey = CryptoUtils.ecPublicKeyFromPem(utf8.decode(key)); - final rawSignature = - _decodeEcSignatureBase64(signatureValue, publicKey.parameters!.n); - final isValid = CryptoUtils.ecVerify( - publicKey, - Uint8List.fromList(utf8.encode(xml)), - rawSignature, - algorithm: 'SHA-256/DET-ECDSA', - ); - if (callback != null) callback(null, isValid); - return isValid; + try { + final publicKey = CryptoUtils.ecPublicKeyFromPem(utf8.decode(key)); + final rawSignature = + _decodeEcSignatureBase64(signatureValue, publicKey.parameters!.n); + final isValid = CryptoUtils.ecVerify( + publicKey, + Uint8List.fromList(utf8.encode(xml)), + rawSignature, + algorithm: 'SHA-256/DET-ECDSA', + ); + if (callback != null) callback(null, isValid); + return isValid; + } catch (e) { + if (callback != null) { + callback( + e is Error + ? e + : ArgumentError.value( + signatureValue, + 'signatureValue', + e.toString(), + ), + false, + ); + } + return false; + } } }