如何在C#中解密Base64格式的Ephemeral public key
C# 处理Curve25519 ECDH公钥(Base64解码与密钥加载)
你的需求是将Base64编码的Curve25519公钥(keyValue字段)解码并在C#中用于ECDH密钥交换,以下是具体实现步骤和代码:
前置说明
.NET Core 3.0及以上版本原生支持Curve25519算法,若使用.NET Framework需要借助第三方库(如BouncyCastle),以下示例基于.NET Core/.NET 5+。
实现步骤
- Base64解码:先将Base64字符串转换为二进制字节数组
- 处理公钥格式:Curve25519公钥标准长度为32字节,你的Base64解码后可能带有1字节的前缀(通常是
0x04),需要截取后32字节作为有效公钥 - 加载公钥并执行ECDH交换:使用
ECDiffieHellman.Create方法指定Curve25519曲线,导入公钥并计算共享密钥
完整代码示例
using System; using System.Security.Cryptography; public class EcdhCurve25519Handler { public static byte[] ComputeSharedSecret(string base64PublicKey) { // 1. Base64解码得到原始字节 byte[] encodedPublicKey = Convert.FromBase64String(base64PublicKey); // 2. 处理公钥:如果带有0x04前缀,截取后32字节(Curve25519标准公钥长度) byte[] curve25519PublicKey; if (encodedPublicKey.Length == 33 && encodedPublicKey[0] == 0x04) { curve25519PublicKey = new byte[32]; Array.Copy(encodedPublicKey, 1, curve25519PublicKey, 0, 32); } else if (encodedPublicKey.Length == 32) { curve25519PublicKey = encodedPublicKey; } else { throw new ArgumentException("无效的Curve25519公钥长度"); } // 3. 创建Curve25519 ECDH实例 using var ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.curve25519); // 4. 导入对方公钥 using var otherPartyPublicKey = ECDiffieHellman.Create(); otherPartyPublicKey.ImportSubjectPublicKeyInfo(curve25519PublicKey, out _); // 5. 计算共享密钥 return ecdh.DeriveKeyMaterial(otherPartyPublicKey.PublicKey); } public static void Main() { string keyValue = "BA5bNnUGeT8y3qoCBBQ+hz/+RUtTO0hV3yPJAR7/NFWJWVMF0Dz3hr/wqn62xztP6LSZXg/IEnpzIdvJkx3P/gI="; try { byte[] sharedSecret = ComputeSharedSecret(keyValue); // 可以将共享密钥转为Base64方便查看 Console.WriteLine("共享密钥(Base64): " + Convert.ToBase64String(sharedSecret)); } catch (Exception ex) { Console.WriteLine("处理失败: " + ex.Message); } } }
关键说明
- 若你的公钥没有
0x04前缀,直接使用32字节的解码结果即可 - 共享密钥是原始二进制数据,通常需要再经过哈希(如SHA-256)作为最终的加密密钥使用
- 如果使用.NET Framework,推荐使用BouncyCastle库的
X25519类来处理Curve25519密钥交换
内容的提问来源于stack exchange,提问作者kanchan
相关产品推荐
相关产品推荐

