/// <summary>Write out the passed in file as a literal data packet in partial packet format.</summary> public static void WriteFileToLiteralData( Stream inputStream, Stream outputStream, char fileType, string fileName, byte[] buffer) { if (fileName == null) { fileName = "fileName"; } try { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(outputStream, fileType, fileName, DateTime.Now, buffer); byte[] buf = new byte[buffer.Length]; int len; while ((len = inputStream.Read(buf, 0, buf.Length)) > 0) { pOut.Write(buf, 0, len); } lData.Close(); } finally { inputStream.Dispose(); } }
public static byte[] EncryptForKeys(byte[] data, List <PgpPublicKey> keys, string filename = "encrypted-data.gpg") { using (MemoryStream encOut = new MemoryStream(), bOut = new MemoryStream()) { // region Compression var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var cos = comData.Open(bOut); var lData = new PgpLiteralDataGenerator(); var pOut = lData.Open( cos, PgpLiteralData.Binary, filename, data.Length, DateTime.UtcNow ); pOut.Write(data, 0, data.Length); lData.Close(); comData.Close(); byte[] bytes = bOut.ToArray(); // endregion // region Encryption var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom()); keys.ForEach(cPk.AddMethod); var cOut = cPk.Open(encOut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); // obtain the actual bytes from the compressed stream cOut.Close(); encOut.Seek(0, SeekOrigin.Begin); return(encOut.ToArray()); // endregion } }
public string EncryptMessage(string unencryptedMessage, char[] passPhrase) { // Convert the input to a byte array. We expect the string to be UTF-8 encoded var unencryptedByteArray = Encoding.UTF8.GetBytes(unencryptedMessage); var lData = new PgpLiteralDataGenerator(); // Write the data to a literal MemoryStream bOut; using (bOut = new MemoryStream()) { using var pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now); pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length); } lData.Close(); var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true); cPk.AddMethod(passPhrase, HashAlgorithmTag.Sha1); var bytes = bOut.ToArray(); MemoryStream encOut; using (encOut = new MemoryStream()) { using var cOut = cPk.Open(encOut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); } return(Convert.ToBase64String(encOut.ToArray())); }
/*.......................................................................數位簽章開始*/ private static void SignFile( string fileName, //欲作簽章的檔案名稱及位置 Stream keyIn, // Private key 的 File Stream Stream outputStream, //簽章後的檔案 File Stream char[] pass, // private Key 的 password bool armor, //用途不明?? 範例預設true bool compress //用途不明?? 範例預設true ) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); } PgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); foreach (string userId in pgpSec.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, userId); sGen.SetHashedSubpackets(spGen.Generate()); // Just the first one! break; } Stream cOut = outputStream; PgpCompressedDataGenerator cGen = null; if (compress) { cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib); cOut = cGen.Open(cOut); } BcpgOutputStream bOut = new BcpgOutputStream(cOut); sGen.GenerateOnePassVersion(false).Encode(bOut); FileInfo file = new FileInfo(fileName); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file); FileStream fIn = file.OpenRead(); int ch = 0; while ((ch = fIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } fIn.Close(); lGen.Close(); sGen.Generate().Encode(bOut); if (cGen != null) { cGen.Close(); } if (armor) { outputStream.Close(); } }
private static void WriteToLiteralData(PgpSignatureGenerator signatureGenerator, Stream outStream, byte[] data) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); MemoryStream ms = new MemoryStream(data); try { using (Stream literalOut = lData.Open(outStream, PgpLiteralData.Binary, "pgp", DateTime.UtcNow, new byte[BUFFER_SIZE])) { byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = ms.Read(buf, 0, buf.Length)) > 0) { literalOut.Write(buf, 0, len); signatureGenerator.Update(buf, 0, len); } } } catch (Exception ex) { throw new CryptoException(ex.Message, ex); } finally { lData.Close(); } }
public string Encrypt(string filename, byte[] data, PgpPublicKey publicKey) { using (MemoryStream encOut = new MemoryStream(), bOut = new MemoryStream()) { var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var cos = comData.Open(bOut); // open it with the final destination var lData = new PgpLiteralDataGenerator(); var pOut = lData.Open( cos, // the compressed output stream PgpLiteralData.Binary, filename, // "filename" to store data.Length, // length of clear data DateTime.UtcNow // current time ); pOut.Write(data, 0, data.Length); lData.Close(); comData.Close(); var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom()); cPk.AddMethod(publicKey); byte[] bytes = bOut.ToArray(); var s = new ArmoredOutputStream(encOut); var cOut = cPk.Open(s, bytes.Length); cOut.Write(bytes, 0, bytes.Length); // obtain the actual bytes from the compressed stream cOut.Close(); s.Close(); encOut.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(encOut); return(reader.ReadToEnd()); } }
public String EncryptKeycode(String publicKeyStr, String unencryptedKeycode) { byte[] unencryptedByteArray = System.Text.Encoding.ASCII.GetBytes(unencryptedKeycode); byte[] decodedPublicKey = System.Text.Encoding.ASCII.GetBytes(publicKeyStr); PgpPublicKey key = null; Stream decodedStream = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPublicKey)); PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(decodedStream); foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { foreach (PgpPublicKey publicKey in pgpPub.GetPublicKeys()) { if (publicKey.IsEncryptionKey) { key = publicKey; break; } } } if (key == null) { throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring."); } PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true); cPk.AddMethod(key); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // Write the data to a literal MemoryStream bOut; using (bOut = new MemoryStream()) { using (Stream pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now)) { pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length); } } lData.Close(); byte[] bytes = bOut.ToArray(); MemoryStream encOut = new MemoryStream(); using (ArmoredOutputStream armoredOut = new ArmoredOutputStream(encOut)) { using (Stream cOut = cPk.Open(armoredOut, bytes.Length)) { cOut.Write(bytes, 0, bytes.Length); } } return(System.Text.Encoding.Default.GetString(encOut.ToArray())); }
/// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static PgpSignatureResult SignFile(PgpSignatureInput input) { HashAlgorithmTag digest = input.HashFunction.ConvertEnum <HashAlgorithmTag>(); using (var privateKeyStream = File.OpenRead(input.PrivateKeyFile)) { var pgpSecKey = PgpServices.SignatureReadSecretKey(privateKeyStream); var pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); var signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); var signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); var enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { signatureSubpacketGenerator.SetSignerUserId(false, (string)enumerator.Current); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); } using (var outputStream = File.Create(input.OutputFile)) { var armoredOutputStream = new ArmoredOutputStream(outputStream); var bcbgOutputStream = new BcpgOutputStream(armoredOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcbgOutputStream); var file = new FileInfo(input.InputFile); var literalDataGenerator = new PgpLiteralDataGenerator(); var literalDataOut = literalDataGenerator.Open(bcbgOutputStream, PgpLiteralData.Binary, file.Name, file.Length, DateTime.Now); using (var fileIn = file.OpenRead()) { int ch; while ((ch = fileIn.ReadByte()) >= 0) { literalDataOut.WriteByte((byte)ch); signatureGenerator.Update((byte)ch); } fileIn.Close(); literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcbgOutputStream); armoredOutputStream.Close(); outputStream.Close(); var ret = new PgpSignatureResult { FilePath = input.OutputFile }; return(ret); } } } }
/// <summary>Write out the passed in file as a literal data packet.</summary> public static void WriteFileToLiteralData( Stream output, char fileType, FileInfo file) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(output, fileType, file.Name, file.Length, file.LastWriteTime); PipeFileContents(file, pOut, 4096); lData.Close(); }
public static void WriteToLiteralData(Stream outStream, char filetype, byte[] data) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(outStream, filetype, "temp", data.LongLength, new DateTime()); foreach (var b in data) { pOut.WriteByte(b); } lData.Close(); }
public static void Encrypt(byte[] clearData, PgpPublicKey encKey, string fileName, FileStream fos, bool withIntegrityCheck, bool armor) { if (fileName == null) { fileName = PgpLiteralData.Console; } MemoryStream encOut = new MemoryStream(); Stream outPut = encOut; if (armor) { outPut = new Org.BouncyCastle.Bcpg.ArmoredOutputStream(outPut); } MemoryStream bOut = new MemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); Stream cos = comData.Open(bOut); // open it with the final // destination PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // we want to generate compressed data. This might be a user option // later, // in which case we would pass in bOut. Stream pOut = lData.Open(cos, PgpLiteralData.Binary, fileName, clearData.Length, DateTime.Now); pOut.Write(clearData, 0, clearData.Length); lData.Close(); comData.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new Org.BouncyCastle.Security.SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); Stream cOut = cPk.Open(outPut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); outPut.Close(); //FileStream fileStream = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from // a byte array. fos.Write(encOut.ToArray(), 0, encOut.ToArray().Length); // close file stream fos.Close(); }
public static void WriteStreamToLiteralData( Stream output, char fileType, Stream input, string name) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(output, fileType, name, input.Length, DateTime.Now); PipeStreamContents(input, pOut, 4096); lData.Close(); }
/// <summary>Write out the passed in file as a literal data packet in partial packet format.</summary> public static async Task WriteFileToLiteralDataAsync( Stream output, char fileType, FileInfo file, byte[] buffer) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(output, fileType, file.Name, file.LastWriteTime, buffer); await PipeFileContentsAsync(file, pOut, buffer.Length); lData.Close(); }
public static async Task WriteStreamToLiteralDataAsync( Stream output, char fileType, Stream input, byte[] buffer, string name) { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(output, fileType, name, DateTime.Now, buffer); await PipeStreamContentsAsync(input, pOut, buffer.Length); lData.Close(); }
// http://stackoverflow.com/questions/20572737/sign-and-verify-xml-file-in-c-sharp public void SignFile(string hashAlgorithm, string fileName, System.IO.Stream privateKeyStream , string privateKeyPassword, System.IO.Stream outStream) { PgpSecretKey pgpSec = ReadSigningSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = null; pgpPrivKey = pgpSec.ExtractPrivateKey(privateKeyPassword.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, ParseHashAlgorithm(hashAlgorithm)); 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); System.IO.FileInfo file = new System.IO.FileInfo(fileName); System.IO.FileStream fIn = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); System.IO.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(); }
private void doTestTextSig( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey, byte[] data, byte[] canonicalData) { PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(data, false); DateTime creationTime = DateTime.UtcNow; sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Text, "_CONSOLE", data.Length * 2, creationTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(data, 0, data.Length); sGen.Update(data); lGen.Close(); PgpSignature sig = sGen.Generate(); if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0)) { Fail("creation time not set in v4 signature"); } sig.Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData); }
/// <summary> /// /// </summary> /// <param name="clearData"></param> /// <param name="publicKeyFile"></param> /// <param name="withIntegrityCheck"></param> /// <param name="filename"></param> /// <returns></returns> public static Stream Encrypt(byte[] clearData, Stream publicKeyFile, bool withIntegrityCheck, string filename) { publicKeyFile.TryResetStream(); PgpPublicKey encKey = ReadPublicKey(publicKeyFile); MemoryStream bOut = new MemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); Stream cos = comData.Open(bOut); // open it with the final destination PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // we want to Generate compressed data. This might be a user option later, // in which case we would pass in bOut. Stream pOut = lData.Open( cos, // the compressed output stream PgpLiteralData.Binary, filename, // "filename" to store clearData.Length, // length of clear data DateTime.UtcNow // current time ); pOut.Write(clearData, 0, clearData.Length); lData.Close(); comData.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); MemoryStream encOut = new MemoryStream(); Stream os = encOut; Stream cOut = cPk.Open(os, bytes.Length); cOut.Write(bytes, 0, bytes.Length); // obtain the actual bytes from the compressed stream cOut.Close(); // encOut.Close(); return(encOut); }
private byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey) { using (MemoryStream bOut = new MemoryStream()) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); Stream compressedStream = compressedDataGenerator.Open(bOut); // open it with the final destination PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // we want to Generate compressed data. This might be a user option later, // in which case we would pass in bOut. Stream pOut = lData.Open( compressedStream, // the compressed output stream PgpLiteralData.Binary, fileName, // "filename" to store clearData.Length, // length of clear data DateTime.UtcNow // current time ); pOut.Write(clearData, 0, clearData.Length); lData.Close(); compressedDataGenerator.Close(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, new SecureRandom()); cPk.AddMethod(encKey); byte[] bytes = bOut.ToArray(); MemoryStream encOut = new MemoryStream(); Stream os = encOut; Stream cOut = cPk.Open(os, bytes.Length); cOut.Write(bytes, 0, bytes.Length); // obtain the actual bytes from the compressed stream cOut.Close(); encOut.Close(); return(encOut.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())); }
private void ReadBackTest( PgpLiteralDataGenerator generator) { Random rand = new Random(); byte[] buf = new byte[MAX]; rand.NextBytes(buf); for (int i = 1; i != MAX; i++) { MemoryStream bOut = new MemoryStream(); Stream outputStream = generator.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, PgpLiteralData.Console, i, DateTime.UtcNow); outputStream.Write(buf, 0, i); generator.Close(); PgpObjectFactory fact = new PgpObjectFactory(bOut.ToArray()); PgpLiteralData data = (PgpLiteralData)fact.NextPgpObject(); Stream inputStream = data.GetInputStream(); for (int count = 0; count != i; count++) { if (inputStream.ReadByte() != (buf[count] & 0xff)) { Fail("failed readback test - length = " + i); } } } }
static void Encrypt(byte[] data, int len, string name, Stream encStream) { byte[] bytes; using (var tempStream = new MemoryStream()) { Stream inputStream = tempStream; var lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(inputStream, PgpLiteralData.Binary, name, len, DateTime.Now); pOut.Write(data, 0, len); pOut.Dispose(); lData.Close(); bytes = tempStream.ToArray(); } // var generator = new PgpEncryptedDataGenerator(KeyAlgorithm, false, new SecureRandom()); generator.AddMethod(PublicKey); using (var encryptedOut = generator.Open(encStream, new byte[BUFFER_SIZE])) { encryptedOut.Write(bytes, 0, bytes.Length); } }
private void doTestSig( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(TEST_DATA, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, "_CONSOLE", TEST_DATA.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(TEST_DATA, 0, TEST_DATA.Length); sGen.Update(TEST_DATA); lGen.Close(); sGen.Generate().Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, TEST_DATA); }
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())); }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing); PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject(); pubKey = pgpPub.GetPublicKey(); if (pubKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream( cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte) ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed Generated signature check"); } // // test encryption // // // find a key sutiable for encryption // long pgpKeyID = 0; AsymmetricKeyParameter pKey = null; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt || pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral) { pKey = pgpKey.GetKey(); pgpKeyID = pgpKey.KeyId; if (pgpKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // verify the key // } } IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding"); c.Init(true, pKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // encrypted message // byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' }; PgpObjectFactory pgpF = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // signed and encrypted message // pgpF = new PgpObjectFactory(signedAndEncMessage); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; ld = (PgpLiteralData)pgpFact.NextPgpObject(); bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } inLd = ld.GetDataStream(); // // note: we use the DSA public key here. // ops.InitVerify(pgpPub.GetPublicKey()); while ((ch = inLd.ReadByte()) >= 0) { ops.Update((byte) ch); bOut.WriteByte((byte) ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } if (!Arrays.AreEqual(bOut.ToArray(), text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt // MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.TripleDes, random); PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in Generated packet"); } // // use of PgpKeyPair // BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral , kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!) for (int pSize = 257; pSize < 264; ++pSize) { // Generate some parameters of the given size ElGamalParametersGenerator epg = new ElGamalParametersGenerator(); epg.Init(pSize, 2, random); elParams = epg.GenerateParameters(); kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); // Run a short encrypt/decrypt test with random key for the given parameters kp = kpg.GenerateKeyPair(); PgpKeyPair elGamalKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); puK = elGamalKeyPair.PublicKey; cPk.AddMethod(puK); cbOut = new MemoryStream(); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = elGamalKeyPair.PrivateKey; // Note: This is where an exception would be expected if the P size causes problems clear = encP.GetDataStream(pgpPrivKey); byte[] decText = Streams.ReadAll(clear); if (!Arrays.AreEqual(text, decText)) { Fail("decrypted message incorrect"); } } // check sub key encoding foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (!pgpKey.IsMasterKey) { byte[] kEnc = pgpKey.GetEncoded(); PgpObjectFactory objF = new PgpObjectFactory(kEnc); // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing // PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject(); // // pKey = k.GetKey(); // pgpKeyID = k.KeyId; // if (k.BitStrength != 1024) // { // Fail("failed - key strength reported incorrectly."); // } // // if (objF.NextPgpObject() != null) // { // Fail("failed - stream not fully parsed."); // } } } }
private void doSigGenerateTest( string privateKeyFile, string publicKeyFile, HashAlgorithmTag digest) { PgpSecretKeyRing secRing = loadSecretKey(privateKeyFile); PgpPublicKeyRing pubRing = loadPublicKey(publicKeyFile); string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, digest); sGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test".ToCharArray())); BcpgOutputStream bcOut = new BcpgOutputStream(bOut); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); // Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000); DateTime testDate = new DateTime( (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDate); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; Assert.AreEqual(digest, ops.HashAlgorithm); Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, ops.KeyAlgorithm); PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDate)) { Assert.Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubRing.GetPublicKey()); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; Assert.AreEqual(digest, sig.HashAlgorithm); Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, sig.KeyAlgorithm); Assert.IsTrue(ops.Verify(sig)); }
public void SignAndEncryptFile(string strActualFileName, string strEmbeddedFileName, System.IO.Stream strmKeyIn, long lngKeyId, System.IO.Stream strmOutputStream, char[] szPassword, bool bArmor, bool bWithIntegrityCheck, PgpPublicKey PGP_PublicKey) { const int iBUFFER_SIZE = 1 << 16; // should always be power of 2 if (bArmor) { strmOutputStream = new ArmoredOutputStream(strmOutputStream); } // Init encrypted data generator PgpEncryptedDataGenerator PGP_EncryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, bWithIntegrityCheck, new SecureRandom()); PGP_EncryptedDataGenerator.AddMethod(PGP_PublicKey); System.IO.Stream strmEncryptedOut = PGP_EncryptedDataGenerator.Open(strmOutputStream, new byte[iBUFFER_SIZE]); // Init compression PgpCompressedDataGenerator PGP_CompressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); System.IO.Stream strmCompressedOut = PGP_CompressedDataGenerator.Open(strmEncryptedOut); // Init signature PgpSecretKeyRingBundle PGP_SecretKeyBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(strmKeyIn)); PgpSecretKey PGP_SecretKey = PGP_SecretKeyBundle.GetSecretKey(lngKeyId); if (PGP_SecretKey == null) { throw new System.ArgumentException(lngKeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId"); } PgpPrivateKey PGP_PrivateKey = PGP_SecretKey.ExtractPrivateKey(szPassword); PgpSignatureGenerator PGP_SignatureGenerator = new PgpSignatureGenerator(PGP_SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); PGP_SignatureGenerator.InitSign(PgpSignature.BinaryDocument, PGP_PrivateKey); foreach (string strUserId in PGP_SecretKey.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator PGP_SignatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); PGP_SignatureSubpacketGenerator.SetSignerUserId(false, strUserId); PGP_SignatureGenerator.SetHashedSubpackets(PGP_SignatureSubpacketGenerator.Generate()); // Just the first one! break; } PGP_SignatureGenerator.GenerateOnePassVersion(false).Encode(strmCompressedOut); // Create the Literal Data generator output stream PgpLiteralDataGenerator PGP_LiteralDataGenerator = new PgpLiteralDataGenerator(); System.IO.FileInfo fiEmbeddedFile = new System.IO.FileInfo(strEmbeddedFileName); System.IO.FileInfo fiActualFile = new System.IO.FileInfo(strActualFileName); // TODO: Use lastwritetime from source file System.IO.Stream strmLiteralOut = PGP_LiteralDataGenerator.Open(strmCompressedOut, PgpLiteralData.Binary, fiEmbeddedFile.Name, fiActualFile.LastWriteTime, new byte[iBUFFER_SIZE]); // Open the input file System.IO.FileStream strmInputStream = fiActualFile.OpenRead(); byte[] baBuffer = new byte[iBUFFER_SIZE]; int iReadLength; while ((iReadLength = strmInputStream.Read(baBuffer, 0, baBuffer.Length)) > 0) { strmLiteralOut.Write(baBuffer, 0, iReadLength); PGP_SignatureGenerator.Update(baBuffer, 0, iReadLength); } strmLiteralOut.Close(); PGP_LiteralDataGenerator.Close(); PGP_SignatureGenerator.Generate().Encode(strmCompressedOut); strmCompressedOut.Close(); PGP_CompressedDataGenerator.Close(); strmEncryptedOut.Close(); PGP_EncryptedDataGenerator.Close(); strmInputStream.Close(); if (bArmor) { strmOutputStream.Close(); } }
private static void EncryptPgp(Stream input, Stream output, Stream key, bool armor, bool integrityCheck) { try { // Find public key for encryption PgpPublicKey publicKey = null; PgpPublicKeyRingBundle pgpPublicKeyRingBundle = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(key)); foreach (PgpPublicKeyRing pkr in pgpPublicKeyRingBundle.GetKeyRings()) { foreach (PgpPublicKey pKey in pkr.GetPublicKeys()) { if (pKey.IsEncryptionKey) { publicKey = pKey; break; } } } if (publicKey == null) { throw new ArgumentException("Public key for encryption not found."); } MemoryStream inputMemory = new MemoryStream(); input.CopyTo(inputMemory); byte[] bytes = inputMemory.ToArray(); // clear data bytes inputMemory.Close(); MemoryStream compressedLiteral = new MemoryStream(); PgpCompressedDataGenerator pgpCompressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.BZip2); Stream compressed = pgpCompressedDataGenerator.Open(compressedLiteral); PgpLiteralDataGenerator pgpLiteralDataGenerator = new PgpLiteralDataGenerator(); Stream literal = pgpLiteralDataGenerator.Open(compressed, PgpLiteralData.Binary, "STREAM", bytes.Length, DateTime.UtcNow); literal.Write(bytes, 0, bytes.Length); pgpLiteralDataGenerator.Close(); pgpCompressedDataGenerator.Close(); PgpEncryptedDataGenerator pgpEncryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, integrityCheck, new SecureRandom()); pgpEncryptedDataGenerator.AddMethod(publicKey); bytes = compressedLiteral.ToArray(); // compressed literal data bytes MemoryStream encryptedMemory = new MemoryStream(); Stream os = encryptedMemory; // optional armor ASCII encoding if (armor) { os = new ArmoredOutputStream(os); } Stream encrypted = pgpEncryptedDataGenerator.Open(os, bytes.Length); encrypted.Write(bytes, 0, bytes.Length); encrypted.Close(); if (armor) { os.Close(); } encryptedMemory.Seek(0, SeekOrigin.Begin); Streams.PipeAll(encryptedMemory, output); encryptedMemory.Close(); Console.WriteLine("OpenPGP encryption successfull."); } catch (PgpException ex) { Console.Error.WriteLine(ex); Exception pgpInnerException = ex.InnerException; if (pgpInnerException != null) { Console.Error.WriteLine(pgpInnerException.Message); Console.Error.WriteLine(pgpInnerException.StackTrace); } } }
/** * Generated signature test * * @param sKey * @param pgpPrivKey * @return test result */ public void GenerateTest( PgpSecretKeyRing sKey, PgpPublicKey pgpPubKey, PgpPrivateKey pgpPrivKey) { string data = "hello world!"; MemoryStream bOut = new MemoryStream(); byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator(); enumerator.MoveNext(); string primaryUserId = (string)enumerator.Current; spGen.SetSignerUserId(true, primaryUserId); sGen.SetHashedSubpackets(spGen.Generate()); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pgpPubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } }
private byte[] GetEncryptedData(byte[] data) { var baos = new MemoryStream(); var outStr = new ArmoredOutputStream(baos); PgpPublicKey publicKey = null; var inputStream = PgpUtilities.GetDecoderStream(new MemoryStream(_encryptionKey)); var pgpPub = new PgpPublicKeyRingBundle(inputStream); for (var i = pgpPub.GetKeyRings().GetEnumerator(); i.MoveNext();) { var pgpPublicKeyRing = (PgpPublicKeyRing)i.Current; if (pgpPublicKeyRing != null) { for (var j = pgpPublicKeyRing.GetPublicKeys().GetEnumerator(); publicKey == null && j.MoveNext();) { var k = (PgpPublicKey)j.Current; if (k != null && k.IsEncryptionKey) { publicKey = k; } } } } if (publicKey == null) { throw new Exception("Can't find encryption key in key ring."); } var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(_signingKey))); PgpPrivateKey privateKey = null; PgpSecretKey secretKey = null; for (var i = pgpSec.GetKeyRings().GetEnumerator(); privateKey == null && i.MoveNext();) { var keyRing = (PgpSecretKeyRing)i.Current; if (keyRing != null) { for (var j = keyRing.GetSecretKeys().GetEnumerator(); j.MoveNext();) { secretKey = (PgpSecretKey)j.Current; if (secretKey != null) { privateKey = secretKey.ExtractPrivateKey(_password); } break; } } } if (secretKey == null) { throw new Exception("Can't find signature key in key ring."); } var cb = new MemoryStream(); var compressedGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); var compressedOut = compressedGenerator.Open(cb); var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512); signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey); for (var i = secretKey.PublicKey.GetUserIds().GetEnumerator(); i.MoveNext();) { var spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, (String)i.Current); signatureGenerator.SetHashedSubpackets(spGen.Generate()); } signatureGenerator.GenerateOnePassVersion(true).Encode(compressedOut); var lgen = new PgpLiteralDataGenerator(); var finalOut = lgen.Open(compressedOut, PgpLiteralData.Binary, "", DateTime.Now, new byte[4096]); finalOut.Write(data, 0, data.Length); signatureGenerator.Update(data); finalOut.Close(); lgen.Close(); signatureGenerator.Generate().Encode(compressedOut); compressedGenerator.Close(); compressedOut.Close(); var compressedData = cb.ToArray(); var encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom()); encryptedDataGenerator.AddMethod(publicKey); var encryptedOut = encryptedDataGenerator.Open(outStr, compressedData.Length); encryptedOut.Write(compressedData, 0, compressedData.Length); encryptedOut.Close(); encryptedDataGenerator.Close(); outStr.Close(); return(baos.ToArray()); }
public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } }
public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } }
private void doTestTextSigV3( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, IPgpPrivateKey privKey, byte[] data, byte[] canonicalData) { PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(data, false); sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Text, "_CONSOLE", data.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(data, 0, data.Length); sGen.Update(data); lGen.Close(); PgpSignature sig = sGen.Generate(); if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0)) { Fail("creation time not set in v3 signature"); } sig.Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData); }
/** * Generated signature test * * @param sKey * @param pgpPrivKey * @return test result */ public void GenerateTest( PgpSecretKeyRing sKey, IPgpPublicKey pgpPubKey, IPgpPrivateKey pgpPrivKey) { string data = "hello world!"; MemoryStream bOut = new MemoryStream(); byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator(); enumerator.MoveNext(); string primaryUserId = (string) enumerator.Current; spGen.SetSignerUserId(true, primaryUserId); sGen.SetHashedSubpackets(spGen.Generate()); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData) pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pgpPubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte) ch); } PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); var pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); IPgpSecretKey secretKey = sKey.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte) ch); } PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData) pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) Fail("null signature found"); sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) Fail("null user attribute found"); count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
private void MixedTest( PgpPrivateKey pgpPrivKey, PgpPublicKey pgpPubKey) { byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // literal data // MemoryStream bOut = new MemoryStream(); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( bOut, PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, DateTime.UtcNow); lOut.Write(text, 0, text.Length); lGen.Close(); byte[] bytes = bOut.ToArray(); PgpObjectFactory f = new PgpObjectFactory(bytes); CheckLiteralData((PgpLiteralData)f.NextPgpObject(), text); MemoryStream bcOut = new MemoryStream(); PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Aes128, true, new SecureRandom()); encGen.AddMethod(pgpPubKey); encGen.AddMethod("password".ToCharArray(), HashAlgorithmTag.Sha1); Stream cOut = encGen.Open(bcOut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); byte[] encData = bcOut.ToArray(); // // asymmetric // PgpObjectFactory pgpF = new PgpObjectFactory(encData); PgpEncryptedDataList encList = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData)pgpFact.NextPgpObject(), text); // // PBE // pgpF = new PgpObjectFactory(encData); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1]; clear = encPbe.GetDataStream("password".ToCharArray()); pgpF = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text); }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) { Fail("null signature found"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) { Fail("null user attribute found"); } count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
private byte[] generateV3BinarySig( IPgpPrivateKey privKey, PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm) { MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(TEST_DATA, false); PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, "_CONSOLE", TEST_DATA.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(TEST_DATA, 0, TEST_DATA.Length); sGen.Update(TEST_DATA); lGen.Close(); sGen.Generate().Encode(bOut); return bOut.ToArray(); }
void SignAndEncryptFile() { const int BUFFER_SIZE = 1 << 16; // should always be power of 2 var OutStream = OutFile.OpenWrite(); PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, WithIntegrityCheck, new SecureRandom()); foreach (var publicKey in PublicKeys) { var encKey = ReadPublicKey(publicKey); encryptedDataGenerator.AddMethod(encKey); } Stream outputStream = OutStream; if (Armor) { outputStream = new ArmoredOutputStream(outputStream); } Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]); if (Compress) { // Init compression PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); encryptedOut = compressedDataGenerator.Open(encryptedOut); } //signing List <PgpSignatureGenerator> pgpSignatureGenerators = new List <PgpSignatureGenerator>(); foreach (var privateKeyInfo in PrivateKeys) { PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyInfo.PrivateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(privateKeyInfo.PrivateKeyPassword == null ? null : privateKeyInfo.PrivateKeyPassword.ToCharArray()); PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); foreach (string userId in pgpSecKey.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(spGen.Generate()); // Just the first one! break; } signatureGenerator.GenerateOnePassVersion(false).Encode(encryptedOut); pgpSignatureGenerators.Add(signatureGenerator); } // Create the Literal Data generator output stream PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); Stream literalOut = literalDataGenerator.Open(encryptedOut, PgpLiteralData.Binary, InFile.Name, InFile.LastWriteTime, new byte[BUFFER_SIZE]); // Open the input file FileStream inputStream = InFile.OpenRead(); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buf, 0, buf.Length)) > 0) { literalOut.Write(buf, 0, len); foreach (var signatureGenerator in pgpSignatureGenerators) { signatureGenerator.Update(buf, 0, len); } } literalOut.Close(); literalDataGenerator.Close(); foreach (var signatureGenerator in pgpSignatureGenerators) { signatureGenerator.Generate().Encode(encryptedOut); } encryptedOut.Close(); encryptedOut.Close(); encryptedDataGenerator.Close(); inputStream.Close(); if (Armor) { outputStream.Close(); } OutStream.Close(); }