-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compressor.cs
77 lines (62 loc) · 2.47 KB
/
Compressor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
namespace HackMdBackup;
using System.IO;
using SharpCompress.Common;
using SharpCompress.Writers;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
public class FileProcessor
{
public void CreateTarGz(string outputPath, string inputDirectory)
{
using Stream targetStream = File.OpenWrite(outputPath);
using var writer = WriterFactory.Open(targetStream, ArchiveType.Tar, CompressionType.GZip);
writer.WriteAll(inputDirectory, searchPattern: "*", SearchOption.AllDirectories);
}
public void EncryptFile(string inputFile, string publicKeyFile, string outputFile, bool armor, bool withIntegrityCheck)
{
using Stream publicKeyStream = File.OpenRead(publicKeyFile);
PgpPublicKey encKey = ReadPublicKey(publicKeyStream);
using MemoryStream bOut = new MemoryStream();
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
PgpUtilities.WriteFileToLiteralData(
comData.Open(bOut),
PgpLiteralData.Binary,
new FileInfo(inputFile));
comData.Close();
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
cPk.AddMethod(encKey);
byte[] bytes = bOut.ToArray();
using Stream outputStream = File.Create(outputFile);
if (armor)
{
using Stream armoredStream = new ArmoredOutputStream(outputStream);
WriteBytesToStream(cPk.Open(armoredStream, bytes.Length), bytes);
}
else
{
WriteBytesToStream(cPk.Open(outputStream, bytes.Length), bytes);
}
}
private static void WriteBytesToStream(Stream outputStream, byte[] bytes)
{
using Stream encryptedOut = outputStream;
encryptedOut.Write(bytes, 0, bytes.Length);
}
private static PgpPublicKey ReadPublicKey(Stream inputStream)
{
using Stream keyIn = inputStream;
PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
{
foreach (PgpPublicKey key in keyRing.GetPublicKeys())
{
if (key.IsEncryptionKey)
{
return key;
}
}
}
throw new ArgumentException("Can't find encryption key in key ring.");
}
}