在在线编译器中运行的 C# ECDSA 签名失败

如何解决在在线编译器中运行的 C# ECDSA 签名失败

我在我的 Windows 机器(Win 10 x64,运行 dotnet 4.7.2)上成功运行了这段代码。它生成一个 EC 密钥对(“P-256”),使用 SHA-256 对明文进行散列,使用 ec 私钥对散列进行签名,并使用 ec 公钥根据散列后的明文验证签名。

我得到这个输出所以一切正常:

EC signature curve secp256r1 / P-256 string
dataToSign: The quick brown fox jumps over the lazy dog
* * * sign the plaintext with the EC private key * * *
EC keysize: 256
signature (Base64): cwLBRSt1vtO33tHWcTdx1OTu9lBFXHEJgvdRyDUynLLE5eMakUZUAKLwaJvYoS7NBylx2Zz0+G6dvgJ6xv5qNA==
* * *verify the signature against hash of plaintext with the EC public key * * *
signature verified: True

现在我试图找到任何能够运行代码的在线编译器。我最喜欢的编译器 (https://repl.it/,Mono C# 编译器版本 6.8.0.123,完整代码:https://repl.it/@javacrypto/EcSignatureFull#main.cs)遇到此错误:

Unhandled Exception:
System.NotImplementedException: The method or operation is not implemented.
  at EcSignatureString.Main () [0x00036] in <13e2ad358a924efc874a89efad35ffe7>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NotImplementedException: The method or operation is not implemented.
  at EcSignatureString.Main () [0x00036] in <13e2ad358a924efc874a89efad35ffe7>:0
exit status 1

使用另一个平台(https://dotnetfiddle.net/,编译器 .net 5,完整代码:https://dotnetfiddle.net/lSPpjz)会出现类似的错误:

Unhandled exception. System.PlatformNotSupportedException: Windows Cryptography Next Generation (CNG) is not supported on this platform.
   at System.Security.Cryptography.ECDsaCng..ctor(Int32 keySize)
   at EcSignatureString.Main()
Command terminated by signal 6

所以我的问题是:是否有任何可以运行代码的在线编译器?

我认为我的问题可能与 SO 无关 - 在这种情况下 - 是否还有其他堆栈交换站点更适合我的问题?

警告:以下代码没有异常处理,仅用于教育目的:

using System;
using System.Security.Cryptography;

class EcSignatureString {
    static void Main() {

    Console.WriteLine("EC signature curve secp256r1 / P-256 string");
    string dataToSignString = "The quick brown fox jumps over the lazy dog";
    byte[] dataToSign = System.Text.Encoding.UTF8.GetBytes(dataToSignString);
    Console.WriteLine("dataToSign: " + dataToSignString);
    try {
        Console.WriteLine("\n* * * sign the plaintext with the EC private key * * *");

        ECDsaCng ecDsaKeypair = new ECDsaCng(256);
        Console.WriteLine("EC keysize: " + ecDsaKeypair.KeySize);

        byte[] hashedData = null;
        byte[] signature = null;
        // create new instance of SHA256 hash algorithm to compute hash
        HashAlgorithm hashAlgo = new SHA256Managed();
        hashedData = hashAlgo.ComputeHash(dataToSign);

        // sign Data using private key
        signature = ecDsaKeypair.SignHash(hashedData);
        string signatureBase64 = Convert.ToBase64String(signature);
        Console.WriteLine("signature (Base64): " + signatureBase64);

        // get public key from private key
        string ecDsaPublicKeyParametersXml = ecDsaKeypair.ToXmlString(ECKeyXmlFormat.Rfc4050);

        // verify
        Console.WriteLine("\n* * *verify the signature against hash of plaintext with the EC public key * * *");
        ECDsaCng ecDsaVerify = new ECDsaCng();
        bool signatureVerified = false;
        ecDsaVerify.FromXmlString(ecDsaPublicKeyParametersXml,ECKeyXmlFormat.Rfc4050);
        signatureVerified = ecDsaVerify.VerifyHash(hashedData,signature);
        Console.WriteLine("signature verified: " + signatureVerified);
        }
        catch(ArgumentNullException) {
            Console.WriteLine("The data was not signed or verified");
        }
    }
}

解决方法

Microsoft 已决定加密和散列必须完全委托给操作系统(在 .NET Framework 中是一半),因此现在 .NET 5(和 .NET Core)有多个后端用于加密(例如 { {1}} 它具有使用 Windows 服务的 ECDsa 和使用 OpenSsl 的 Linux/MacOs 的 ECDsaCng(请参阅 MSDN

现在...您的问题的解决方案是使用 ECDsaOpenSsl 类并让它选择其后端。它存在一些问题。您不能轻松地将密钥导出为 xml 格式,也不能轻松地将它们导出为 PEM 格式。您可以轻松地将它们导出为 ECDsa,并且可以轻松地从 PEM 格式导入它们。这并不是什么大问题,因为您很少需要生成密钥,通常您的程序从外部源接收其密钥,或者如果它自己生成它们,它可以将它们保存为二进制格式以便以后重用。

byte[]

关于var dataToSignString = "Hello world!"; var dataToSign = Encoding.UTF8.GetBytes(dataToSignString); Console.WriteLine("dataToSign: " + dataToSignString); try { Console.WriteLine("\n* * * sign the plaintext with the EC private key * * *"); var ecDsaKeypair = ECDsa.Create(ECCurve.NamedCurves.nistP256); // Normally here: //ecDsaKeypair.ImportFromPem() Console.WriteLine("EC keysize: " + ecDsaKeypair.KeySize); byte[] hashedData = null; byte[] signature = null; // create new instance of SHA256 hash algorithm to compute hash HashAlgorithm hashAlgo = new SHA256Managed(); hashedData = hashAlgo.ComputeHash(dataToSign); // sign Data using private key signature = ecDsaKeypair.SignHash(hashedData); string signatureBase64 = Convert.ToBase64String(signature); Console.WriteLine("signature (Base64): " + signatureBase64); // get public key from private key string ecDsaPublicKeyParameters = Convert.ToBase64String(ecDsaKeypair.ExportSubjectPublicKeyInfo()); // verify Console.WriteLine("\n* * *verify the signature against hash of plaintext with the EC public key * * *"); var ecDsaVerify = ECDsa.Create(ECCurve.NamedCurves.nistP256); bool signatureVerified = false; // Normally here: //ecDsaKeypair.ImportFromPem() var publicKey = Convert.FromBase64String(ecDsaPublicKeyParameters); ecDsaVerify.ImportSubjectPublicKeyInfo(publicKey,out _); signatureVerified = ecDsaVerify.VerifyHash(hashedData,signature); Console.WriteLine("signature verified: " + signatureVerified); } catch (ArgumentNullException) { Console.WriteLine("The data was not signed or verified"); } current comment on them on the github of .NET Core is

From/ToXmlFormat

嗯,从完成的一些测试来看,以 PEM 格式导出似乎很容易:

// There is currently not a standard XML format for ECC keys,so we will not implement the default
// To/FromXmlString so that we're not tied to one format when a standard one does exist. Instead we'll
// use an overload which allows the user to specify the format they'd like to serialize into.

然后

public static IEnumerable<string> Split(string str,int chunkSize)
{
    for (int i = 0; i < str.Length; i += chunkSize)
    {
        yield return str.Substring(i,Math.Min(chunkSize,str.Length - i));
    }
}

string b64privateKey = Convert.ToBase64String(ecDsaKeypair.ExportPkcs8PrivateKey());
b64privateKey = string.Join("\r\n",Split(b64privateKey,64));
string pemPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" + b64privateKey + "\r\n-----END PRIVATE KEY-----";

(请注意,我必须手动将字符串拆分为 64 个字符的块,这是 rfc7468 中给出的确切数字,因为 string b64publicKey = Convert.ToBase64String(ecDsaKeypair.ExportSubjectPublicKeyInfo()); b64publicKey = string.Join("\r\n",Split(b64publicKey,64)); string pemPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" + b64publicKey + "\r\n-----END PUBLIC KEY-----"; 仅支持 76 行长度)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-