gpt4 book ai didi

c# - 如何使用 Bouncy CaSTLe 库在 C# 中使用 PGP key 对 txt 文件进行签名

转载 作者:行者123 更新时间:2023-11-30 14:02:16 26 4
gpt4 key购买 nike

有没有人举例说明如何使用 C# 和 Bouncy CaSTLe 库中的 PGP key 对 txt 文件进行签名。不加密文件,只添加签名。

最佳答案

public void SignFile(String fileName, 
Stream privateKeyStream,
String privateKeyPassword,
Stream outStream)
{

PgpSecretKey pgpSec = ReadSigningSecretKey(privateKeyStream);
PgpPrivateKey pgpPrivKey = null;

pgpPrivKey = pgpSec.ExtractPrivateKey(privateKeyPassword.ToCharArray());
PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, KeyStore.ParseHashAlgorithm(this.hash.ToString()));

sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

foreach (string userId in pgpSec.PublicKey.GetUserIds()) {
PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

spGen.SetSignerUserId(false, userId);
sGen.SetHashedSubpackets(spGen.Generate());
}

CompressionAlgorithmTag compression = PreferredCompression(pgpSec.PublicKey);
PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(compression);

BcpgOutputStream bOut = new BcpgOutputStream(cGen.Open(outStream));
sGen.GenerateOnePassVersion(false).Encode(bOut);

FileInfo file = new FileInfo(fileName);
FileStream fIn = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);

int ch = 0;
while ((ch = fIn.ReadByte()) >= 0) {
lOut.WriteByte((byte)ch);
sGen.Update((byte) ch);
}

fIn.Close();
sGen.Generate().Encode(bOut);
lGen.Close();
cGen.Close();
outStream.Close();
}

public PgpSecretKey ReadSigningSecretKey(Stream inStream)
// throws IOException, PGPException, WrongPrivateKeyException
{
PgpSecretKeyRingBundle pgpSec = CreatePgpSecretKeyRingBundle(inStream);
PgpSecretKey key = null;
IEnumerator rIt = pgpSec.GetKeyRings().GetEnumerator();
while (key == null && rIt.MoveNext())
{
PgpSecretKeyRing kRing = (PgpSecretKeyRing)rIt.Current;
IEnumerator kIt = kRing.GetSecretKeys().GetEnumerator();
while (key == null && kIt.MoveNext())
{
PgpSecretKey k = (PgpSecretKey)kIt.Current;
if(k.IsSigningKey)
key = k;
}
}

if(key == null)
throw new WrongPrivateKeyException("Can't find signing key in key ring.");
else
return key;
}

关于c# - 如何使用 Bouncy CaSTLe 库在 C# 中使用 PGP key 对 txt 文件进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6337985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com