Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
* [Quire](https://quire.io) - a simple, collaborative, multi-level task management tool.
125 changes: 125 additions & 0 deletions lib/src/signed_xml.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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,
};
Expand Down Expand Up @@ -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';
Expand All @@ -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<int> 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<String> transforms;
Expand Down
5 changes: 4 additions & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ 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
test: ^1.31.0

false_secrets:
- /example/client.pem
- /test/static/client.pem
- /test/static/client.pem
- /test/static/ecdsa_private.pem
59 changes: 59 additions & 0 deletions test/ecdsa_test.dart
Original file line number Diff line number Diff line change
@@ -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 = '<library><book><name>Harry Potter</name></book></library>';
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"',
),
);
});
});
}
5 changes: 5 additions & 0 deletions test/static/ecdsa_private.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIPPibSN4pzvDrKRK2l3vhC19uI7LG3Nmy/6m9qT01vuRoAoGCCqGSM49
AwEHoUQDQgAEkn5uPRBoP/rwNB7ejf5X8vh44/i1hAqd/u0t18dAKtGOT2h14itL
9yP5y683RdvEcMyV1qCQD9yD34ScGcusZw==
-----END EC PRIVATE KEY-----
4 changes: 4 additions & 0 deletions test/static/ecdsa_public.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEkn5uPRBoP/rwNB7ejf5X8vh44/i1
hAqd/u0t18dAKtGOT2h14itL9yP5y683RdvEcMyV1qCQD9yD34ScGcusZw==
-----END PUBLIC KEY-----
1 change: 1 addition & 0 deletions test/static/ecdsa_signature.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<library><book><name>Harry Potter</name></book><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>4yiUiRBI4b7+cyg+0dWWdL8xbN5y9cuVZR2Mz6no8qA=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>KQE1gsa4/qqEF4IDdbWwVLcg2tfGS0+/k5Eom55ehL/fd4/GQQSvw3Vjjj5QzkTPHI7pIoURJkTSRR7yN4RKzQ==</ds:SignatureValue><ds:KeyInfo><ds:KeyValue><dsig11:ECKeyValue xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BJJ+bj0QaD/68DQe3o3+V/L4eOP4tYQKnf7tLdfHQCrRjk9odeIrS/cj+cuvN0XbxHDMldagkA/cg9+EnBnLrGc=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue></ds:KeyInfo></ds:Signature></library>
Loading