google / webcrypto.dart

Cross-platform implementation of Web Cryptography APIs
https://pub.dev/packages/webcrypto
Apache License 2.0
71 stars 43 forks source link

EcdsaPrivateKey.importRawKey unavailable #99

Closed rohintoncollins closed 3 months ago

rohintoncollins commented 3 months ago

EcdsaPublicKey.importRawKey is available, and we can import the raw public key (65 bytes) and verify a signature. However, I am securely storing a private key as 32 bytes, and I would like to be able to create an EcdsaPrivateKey which I can then use for signing. Is this at all possible, or is this a feature request? It can be done on other libraries, e.g. CryptoKit, PointyCastle, but I so far prefer using the web crypto package, and I am having other issues with pointycastle and cryptography packages.

rohintoncollins commented 3 months ago

I came up with a solution to this by using the elliptic package in conjunction with the web crypto package. I used the elliptic package to create a PrivateKey using the 32 bytes of the private key ('d'). I then generated the PublicKey from the PrivateKey and converted both keys to PKCS#8 format. I was then able to use the PKCS#8 constructor in web crypto to create an EcdsaPrivateKey which I could then use for ECDSA (sign). I hard-coded the PKCS#8 format, as I am only using a single curve (NIST P256 / secp256r1 / prime256v1). Here is my code in case it is useful for anyone who finds this issue. The integerListFromHexString is external to this code. You could use the hex package instead.

import 'dart:typed_data';
import 'package:elliptic/elliptic.dart' hide EllipticCurve;
import 'package:webcrypto/webcrypto.dart';
import 'package:zcrypto/src/convert.dart';

/// ECDSA sign/verify using NIST-P256 algorithm
class Ecdsa {
  /// We need to convert elliptic.PrivateKey and elliptic.PublicKey -> webcrypto.EcdsaPrivateKey
  static Future<Uint8List> sign({required Uint8List message, required PrivateKey privateKey}) async {
    final pkcs8 = await
      '308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b0201010420'
      '${privateKey.toHex()}'
      'a144034200'
      '${privateKey.publicKey.toHex()}'.integerListFromHexString();
    final signingKey = await EcdsaPrivateKey.importPkcs8Key(pkcs8, EllipticCurve.p256);
    return await signingKey.signBytes(message, Hash.sha256);
  }

  /// For verification we can convert directly from elliptic.PublicKey -> webcrypto.EcdsaPublicKey
  static Future<bool> verify({required Uint8List message, required Uint8List signature, required PublicKey publicKey}) async {    
    final publicKeyBytes = await publicKey.toHex().integerListFromHexString();
    final verifyingKey = await EcdsaPublicKey.importRawKey(publicKeyBytes, EllipticCurve.p256);
    return await verifyingKey.verifyBytes(signature, message, Hash.sha256);
  }
}