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..e93b92c 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' show ECSignature; import 'package:rsa_pkcs/rsa_pkcs.dart' show RSAPKCSParser; import 'package:xml/xml.dart' hide XmlNamespace; @@ -122,6 +124,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, }; @@ -1213,6 +1216,59 @@ class RSASHA512 implements SignatureAlgorithm { } } +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 encodedSignature = + _encodeEcSignatureBase64(rawSignature, privateKey.parameters!.n); + if (callback != null) callback(null, encodedSignature); + return encodedSignature; + } + + @override + bool verifySignature(String xml, Uint8List key, String signatureValue, + [ValidateSignatureCallback? callback]) { + 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; + } + } +} + class HMACSHA1 implements SignatureAlgorithm { @override String get algorithmName => 'http://www.w3.org/2000/09/xmldsig#hmac-sha1'; @@ -1232,6 +1288,75 @@ 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 = _ecComponentLength(order); + final rawSignature = Uint8List(componentLength * 2) + ..setRange(0, componentLength, + _encodeBigIntToFixedLength(signature.r, componentLength)) + ..setRange(componentLength, componentLength * 2, + _encodeBigIntToFixedLength(signature.s, componentLength)); + 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 = _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) { + throw ArgumentError( + '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)), + _decodeBigInt(rawSignature.sublist(componentLength)), + ); +} + +/// 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([ + 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 requires ${bytes.length} bytes but only $length bytes are allowed'); + } + + return Uint8List(length)..setRange(length - bytes.length, length, bytes); +} + +/// 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; + + 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; 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