2026-04-24 14:06:19 +08:00

158 lines
4.9 KiB
C#

using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
using NBitcoin;
const string cipherTextBase64 = "QklFMQMdos3oztNAUqW++4+GjfblOT2MSNZEd18K++IqbAckRCq7/RjlzUJbgonrHbZabwdDSyTkrpUM2X8K0aip90/7K0fNvbILk7kgfiQBxMErAwnJzcJXLtKI/Yb3M4Kpj3BSWLhFpYkpx8lMmBsg8lHHnD+JIkf8johOj60UzL0CxeFS5NvohFRmzdesox2Ge8CoNn8A+szcsrENmxvDWGsQx0C/D1ya6GobKYZpWnG+KA0yui7KpfQCM6jP7JvnaLc=";
const string recipientWif = "cRLzVXAinDb2Fvn3hTn5R3q57wbigm5SvFe4WbiDmzrMqGYwPfD3";
const string candidateAPublicKey = "029b9415580dc6fb0bc298923470ce2f2289cfefb6a06e14f1620e877c164a65b7";
const string candidateCPrivateKey = "cUsnFska4Ksz8eqCA31JBVYCPPe453jQ8FXHfACaL23sZcBarXKS";
const string candidateDPublicKey = "03f25e285ae095e927ef3477c05d67ce8d4d31e3a151459c9a76f124248a3738b5";
var recipientSecret = ResolveSecret(recipientWif);
var envelope = Bie1Envelope.Parse(cipherTextBase64);
var plainText = envelope.Decrypt(recipientSecret.PrivateKey);
var sender = InferSender(envelope.SenderPublicKey, plainText, recipientSecret.PrivateKey.PubKey);
Console.WriteLine($"密文解密后是 {plainText}");
Console.WriteLine($"内嵌发送方公钥是 {envelope.SenderPublicKey.ToHex()}");
Console.WriteLine($"这条消息来自 {sender}");
static string InferSender(PubKey embeddedSenderPublicKey, string plainText, PubKey recipientPublicKey)
{
var candidates = new Dictionary<string, PubKey>(StringComparer.Ordinal)
{
["A"] = new PubKey(Convert.FromHexString(candidateAPublicKey)),
["B"] = recipientPublicKey,
["C"] = ResolveSecret(candidateCPrivateKey).PrivateKey.PubKey,
["D"] = new PubKey(Convert.FromHexString(candidateDPublicKey))
};
var signedMessage = ParseSignedMessage(plainText);
if (signedMessage is not null)
{
foreach (var candidate in candidates)
{
if (candidate.Value.VerifyMessage(signedMessage.Message, signedMessage.Signature))
{
return candidate.Key;
}
}
}
foreach (var candidate in candidates)
{
if (candidate.Value.ToHex().Equals(embeddedSenderPublicKey.ToHex(), StringComparison.OrdinalIgnoreCase))
{
return candidate.Key;
}
}
foreach (var candidate in candidates.Keys)
{
if (plainText.Contains($"来自{candidate}", StringComparison.Ordinal)
|| plainText.Contains($"我是{candidate}", StringComparison.Ordinal)
|| plainText.Contains($"from {candidate}", StringComparison.OrdinalIgnoreCase)
|| plainText.Contains($"sender:{candidate}", StringComparison.OrdinalIgnoreCase))
{
return candidate;
}
}
return "无法仅凭当前信息自动判定";
}
static SignedMessage? ParseSignedMessage(string plainText)
{
var match = Regex.Match(plainText, "^Msg: \"(?<message>.*)\", signature: \"(?<signature>.*)\"$", RegexOptions.CultureInvariant);
if (!match.Success)
{
return null;
}
return new SignedMessage(match.Groups["message"].Value, match.Groups["signature"].Value);
}
static BitcoinSecret ResolveSecret(string wif)
{
foreach (var network in new[] { Network.Main, Network.TestNet })
{
try
{
return new BitcoinSecret(wif, network);
}
catch (FormatException)
{
}
}
throw new FormatException($"无法识别 WIF 私钥对应的网络: {wif}");
}
sealed class Bie1Envelope
{
private Bie1Envelope(byte[] rawBytes, PubKey senderPublicKey, byte[] cipherText, byte[] mac)
{
RawBytes = rawBytes;
SenderPublicKey = senderPublicKey;
CipherText = cipherText;
Mac = mac;
}
public byte[] RawBytes { get; }
public PubKey SenderPublicKey { get; }
public byte[] CipherText { get; }
public byte[] Mac { get; }
public static Bie1Envelope Parse(string base64)
{
var rawBytes = Convert.FromBase64String(base64);
if (rawBytes.Length <= 69)
{
throw new FormatException("BIE1 密文长度无效。");
}
var magic = Encoding.ASCII.GetString(rawBytes, 0, 4);
if (!string.Equals(magic, "BIE1", StringComparison.Ordinal))
{
throw new FormatException("密文不是 BIE1 格式。");
}
var senderPublicKeyBytes = rawBytes[4..37];
var cipherText = rawBytes[37..^32];
var mac = rawBytes[^32..];
return new Bie1Envelope(rawBytes, new PubKey(senderPublicKeyBytes), cipherText, mac);
}
public string Decrypt(Key recipientPrivateKey)
{
var sharedPublicKey = SenderPublicKey.GetSharedPubkey(recipientPrivateKey);
var derived = SHA512.HashData(sharedPublicKey.ToBytes());
var iv = derived[..16];
var encryptionKey = derived[16..32];
var macKey = derived[32..64];
var expectedMac = HMACSHA256.HashData(macKey, RawBytes[..^32]);
if (!CryptographicOperations.FixedTimeEquals(expectedMac, Mac))
{
throw new CryptographicException("BIE1 HMAC 校验失败。");
}
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = encryptionKey;
aes.IV = iv;
using var decryptor = aes.CreateDecryptor();
var plainBytes = decryptor.TransformFinalBlock(CipherText, 0, CipherText.Length);
return Encoding.UTF8.GetString(plainBytes);
}
}
sealed record SignedMessage(string Message, string Signature);