public override void Encode(BcpgOutputStream pOut) { SymmetricKeyEncSessionPacket pk = new SymmetricKeyEncSessionPacket( encAlgorithm, s2k, sessionInfo); pOut.WritePacket(pk); }
/// <summary> /// Close the literal data packet - this is equivalent to calling Close() /// on the stream returned by the Open() method. /// </summary> public void Close() { if (_pkOut != null) { _pkOut.Finish(); _pkOut.Flush(); _pkOut = null; } }
/// <summary> /// Close the literal data packet - this is equivalent to calling Close() /// on the stream returned by the Open() method. /// </summary> public void Close() { if (pkOut != null) { pkOut.Finish(); pkOut.Flush(); pkOut = null; } }
/// <summary> /// Close the literal data packet - this is equivalent to calling Close() /// on the stream returned by the Open() method. /// </summary> public void Close() { if (_pkOut == null) return; _pkOut.Finish(); _pkOut.Flush(); _pkOut = null; }
private void WriteHeader(BcpgOutputStream outStr, char format, string name, long modificationTime) { byte[] encName = Strings.ToUtf8ByteArray(name); outStr.Write((byte) format, (byte) encName.Length); outStr.Write(encName); long modDate = modificationTime/1000L; outStr.Write((byte) (modDate >> 24), (byte) (modDate >> 16), (byte) (modDate >> 8), (byte) modDate); }
/// <summary> /// <p> /// Return an output stream which will save the data being written to /// the compressed object. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// </summary> /// <param name="outStr">Stream to be used for output.</param> /// <returns>A Stream for output of the compressed data.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="IOException"></exception> public Stream Open( Stream outStr) { if (dOut != null) throw new InvalidOperationException("generator already in open state"); if (outStr == null) throw new ArgumentNullException("outStr"); this.pkOut = new BcpgOutputStream(outStr, PacketTag.CompressedData); doOpen(); return new WrappedGeneratorStream(this, dOut); }
/// <summary>Close the compressed object.</summary> /// summary> public void Close() { if (_dOut != null) { if (_dOut != _pkOut) { _dOut.Flush(); _dOut.Dispose(); } _dOut = null; _pkOut.Finish(); _pkOut.Flush(); _pkOut = null; } }
/// <summary>Close the compressed object.</summary>summary> public void Close() { if (dOut != null) { if (dOut != pkOut) { dOut.Dispose(); dOut.Flush(); } dOut = null; pkOut.Finish(); pkOut.Flush(); pkOut = null; } }
/// <summary>Close the compressed object.</summary>summary> public void Close() { if (_dOut == null) return; if (_dOut != _pkOut) { _dOut.Flush(); #if !NETFX_CORE _dOut.Close(); #endif } _dOut = null; _pkOut.Finish(); _pkOut.Flush(); _pkOut = null; }
/// <summary> /// Open a literal data packet, returning a stream to store the data inside the packet. /// The stream can be closed off by calling Close() on either the stream or the generator. /// </summary> /// <param name="outStr">The stream we want the packet in.</param> /// <param name="format">The format we are using.</param> /// <param name="name">The name of the 'file'.</param> /// <param name="length">The length of the data we will write.</param> /// <param name="modificationTime">The time of last modification we want stored.</param> public Stream Open( Stream outStr, char format, string name, long length, DateTime modificationTime) { if (pkOut != null) throw new InvalidOperationException("generator already in open state"); if (outStr == null) throw new ArgumentNullException("outStr"); // Do this first, since it might throw an exception long unixMs = DateTimeUtilities.DateTimeToUnixMs(modificationTime); pkOut = new BcpgOutputStream(outStr, PacketTag.LiteralData, length + 2 + name.Length + 4, oldFormat); WriteHeader(pkOut, format, name, unixMs); return new WrappedGeneratorStream(this, pkOut); }
private static string CreateSignature( string message, Stream keyIn, Stream outputStream, char[] pass, bool armor) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); } PgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator( pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); BcpgOutputStream bOut = new BcpgOutputStream(outputStream); sGen.Update(System.Text.Encoding.UTF8.GetBytes(message)); PgpSignature sig = sGen.Generate(); sig.Encode(bOut); if (armor) { outputStream.Close(); } MemoryStream ms = new MemoryStream(); sig.Encode(ms); byte[] bytes = ms.ToArray(); return(Convert.ToBase64String(bytes)); }
/// <summary> /// <p> /// Close off the encrypted object - this is equivalent to calling Close() on the stream /// returned by the Open() method. /// </p> /// <p> /// <b>Note</b>: This does not close the underlying output stream, only the stream on top of /// it created by the Open() method. /// </p> /// </summary> public void Close() { if (cOut != null) { // TODO Should this all be under the try/catch block? if (digestOut != null) { // // hand code a mod detection packet // BcpgOutputStream bOut = new BcpgOutputStream( digestOut, PacketTag.ModificationDetectionCode, 20); bOut.Flush(); digestOut.Flush(); // TODO byte[] dig = DigestUtilities.DoFinal(digestOut.WriteDigest()); cOut.Write(dig, 0, dig.Length); } cOut.Flush(); try { pOut.Write(c.DoFinal()); pOut.Finish(); } catch (Exception e) { throw new IOException(e.Message, e); } cOut = null; pOut = null; } }
/// <summary>Close the compressed object.</summary>summary> public void Close() { if (dOut != null) { switch (algorithm) { case CompressionAlgorithmTag.BZip2: ((CBZip2OutputStream) dOut).Finish(); break; case CompressionAlgorithmTag.Zip: case CompressionAlgorithmTag.ZLib: ((ZDeflaterOutputStream) dOut).Finish(); break; } dOut.Flush(); pkOut.Finish(); pkOut.Flush(); dOut = null; pkOut = null; } }
bool TestPrivateKey(PgpPublicKey publicKey, PgpPrivateKey privateKey) { try { byte[] testData = Encoding.ASCII.GetBytes("testdata"); var signature = ""; using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); using (var bOut = new BcpgOutputStream(s)) { var sGen = new PgpSignatureGenerator(publicKey.Algorithm, HashAlgorithmTag.Sha512); sGen.InitSign(PgpSignature.BinaryDocument, privateKey); sGen.Update(testData); sGen.Generate().Encode(bOut); s.Close(); ms.Seek(0, SeekOrigin.Begin); signature = Encoding.UTF8.GetString(ms.ToArray()); } } return(VerifySignature(testData, signature, publicKey)); } catch (Exception e) { Logger.Error(PGPManagerLog, $"Error verifing private key: {e}"); return(false); } }
public override void Encode(BcpgOutputStream pOut) { PublicKeyEncSessionPacket pk = new PublicKeyEncSessionPacket( pubKey.KeyId, pubKey.Algorithm, data); pOut.WritePacket(pk); }
public override void PerformTest() { // // Read the public key // PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing); PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject(); var pubKey = pgpPub.GetPublicKey(); if (pubKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing); IPgpSecretKey secretKey = sKey.GetSecretKey(); IPgpPrivateKey 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; IAsymmetricKeyParameter 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); IPgpPublicKey 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 // IBigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); IBigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); IAsymmetricCipherKeyPair 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."); // } } } }
public abstract void Encode(BcpgOutputStream bcpgOut);
/* * 文章 -> hash -> 私鑰(自己)簽章 -> 簽章後的hash值 * 文章 - - - - - - - - - - - - - -> 文章 */ /*.......................................................................數位簽章開始*/ 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); //匯出位置、headers、雜湊表 } PgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn); //PgpSecretKey包含私鑰及公鑰整個物件 PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass); //需輸入私鑰密碼才能取出私鑰 /* * SHA是由美國國家安全局制定,主要應用於數字簽名標準裡面的數字簽名算法( DSA : Digital Signature Algorithm ), * SHA家族中以SHA1和SHA256最為廣泛使用。SHA1的雜湊值長度為160bit、SHA256則為256bit,長度越長碰撞的機會就越低也越安全, * 但同時計算的時間複雜度也隨著增高。 */ PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256); //PublicKey.Algorithm即原始公鑰 sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); //若沒私鑰重新生產一個 foreach (string userId in pgpSec.PublicKey.GetUserIds()) //ExportKeyPair 的 identity (MarkWu) { PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, userId); //數位簽章的使用者 sGen.SetHashedSubpackets(spGen.Generate()); //將 SignatureSubpacket 陣列化再回傳 // 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); //hash 加密 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(); } }
/// <summary> /// Create a file with PGP clear text signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpClearTextSignature Returns: Object {string FilePath} /// </summary> public static Result PGPClearTextSignFile(Input input) { HashAlgorithmTag digest; if (input.HashFunction == HashFunctionType.MD5) { digest = HashAlgorithmTag.MD5; } else if (input.HashFunction == HashFunctionType.RipeMD160) { digest = HashAlgorithmTag.RipeMD160; } else if (input.HashFunction == HashFunctionType.Sha1) { digest = HashAlgorithmTag.Sha1; } else if (input.HashFunction == HashFunctionType.Sha224) { digest = HashAlgorithmTag.Sha224; } else if (input.HashFunction == HashFunctionType.Sha384) { digest = HashAlgorithmTag.Sha384; } else if (input.HashFunction == HashFunctionType.Sha512) { digest = HashAlgorithmTag.Sha512; } else { digest = HashAlgorithmTag.Sha256; } Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile); PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(input.InputFile); Stream outputStream = File.Create(input.OutputFile); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return(ret); }
private void generateTest( string message, string type) { PgpSecretKey pgpSecKey = ReadSecretKey(new MemoryStream(secretKey)); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey("".ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator it = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (it.MoveNext()) { spGen.SetSignerUserId(false, (string)it.Current); sGen.SetHashedSubpackets(spGen.Generate()); } MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(message), false); aOut.BeginClearText(HashAlgorithmTag.Sha256); // // note the last \n m_in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, bIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, bIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } aOut.EndClearText(); BcpgOutputStream bcpgOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bcpgOut); aOut.Close(); byte[] bs = bOut.ToArray(); messageTest(Encoding.ASCII.GetString(bs, 0, bs.Length), type); }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey(); IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator(); enumerator.MoveNext(); string uid = (string) enumerator.Current; enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); PgpSignature sig = (PgpSignature) enumerator.Current; sig.InitVerify(pgpPub.GetPublicKey()); if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey())) { Fail("failed to verify certification"); } // // write a public key // MemoryStream bOut = new UncloseableMemoryStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pgpPub.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPubKey)) { Fail("public key rewrite failed"); } // // Read the public key // PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3); AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey(); // // write a V3 public key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPubV3.Encode(pOut); // // Read a v3 private key // char[] passP = "FIXCITY_QA".ToCharArray(); { PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3); PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey(); PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP); // // write a v3 private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv2.Encode(pOut); byte[] result = bOut.ToArray(); if (!Arrays.AreEqual(result, testPrivKeyV3)) { Fail("private key V3 rewrite failed"); } } // // Read the private key // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass); // // write a private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey)) { Fail("private key rewrite failed"); } // // test encryption // IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.Init(Cipher.ENCRYPT_MODE, pubKey); c.Init(true, pubKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); // c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey()); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // 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(pgpPub.GetPublicKey(ops.KeyId)); 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"); } // // encrypted message - read subkey // pgpPriv = new PgpSecretKeyRing(subKey); // // encrypted message // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); PgpObjectFactory pgpF = new PgpObjectFactory(enc1); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); 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"); } // // encrypt - short message // byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), shortText.Length); cOut.Write(shortText, 0, shortText.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5) { Fail("symmetric algorithm mismatch"); } clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, shortText)) { Fail("wrong plain text in generated short text packet"); } // // encrypt // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); 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 = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in generated packet"); } // // read public key with sub key. // pgpF = new PgpObjectFactory(subPubKey); object o; while ((o = pgpFact.NextPgpObject()) != null) { // TODO Should something be tested here? // Console.WriteLine(o); } // // key pair generation - CAST5 encryption // char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25); kpg.Init(genParam); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom() ); PgpPublicKey key = secretKey.PublicKey; enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase); key = PgpPublicKey.RemoveCertification(key, uid, sig); if (key == null) { Fail("failed certification removal"); } byte[] keyEnc = key.GetEncoded(); key = PgpPublicKey.AddCertification(key, uid, sig); keyEnc = key.GetEncoded(); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase)); sig = sGen.GenerateCertification(key); key = PgpPublicKey.AddCertification(key, sig); keyEnc = key.GetEncoded(); PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc); key = tmpRing.GetPublicKey(); IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator(); sgEnum.MoveNext(); sig = (PgpSignature) sgEnum.Current; sig.InitVerify(key); if (!sig.VerifyCertification(key)) { Fail("failed to verify revocation certification"); } // // use of PgpKeyPair // PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; k1.GetEncoded(); MixedTest(k2, k1); // // key pair generation - AES_256 encryption. // kp = kpg.GenerateKeyPair(); secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); secretKey.ExtractPrivateKey(passPhrase); secretKey.Encode(new UncloseableMemoryStream()); // // secret key password changing. // const string newPass = "******"; secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom()); secretKey.ExtractPrivateKey(newPass.ToCharArray()); secretKey.Encode(new UncloseableMemoryStream()); key = secretKey.PublicKey; key.Encode(new UncloseableMemoryStream()); enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray()); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, 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); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // 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(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // signature generation - version 3 // bOut = new UncloseableMemoryStream(); testIn = new MemoryStream(dataBytes); PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); lGen = new PgpLiteralDataGenerator(); lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // 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(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed v3 generated signature check"); } // // extract PGP 8 private key // pgpPriv = new PgpSecretKeyRing(pgp8Key); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass); // // other sig tests // PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); FingerPrintTest(); ExistingEmbeddedJpegTest(); EmbeddedJpegTest(); }
/* * create a clear text signed file. */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, string digestName) { HashAlgorithmTag digest; if (digestName.Equals("SHA256")) { digest = HashAlgorithmTag.Sha256; } else if (digestName.Equals("SHA384")) { digest = HashAlgorithmTag.Sha384; } else if (digestName.Equals("SHA512")) { digest = HashAlgorithmTag.Sha512; } else if (digestName.Equals("MD5")) { digest = HashAlgorithmTag.MD5; } else if (digestName.Equals("RIPEMD160")) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha1; } PgpSecretKey pgpSecKey = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string) enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(fileName); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); }
/// <summary> /// Signs the specified byte array using the specified key after unlocking the key with the specified passphrase. /// </summary> /// <param name="bytes">The byte array containing the payload to sign.</param> /// <param name="key">The PGP key to be used to sign the payload.</param> /// <param name="passphrase">The passphrase used to unlock the PGP key.</param> /// <returns>A byte array containing the generated PGP signature.</returns> public static byte[] Sign(byte[] bytes, string key, string passphrase) { // prepare a memory stream to hold the signature MemoryStream memoryStream = new MemoryStream(); // prepare an armored output stream to produce an armored ASCII signature Stream outputStream = new ArmoredOutputStream(memoryStream); // retrieve the keys PgpSecretKey secretKey = ReadSecretKeyFromString(key); PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passphrase.ToCharArray()); // create and initialize a signature generator PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512); signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey); // retrieve the first user id contained within the public key and use it to set the signature signer foreach (string userId in secretKey.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureSubpacketGenerator.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); break; } // prepare a compressed data generator and compressed output stream to compress the data PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib); Stream compressedOutputStream = compressedDataGenerator.Open(outputStream); // generate the signature taken pretty much verbatim from the bouncycastle example; not sure what all of it does. BcpgOutputStream bcpgOutputStream = new BcpgOutputStream(compressedOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcpgOutputStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); Stream literalOutputStream = literalDataGenerator.Open(bcpgOutputStream, PgpLiteralData.Binary, "signatureData", DateTime.UtcNow, new byte[4092]); foreach (byte b in bytes) { literalOutputStream.WriteByte(b); signatureGenerator.Update(b); } literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcpgOutputStream); compressedDataGenerator.Close(); outputStream.Close(); // fetch a byte array containing the contents of the memory stream byte[] retVal = memoryStream.ToArray(); // close the memory stream memoryStream.Close(); // return the generated signature return(retVal); }
/// <summary> /// <p> /// Return an output stream which will compress the data as it is written to it. /// The stream will be written out in chunks according to the size of the passed in buffer. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// <p> /// <b>Note</b>: if the buffer is not a power of 2 in length only the largest power of 2 /// bytes worth of the buffer will be used. /// </p> /// <p> /// <b>Note</b>: using this may break compatibility with RFC 1991 compliant tools. /// Only recent OpenPGP implementations are capable of accepting these streams. /// </p> /// </summary> /// <param name="outStr">Stream to be used for output.</param> /// <param name="buffer">The buffer to use.</param> /// <returns>A Stream for output of the compressed data.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="IOException"></exception> /// <exception cref="PgpException"></exception> public Stream Open(Stream outStr, byte[] buffer) { if (_dOut != null) { throw new InvalidOperationException("generator already in open state"); } if (outStr == null) { throw new ArgumentNullException("outStr"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } _pkOut = new BcpgOutputStream(outStr, PacketTag.CompressedData, buffer); DoOpen(); return new WrappedGeneratorStream(this, _dOut); }
/// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static Result PGPSignFile(Input input) { HashAlgorithmTag digest; if (input.HashFunction == HashFunctionType.MD5) { digest = HashAlgorithmTag.MD5; } else if (input.HashFunction == HashFunctionType.RipeMD160) { digest = HashAlgorithmTag.RipeMD160; } else if (input.HashFunction == HashFunctionType.Sha1) { digest = HashAlgorithmTag.Sha1; } else if (input.HashFunction == HashFunctionType.Sha224) { digest = HashAlgorithmTag.Sha224; } else if (input.HashFunction == HashFunctionType.Sha384) { digest = HashAlgorithmTag.Sha384; } else if (input.HashFunction == HashFunctionType.Sha512) { digest = HashAlgorithmTag.Sha512; } else { digest = HashAlgorithmTag.Sha256; } Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile); PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream outputStream = File.Create(input.OutputFile); ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream); BcpgOutputStream bOut = new BcpgOutputStream(armoredOutputStream); sGen.GenerateOnePassVersion(false).Encode(bOut); FileInfo file = new FileInfo(input.InputFile); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file); FileStream fIn = file.OpenRead(); int ch; while ((ch = fIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } fIn.Close(); lGen.Close(); sGen.Generate().Encode(bOut); armoredOutputStream.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return(ret); }
/* * create a clear text signed file. */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, string digestName) { HashAlgorithmTag digest; if (digestName.Equals("SHA256")) { digest = HashAlgorithmTag.Sha256; } else if (digestName.Equals("SHA384")) { digest = HashAlgorithmTag.Sha384; } else if (digestName.Equals("SHA512")) { digest = HashAlgorithmTag.Sha512; } else if (digestName.Equals("MD5")) { digest = HashAlgorithmTag.MD5; } else if (digestName.Equals("RIPEMD160")) { digest = HashAlgorithmTag.RipeMD160; } else { digest = HashAlgorithmTag.Sha1; } PgpSecretKey pgpSecKey = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { spGen.SetSignerUserId(false, (string)enumerator.Current); sGen.SetHashedSubpackets(spGen.Generate()); } Stream fIn = File.OpenRead(fileName); ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream); aOut.BeginClearText(digest); // // note the last \n/\r/\r\n in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, fIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, fIn); sGen.Update((byte)'\r'); sGen.Update((byte)'\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); }while (lookAhead != -1); } fIn.Close(); aOut.EndClearText(); BcpgOutputStream bOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bOut); aOut.Close(); }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WriteShort((short)val.BitLength); bcpgOut.Write(val.ToByteArrayUnsigned()); }
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; }
internal static void Encode(BcpgOutputStream bcpgOut, BigInteger val) { bcpgOut.WriteShort((short)val.BitLength); bcpgOut.Write(val.ToByteArrayUnsigned()); }
/** * Generate an encapsulated signed file. * * @param fileName * @param keyIn * @param outputStream * @param pass * @param armor */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, bool armor, bool compress) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); } PgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn); PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1); 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(); } }
/// <summary>Close the compressed object.</summary>summary> public void Close() { if (dOut != null) { if (dOut != pkOut) { Platform.Dispose(dOut); } dOut = null; pkOut.Finish(); pkOut.Flush(); pkOut = null; } }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WriteObjects(d, p, q, u); }
private void PerformTestSig( HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); 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); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // 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(pubKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check - " + hashAlgorithm); } }
internal PgpSecretKey( PgpPrivateKey privKey, PgpPublicKey pubKey, SymmetricKeyAlgorithmTag encAlgorithm, char[] passPhrase, bool useSha1, SecureRandom rand, bool isMasterKey) { BcpgObject secKey; this.pub = pubKey; switch (pubKey.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaSign: case PublicKeyAlgorithmTag.RsaGeneral: RsaPrivateCrtKeyParameters rsK = (RsaPrivateCrtKeyParameters)privKey.Key; secKey = new RsaSecretBcpgKey(rsK.Exponent, rsK.P, rsK.Q); break; case PublicKeyAlgorithmTag.Dsa: DsaPrivateKeyParameters dsK = (DsaPrivateKeyParameters)privKey.Key; secKey = new DsaSecretBcpgKey(dsK.X); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPrivateKeyParameters esK = (ElGamalPrivateKeyParameters)privKey.Key; secKey = new ElGamalSecretBcpgKey(esK.X); break; default: throw new PgpException("unknown key class"); } try { MemoryStream bOut = new MemoryStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pOut.WriteObject(secKey); byte[] keyData = bOut.ToArray(); byte[] checksumData = Checksum(useSha1, keyData, keyData.Length); keyData = Arrays.Concatenate(keyData, checksumData); if (encAlgorithm == SymmetricKeyAlgorithmTag.Null) { if (isMasterKey) { this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, null, null, keyData); } else { this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, null, null, keyData); } } else { S2k s2k; byte[] iv; byte[] encData; if (pub.Version >= 4) { encData = EncryptKeyData(keyData, encAlgorithm, passPhrase, rand, out s2k, out iv); } else { // TODO v3 RSA key encryption throw Platform.CreateNotImplementedException("v3 RSA"); } int s2kUsage = useSha1 ? SecretKeyPacket.UsageSha1 : SecretKeyPacket.UsageChecksum; if (isMasterKey) { this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData); } else { this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData); } } } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception encrypting key", e); } }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WriteObjects(p, g, y); }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WritePacket(PacketTag.ModificationDetectionCode, digest, oldFormat: false); }
/** * Generate an encapsulated signed file. * * @param fileName * @param keyIn * @param outputStream * @param pass * @param armor */ private static void SignFile( string fileName, Stream keyIn, Stream outputStream, char[] pass, bool armor, bool compress) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); } IPgpSecretKey pgpSec = PgpExampleUtilities.ReadSecretKey(keyIn); IPgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1); 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(); } }
internal PgpSecretKey( PgpPrivateKey privKey, PgpPublicKey pubKey, SymmetricKeyAlgorithmTag encAlgorithm, byte[] rawPassPhrase, bool clearPassPhrase, bool useSha1, SecureRandom rand, bool isMasterKey) { BcpgObject secKey; this.pub = pubKey; switch (pubKey.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaSign: case PublicKeyAlgorithmTag.RsaGeneral: RsaPrivateCrtKeyParameters rsK = (RsaPrivateCrtKeyParameters) privKey.Key; secKey = new RsaSecretBcpgKey(rsK.Exponent, rsK.P, rsK.Q); break; case PublicKeyAlgorithmTag.Dsa: DsaPrivateKeyParameters dsK = (DsaPrivateKeyParameters) privKey.Key; secKey = new DsaSecretBcpgKey(dsK.X); break; case PublicKeyAlgorithmTag.ECDH: case PublicKeyAlgorithmTag.ECDsa: ECPrivateKeyParameters ecK = (ECPrivateKeyParameters)privKey.Key; secKey = new ECSecretBcpgKey(ecK.D); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPrivateKeyParameters esK = (ElGamalPrivateKeyParameters) privKey.Key; secKey = new ElGamalSecretBcpgKey(esK.X); break; default: throw new PgpException("unknown key class"); } try { MemoryStream bOut = new MemoryStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pOut.WriteObject(secKey); byte[] keyData = bOut.ToArray(); byte[] checksumData = Checksum(useSha1, keyData, keyData.Length); keyData = Arrays.Concatenate(keyData, checksumData); if (encAlgorithm == SymmetricKeyAlgorithmTag.Null) { if (isMasterKey) { this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, null, null, keyData); } else { this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, null, null, keyData); } } else { S2k s2k; byte[] iv; byte[] encData; if (pub.Version >= 4) { encData = EncryptKeyDataV4(keyData, encAlgorithm, HashAlgorithmTag.Sha1, rawPassPhrase, clearPassPhrase, rand, out s2k, out iv); } else { encData = EncryptKeyDataV3(keyData, encAlgorithm, rawPassPhrase, clearPassPhrase, rand, out s2k, out iv); } int s2kUsage = useSha1 ? SecretKeyPacket.UsageSha1 : SecretKeyPacket.UsageChecksum; if (isMasterKey) { this.secret = new SecretKeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData); } else { this.secret = new SecretSubkeyPacket(pub.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData); } } } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception encrypting key", e); } }
/// <summary> /// Sign data using key /// </summary> /// <param name="data">Data to sign</param> /// <param name="key">Email address of key</param> /// <returns>Returns ascii armored signature</returns> public string SignClear(string data, string key, Encoding encoding, Dictionary <string, string> headers) { Context = new CryptoContext(Context); var senderKey = GetSecretKeyForSigning(key); if (senderKey == null) { throw new SecretKeyNotFoundException("Error, unable to locate signing key \"" + key + "\"."); } // Setup signature stuff // var signatureData = new PgpSignatureGenerator(senderKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); signatureData.InitSign(PgpSignature.CanonicalTextDocument, senderKey.ExtractPrivateKey(Context.Password)); foreach (string userId in senderKey.PublicKey.GetUserIds()) { var subPacketGenerator = new PgpSignatureSubpacketGenerator(); subPacketGenerator.SetSignerUserId(false, userId); signatureData.SetHashedSubpackets(subPacketGenerator.Generate()); // Just the first one! break; } // // using (var sout = new MemoryStream()) { using (var armoredOut = new ArmoredOutputStream(sout)) { foreach (var header in headers) { armoredOut.SetHeader(header.Key, header.Value); } armoredOut.BeginClearText(HashAlgorithmTag.Sha1); // Remove any extra trailing whitespace. // this should not include \r or \n. data = data.TrimEnd(null); using (var stringReader = new StringReader(data)) { do { var line = stringReader.ReadLine(); if (line == null) { break; } // Lines must have all white space removed line = line.TrimEnd(null); line = line.TrimEnd(new char[] { ' ', '\t', '\r', '\n' }); line += "\r\n"; signatureData.Update(encoding.GetBytes(line)); armoredOut.Write(encoding.GetBytes(line)); }while (true); } // Write extra line before signature block. armoredOut.Write(encoding.GetBytes("\r\n")); armoredOut.EndClearText(); using (var outputStream = new BcpgOutputStream(armoredOut)) { signatureData.Generate().Encode(outputStream); } } return(encoding.GetString(sout.ToArray())); } }
/// <summary> /// <p> /// If buffer is non null stream assumed to be partial, otherwise the length will be used /// to output a fixed length packet. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// </summary> private Stream Open( Stream outStr, long length, byte[] buffer) { if (cOut != null) throw new InvalidOperationException("generator already in open state"); if (methods.Count == 0) throw new InvalidOperationException("No encryption methods specified"); if (outStr == null) throw new ArgumentNullException("outStr"); pOut = new BcpgOutputStream(outStr); KeyParameter key; if (methods.Count == 1) { if (methods[0] is PbeMethod) { PbeMethod m = (PbeMethod)methods[0]; key = m.GetKey(); } else { key = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key); PubMethod m = (PubMethod)methods[0]; try { m.AddSessionInfo(sessionInfo, rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } } pOut.WritePacket((ContainedPacket)methods[0]); } else // multiple methods { key = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key); for (int i = 0; i != methods.Count; i++) { EncMethod m = (EncMethod)methods[i]; try { m.AddSessionInfo(sessionInfo, rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } pOut.WritePacket(m); } } string cName = PgpUtilities.GetSymmetricCipherName(defAlgorithm); if (cName == null) { throw new PgpException("null cipher specified"); } try { if (withIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } c = CipherUtilities.GetCipher(cName); // TODO Confirm the IV should be all zero bytes (not inLineIv - see below) byte[] iv = new byte[c.GetBlockSize()]; c.Init(true, new ParametersWithRandom(new ParametersWithIV(key, iv), rand)); if (buffer == null) { // // we have to Add block size + 2 for the Generated IV and + 1 + 22 if integrity protected // if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + c.GetBlockSize() + 2 + 1 + 22); pOut.WriteByte(1); // version number } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + c.GetBlockSize() + 2, oldFormat); } } else { if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer); pOut.WriteByte(1); // version number } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer); } } int blockSize = c.GetBlockSize(); byte[] inLineIv = new byte[blockSize + 2]; rand.NextBytes(inLineIv, 0, blockSize); Array.Copy(inLineIv, inLineIv.Length - 4, inLineIv, inLineIv.Length - 2, 2); Stream myOut = cOut = new CipherStream(pOut, null, c); if (withIntegrityPacket) { string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); myOut = digestOut = new DigestStream(myOut, null, digest); } myOut.Write(inLineIv, 0, inLineIv.Length); return new WrappedGeneratorStream(this, myOut); } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } }
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)); }
/** * 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"); } }
private void WriteHeader( BcpgOutputStream outStr, char format, string name, long modificationTime) { byte[] asciiName = Encoding.ASCII.GetBytes(name); outStr.Write( (byte) format, (byte) asciiName.Length); outStr.Write(asciiName); long modDate = modificationTime / 1000L; outStr.Write( (byte)(modDate >> 24), (byte)(modDate >> 16), (byte)(modDate >> 8), (byte)modDate); }
public override void Encode( BcpgOutputStream bcpgOut) { bcpgOut.WritePacket(tag, contents, true); }
public void Encode( Stream outStr) { BcpgOutputStream.Wrap(outStr).WritePacket(sigPack); }
/** * 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"); } }
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; }
/// <summary> /// <p> /// If buffer is non null stream assumed to be partial, otherwise the length will be used /// to output a fixed length packet. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// </summary> private Stream Open(Stream outStr, long length, byte[] buffer) { if (_cOut != null) { throw new InvalidOperationException("generator already in open state"); } if (_methods.Count == 0) { throw new InvalidOperationException("No encryption methods specified"); } if (outStr == null) { throw new ArgumentNullException("outStr"); } _pOut = new BcpgOutputStream(outStr); KeyParameter key; if (_methods.Count == 1) { var pbeMethod = _methods[0] as PbeMethod; if (pbeMethod != null) { key = pbeMethod.GetKey(); } else { var pubMethod = (PubMethod)_methods[0]; key = PgpUtilities.MakeRandomKey(_defAlgorithm, _rand); var sessionInfo = CreateSessionInfo(_defAlgorithm, key); try { pubMethod.AddSessionInfo(sessionInfo, _rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } } _pOut.WritePacket((ContainedPacket)_methods[0]); } else // multiple methods { key = PgpUtilities.MakeRandomKey(_defAlgorithm, _rand); var sessionInfo = CreateSessionInfo(_defAlgorithm, key); for (var i = 0; i != _methods.Count; i++) { var m = (EncMethod)_methods[i]; try { m.AddSessionInfo(sessionInfo, _rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } _pOut.WritePacket(m); } } var cName = PgpUtilities.GetSymmetricCipherName(_defAlgorithm); if (cName == null) { throw new PgpException("null cipher specified"); } try { if (_withIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } _c = CipherUtilities.GetCipher(cName); // TODO Confirm the IV should be all zero bytes (not inLineIv - see below) var iv = new byte[_c.GetBlockSize()]; _c.Init(true, new ParametersWithRandom(new ParametersWithIV(key, iv), _rand)); if (buffer == null) { // // we have to Add block size + 2 for the Generated IV and + 1 + 22 if integrity protected // if (_withIntegrityPacket) { _pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + _c.GetBlockSize() + 2 + 1 + 22); _pOut.WriteByte(1); // version number } else { _pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + _c.GetBlockSize() + 2, _oldFormat); } } else { if (_withIntegrityPacket) { _pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer); _pOut.WriteByte(1); // version number } else { _pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer); } } var blockSize = _c.GetBlockSize(); var inLineIv = new byte[blockSize + 2]; _rand.NextBytes(inLineIv, 0, blockSize); Array.Copy(inLineIv, inLineIv.Length - 4, inLineIv, inLineIv.Length - 2, 2); Stream myOut = _cOut = new CipherStream(_pOut, null, _c); if (_withIntegrityPacket) { var digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); var digest = DigestUtilities.GetDigest(digestName); myOut = _digestOut = new DigestStream(myOut, null, digest); } myOut.Write(inLineIv, 0, inLineIv.Length); return(new WrappedGeneratorStream(this, myOut)); } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } }
/** * Generates an encapsulated signed file. */ public void signMessage(Stream unsignedContent, Stream signedContent, bool armor) { if (armor) { // output will be BASE64 encoded signedContent = new ArmoredOutputStream(signedContent); } PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); try { BcpgOutputStream bcpgSignedContentOut = new BcpgOutputStream(compressedDataGenerator.Open(signedContent)); PgpPrivateKey pgpPrivateKey = secretKeyForSigning.ExtractPrivateKey(secretKeyPassword); PgpSignatureGenerator signatureGenerator = createSignatureGenerator(pgpPrivateKey); signatureGenerator.GenerateOnePassVersion(false).Encode(bcpgSignedContentOut); Stream literalDataOut = literalDataGenerator.Open(bcpgSignedContentOut, PgpLiteralData.Binary, "_CONSOLE", unsignedContent.Length, DateTime.Now); updateSignatureGeneratorWithInputBytes(unsignedContent, signatureGenerator, literalDataOut); signatureGenerator.Generate().Encode(bcpgSignedContentOut); } finally { literalDataGenerator.Close(); compressedDataGenerator.Close(); signedContent.Close(); } }
internal PgpSecretKey( PgpPrivateKey privKey, PgpPublicKey pubKey, SymmetricKeyAlgorithmTag encAlgorithm, char[] passPhrase, bool useSha1, ISecureRandom rand, bool isMasterKey) { BcpgObject secKey; _pub = pubKey; switch (pubKey.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaSign: case PublicKeyAlgorithmTag.RsaGeneral: var rsK = (RsaPrivateCrtKeyParameters)privKey.Key; secKey = new RsaSecretBcpgKey(rsK.Exponent, rsK.P, rsK.Q); break; case PublicKeyAlgorithmTag.Dsa: var dsK = (DsaPrivateKeyParameters)privKey.Key; secKey = new DsaSecretBcpgKey(dsK.X); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: var esK = (ElGamalPrivateKeyParameters)privKey.Key; secKey = new ElGamalSecretBcpgKey(esK.X); break; case PublicKeyAlgorithmTag.Ecdh: case PublicKeyAlgorithmTag.Ecdsa: var ecK = (ECPrivateKeyParameters)privKey.Key; secKey = new ECSecretBcpgKey(ecK.D); break; default: throw new PgpException("unknown key class"); } try { using (var bOut = new MemoryStream()) { using (var pOut = new BcpgOutputStream(bOut)) { pOut.WriteObject(secKey); var keyData = bOut.ToArray(); var checksumBytes = Checksum(useSha1, keyData, keyData.Length); pOut.Write(checksumBytes); var bOutData = bOut.ToArray(); if (encAlgorithm == SymmetricKeyAlgorithmTag.Null) { this._secret = isMasterKey ? new SecretKeyPacket(_pub.PublicKeyPacket, encAlgorithm, null, null, bOutData) : new SecretSubkeyPacket(_pub.PublicKeyPacket, encAlgorithm, null, null, bOutData); } else { S2k s2K; byte[] iv; var encData = EncryptKeyData(bOutData, encAlgorithm, passPhrase, rand, out s2K, out iv); var s2KUsage = useSha1 ? SecretKeyPacket.UsageSha1 : SecretKeyPacket.UsageChecksum; this._secret = isMasterKey ? new SecretKeyPacket(_pub.PublicKeyPacket, encAlgorithm, s2KUsage, s2K, iv, encData) : new SecretSubkeyPacket(_pub.PublicKeyPacket, encAlgorithm, s2KUsage, s2K, iv, encData); } } } } catch (PgpException) { throw; } catch (Exception e) { throw new PgpException("Exception encrypting key", e); } }
public override void Encode(BcpgOutputStream pOut) { PublicKeyEncSessionPacket pk = new PublicKeyEncSessionPacket(pubKey.KeyId, pubKey.Algorithm, data); pOut.WritePacket(pk); }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WritePacket(PacketTag.PublicSubkey, GetEncodedContents(), oldFormat: true); }
/// <summary> /// <p> /// Open a literal data packet, returning a stream to store the data inside the packet, /// as an indefinite length stream. The stream is written out as a series of partial /// packets with a chunk size determined by the size of the passed in buffer. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// <p> /// <b>Note</b>: if the buffer is not a power of 2 in length only the largest power of 2 /// bytes worth of the buffer will be used.</p> /// </summary> /// <param name="outStr">The stream we want the packet in.</param> /// <param name="format">The format we are using.</param> /// <param name="name">The name of the 'file'.</param> /// <param name="modificationTime">The time of last modification we want stored.</param> /// <param name="buffer">The buffer to use for collecting data to put into chunks.</param> public Stream Open( Stream outStr, char format, string name, DateTime modificationTime, byte[] buffer) { if (pkOut != null) throw new InvalidOperationException("generator already in open state"); if (outStr == null) throw new ArgumentNullException("outStr"); // Do this first, since it might throw an exception long unixMs = DateTimeUtilities.DateTimeToUnixMs(modificationTime); byte[] encName = Strings.ToUtf8ByteArray(name); pkOut = new BcpgOutputStream(outStr, PacketTag.LiteralData, buffer); WriteHeader(pkOut, format, encName, unixMs); return new WrappedGeneratorStream(this, pkOut); }
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 Stream Open(Stream outStr, long length, byte[] buffer) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (cOut != null) { throw new InvalidOperationException("generator already in open state"); } if (((global::System.Collections.ICollection)methods).get_Count() == 0) { throw new InvalidOperationException("No encryption methods specified"); } if (outStr == null) { throw new ArgumentNullException("outStr"); } pOut = new BcpgOutputStream(outStr); KeyParameter keyParameter; if (((global::System.Collections.ICollection)methods).get_Count() == 1) { if (methods.get_Item(0) is PbeMethod) { PbeMethod pbeMethod = (PbeMethod)methods.get_Item(0); keyParameter = pbeMethod.GetKey(); } else { keyParameter = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] si = CreateSessionInfo(defAlgorithm, keyParameter); PubMethod pubMethod = (PubMethod)methods.get_Item(0); try { pubMethod.AddSessionInfo(si, rand); } catch (global::System.Exception exception) { throw new PgpException("exception encrypting session key", exception); } } pOut.WritePacket((ContainedPacket)methods.get_Item(0)); } else { keyParameter = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] si2 = CreateSessionInfo(defAlgorithm, keyParameter); for (int i = 0; i != ((global::System.Collections.ICollection)methods).get_Count(); i++) { EncMethod encMethod = (EncMethod)methods.get_Item(i); try { encMethod.AddSessionInfo(si2, rand); } catch (global::System.Exception exception2) { throw new PgpException("exception encrypting session key", exception2); } pOut.WritePacket(encMethod); } } string symmetricCipherName = PgpUtilities.GetSymmetricCipherName(defAlgorithm); if (symmetricCipherName == null) { throw new PgpException("null cipher specified"); } try { symmetricCipherName = ((!withIntegrityPacket) ? (symmetricCipherName + "/OpenPGPCFB/NoPadding") : (symmetricCipherName + "/CFB/NoPadding")); c = CipherUtilities.GetCipher(symmetricCipherName); byte[] iv = new byte[c.GetBlockSize()]; c.Init(forEncryption: true, new ParametersWithRandom(new ParametersWithIV(keyParameter, iv), rand)); if (buffer == null) { if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + c.GetBlockSize() + 2 + 1 + 22); ((Stream)pOut).WriteByte((byte)1); } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + c.GetBlockSize() + 2, oldFormat); } } else if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer); ((Stream)pOut).WriteByte((byte)1); } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer); } int blockSize = c.GetBlockSize(); byte[] array = new byte[blockSize + 2]; rand.NextBytes(array, 0, blockSize); global::System.Array.Copy((global::System.Array)array, array.Length - 4, (global::System.Array)array, array.Length - 2, 2); Stream val = (Stream)(object)(cOut = new CipherStream((Stream)(object)pOut, null, c)); if (withIntegrityPacket) { string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); val = (Stream)(object)(digestOut = new DigestStream(val, null, digest)); } val.Write(array, 0, array.Length); return((Stream)(object)new WrappedGeneratorStream(this, val)); } catch (global::System.Exception exception3) { throw new PgpException("Exception creating cipher", exception3); } }
public override void Encode(BcpgOutputStream bcpgOut) { bcpgOut.WritePacket(PacketTag.Marker, marker, oldFormat: true); }
public override void Encode(BcpgOutputStream pOut) { SymmetricKeyEncSessionPacket p = new SymmetricKeyEncSessionPacket(encAlgorithm, s2k, sessionInfo); pOut.WritePacket(p); }