asn1IntegerFromHex method

Pointer<ASN1_INTEGER> asn1IntegerFromHex(
  1. String hex
)
inherited

Converts hexadecimal string to ASN1_INTEGER through BIGNUM.

Caller is responsible for freeing the returned pointer using ASN1_INTEGER_free.

Implementation

Pointer<ASN1_INTEGER> asn1IntegerFromHex(String hex) {
  var normalized = hex.trim();
  if (normalized.startsWith('0x') || normalized.startsWith('0X')) {
    normalized = normalized.substring(2);
  }
  normalized = normalized.replaceAll(':', '').replaceAll(' ', '');
  if (normalized.isEmpty || !_isHex(normalized)) {
    throw ArgumentError('Invalid hexadecimal ASN1 integer: $hex');
  }

  if (normalized.length.isOdd) {
    normalized = '0$normalized';
  }

  final bytes = _hexToBytes(normalized);
  final inPtr = calloc<Uint8>(bytes.length);
  inPtr.asTypedList(bytes.length).setAll(0, bytes);

  final bn =
      bindings.BN_bin2bn(inPtr.cast<UnsignedChar>(), bytes.length, nullptr);
  calloc.free(inPtr);

  if (bn == nullptr) {
    throw OpenSslException('BN_bin2bn failed');
  }

  try {
    final asn1 = bindings.BN_to_ASN1_INTEGER(bn, nullptr);
    if (asn1 == nullptr) {
      throw OpenSslException('BN_to_ASN1_INTEGER failed');
    }
    return asn1;
  } finally {
    bindings.BN_free(bn);
  }
}