/// <summary> /// 使用公钥验证消息的签名是否正确 /// </summary> /// <param name="publicKey"></param> /// <param name="message"></param> /// <param name="signature"></param> /// <returns></returns> public static bool Verify(PublicKey publicKey, ReadOnlySpan <byte> message, Signature signature) { if (message.Length != 32) { throw new InvalidMessageException("消息长度必须是32字节"); } var msg = ModN.U256(message, bigEndian: true); var S_inv = ModN.Inverse(signature.S); var u1 = ModN.Mul(S_inv, msg); var u2 = ModN.Mul(S_inv, signature.R); var P = ModP.Add(ModP.MulG(u1), ModP.Mul(publicKey.ToPoint(), u2)); return(ModP.Equal(P.X, signature.R)); }
/// <summary> /// 使用自己的私钥与对方公钥进行密钥交换(私钥A×公钥B = 私钥B×公钥A) /// </summary> /// <param name="privateKey"></param> /// <param name="publicKey"></param> /// <returns></returns> unsafe public static EncryptionKey CreateEncryptionKey(ReadOnlySpan <byte> privateKey, PublicKey publicKey) { if (privateKey.Length != 32) { throw new InvalidPrivateKeyException("私钥长度必须是32字节"); } var k = new U256(privateKey, bigEndian: true); if (k.IsZero || k >= ModN.N) { throw new InvalidPrivateKeyException(); } var p = ModP.Mul(publicKey.ToPoint(), k); Clear(&k); return(new EncryptionKey(ModP.ToU256(p.X), ModP.ToU256(p.Y))); }