public static byte[] ToAsc(byte[] pgp) { MemoryStream ms = new MemoryStream(); var ring = new PgpPublicKeyRing(GetStream(pgp)); var armored = new ArmoredOutputStream(ms); ring.Encode(armored); armored.Dispose(); return(ms.ToArray()); }
public static string Sign(string hash, string keyFile, string keyPass) { var outStream = new MemoryStream(); var armoredStream = new ArmoredOutputStream(outStream); var secretKey = ReadSigningKey(keyFile); var privateKey = secretKey.ExtractPrivateKey(keyPass.ToCharArray()); var sigGen = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha384); sigGen.InitSign(PgpSignature.BinaryDocument, privateKey); foreach (string userId in secretKey.PublicKey.GetUserIds()) { var subpacketGenerator = new PgpSignatureSubpacketGenerator(); subpacketGenerator.SetSignerUserId(false, userId); sigGen.SetHashedSubpackets(subpacketGenerator.Generate()); break; } var signedStream = new BcpgOutputStream(armoredStream); sigGen.GenerateOnePassVersion(false).Encode(signedStream); var inStream = new MemoryStream(Encoding.ASCII.GetBytes(hash)); var literalGenerator = new PgpLiteralDataGenerator(); var literalOut = literalGenerator.Open(signedStream, PgpLiteralData.Binary, "hash", hash.Length, DateTime.Now); int ch; while ((ch = inStream.ReadByte()) >= 0) { literalOut.WriteByte((byte)ch); sigGen.Update((byte)ch); } inStream.Dispose(); literalGenerator.Close(); sigGen.Generate().Encode(signedStream); armoredStream.Dispose(); return(Encoding.ASCII.GetString(outStream.ToArray())); }
public static string EncryptKeyFor(string aesKeyToEncrypt, string publicKeyText) { var publicKey = ReadPublicKey(publicKeyText); var literalByteStream = new MemoryStream(); var literalDataGenerator = new PgpLiteralDataGenerator(); var pOut = literalDataGenerator.Open( literalByteStream, // A stream for all the literal data PgpLiteralData.Binary, "key", // "filename" to store aesKeyToEncrypt.Length, // length of clear data DateTime.UtcNow // current time ); pOut.Write(Encoding.ASCII.GetBytes(aesKeyToEncrypt), 0, aesKeyToEncrypt.Length); literalDataGenerator.Close(); var encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, new SecureRandom()); encryptedDataGenerator.AddMethod(publicKey); byte[] literalBytes = literalByteStream.ToArray(); MemoryStream encryptedStream = new MemoryStream(); var armoredStream = new ArmoredOutputStream(encryptedStream); Stream cOut = encryptedDataGenerator.Open(armoredStream, literalBytes.Length); cOut.Write(literalBytes, 0, literalBytes.Length); // obtain the actual bytes from the compressed stream cOut.Dispose(); armoredStream.Dispose(); return(Encoding.ASCII.GetString(encryptedStream.ToArray())); }