/** * decrypt the passed in message stream */ private byte[] DecryptMessage( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime); } Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bytes; }
public override void PerformTest() { // // test encrypted message // PgpObjectFactory pgpFact = new PgpObjectFactory(message1); if (pgpFact.NextPgpObject() is PgpMarker) { if (pgpFact.NextPgpObject() is PgpEncryptedDataList) { return; } else { Fail("error processing after marker."); } } // TODO Does this even get called? pgpFact = new PgpObjectFactory(message2); if (pgpFact.NextPgpObject() is PgpMarker) { if (!(pgpFact.NextPgpObject() is PgpEncryptedDataList)) { return; } else { Fail("error processing after marker."); } } }
private PgpObject GetClearCompressedMessage(PgpPublicKeyEncryptedData publicKeyED, ChoPGPEncryptionKeys encryptionKeys) { PgpObjectFactory clearFactory = GetClearDataStream(encryptionKeys.PrivateKey, publicKeyED); PgpObject message = clearFactory.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = clearFactory.NextPgpObject(); } return(message); }
public EncryptionKeys(string publicKeyText, Boolean isKey) { if (string.IsNullOrEmpty(publicKeyText)) { throw new ArgumentException("Public key string is NULL.", "publicKeyString"); } PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(Convert.FromBase64String(publicKeyText)); PgpPublicKeyRing pgpPublicKeyRing = (PgpPublicKeyRing)pgpObjectFactory.NextPgpObject(); PublicKey = pgpPublicKeyRing.GetPublicKey(); }
public String DecryptMessage(String encryptedMessage, char[] passPhrase) { // Remove the Base64 encoding byte[] rawMessage = Convert.FromBase64String(encryptedMessage); Stream inputStream = new MemoryStream(rawMessage); inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc = null; PgpObject o = pgpF.NextPgpObject(); // // the first object might be a PGP marker packet. // if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); String message; using (StreamReader reader = new StreamReader(unc, Encoding.UTF8)) { message = reader.ReadToEnd(); } // Finally verify the integrity if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit."); } } return(message); }
public void Add(string hash, byte[] rawSignature) { using (MemoryStream stream = new MemoryStream(rawSignature)) using (var signatureStream = PgpUtilities.GetDecoderStream(stream)) { PgpObjectFactory pgpFactory = new PgpObjectFactory(signatureStream); PgpSignatureList signatureList = (PgpSignatureList)pgpFactory.NextPgpObject(); PgpSignature signature = signatureList[0]; this.Signatures.Add(hash, signature); } }
public void decrypt(Stream input, string outputpath) { input = PgpUtilities.GetDecoderStream(input); try { PgpObjectFactory pgpObjF = new PgpObjectFactory(input); PgpEncryptedDataList enc; PgpObject obj = pgpObjF.NextPgpObject(); if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else { enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject(); } PgpPrivateKey privKey = _decryptionKeys.PrivateKey; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { if (privKey != null) { pbe = pked; break; } } Stream clear = pbe.GetDataStream(privKey); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpObject message = plainFact.NextPgpObject(); if (message is PgpOnePassSignatureList) { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream output = File.Create(outputpath + "\\" + Ld.FileName); Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream output = File.Create(outputpath + "\\" + Ld.FileName); Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } catch (Exception e) { throw new Exception(e.Message); } }
private void DoTestSignedEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey); PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject(); PgpOnePassSignature ops = sList[0]; PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } Stream dIn = lData.GetInputStream(); ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } }
/// <summary> /// Gets a PGP signature. /// </summary> /// <param name="tag"> /// The tag which contains the PGP signature. /// </param> /// <returns> /// A <see cref="PgpSignature"/> object which represents the PGP signature. /// </returns> private PgpSignature GetPgpSignature(SignatureTag tag) { byte[] value = (byte[])this.Package.Signature.Records[tag].Value; using (MemoryStream stream = new MemoryStream(value)) using (var signatureStream = PgpUtilities.GetDecoderStream(stream)) { PgpObjectFactory pgpFactory = new PgpObjectFactory(signatureStream); PgpSignatureList signatureList = (PgpSignatureList)pgpFactory.NextPgpObject(); PgpSignature signature = signatureList[0]; return signature; } }
/// <summary> /// Decompress previously compressed BZIP2 output encoded using ASCII /// armor format. /// </summary> /// <param name="data"> /// The data to decompress. /// </param> /// <returns> /// The decompressed <see cref="byte"/> array. /// </returns> public static byte[] DecompressData(byte[] data) { using (var stream = new MemoryStream(data)) { var objectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(stream)); var compressedData = (PgpCompressedData)objectFactory.NextPgpObject(); using (var compressedDataStream = compressedData.GetDataStream()) { var actualBytes = Streams.ReadAll(compressedDataStream); return(actualBytes); } } }
/// <summary> /// Process each message block type depending on the type. /// </summary> /// <param name="encryptedData"> /// Encrypted data packets. /// </param> /// <param name="outputStream"> /// Stream to write output. /// </param> /// <param name="publicKeyStream"> /// Public key stream for validating signature. /// </param> /// <param name="privateKey"> /// Private key for decrypting data. /// </param> /// <returns> /// Return true if the data is valid; false otherwise. /// </returns> private static bool ProcessDecryptionMessageBlocks( PgpPublicKeyEncryptedData encryptedData, Stream outputStream, Stream publicKeyStream, PgpPrivateKey privateKey) { var valid = true; PgpOnePassSignatureList onePassSignatureList = null; PgpOnePassSignature onePassSignature = null; PgpPublicKey publicKey = null; var clear = encryptedData.GetDataStream(privateKey); var plainFact = new PgpObjectFactory(clear); var message = plainFact.NextPgpObject(); while (message != null) { Console.WriteLine(message.ToString()); if (message is PgpCompressedData) { var compressedData = (PgpCompressedData)message; plainFact = new PgpObjectFactory(compressedData.GetDataStream()); } else if (message is PgpLiteralData) { onePassSignature = InitOnePassSignatureFromLiteral( publicKeyStream, onePassSignatureList, ref publicKey); ProcessDecryptionStreams(outputStream, message, onePassSignature); } else if (message is PgpOnePassSignatureList) { onePassSignatureList = (PgpOnePassSignatureList)message; } else if (message is PgpSignatureList) { valid = VerifyOnePassSignature(message, onePassSignature, publicKey, valid); } else { throw new PgpException("message unknown message type."); } message = plainFact.NextPgpObject(); } return(valid); }
/** * verify the signature in in against the file fileName. */ private static void VerifySignature( string fileName, Stream inputStream, Stream keyIn) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpSignatureList p3 = null; PgpObject o = pgpFact.NextPgpObject(); if (o is PgpCompressedData) { PgpCompressedData c1 = (PgpCompressedData)o; pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); Stream dIn = File.OpenRead(fileName); PgpSignature sig = p3[0]; PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { sig.Update((byte)ch); } dIn.Close(); if (sig.Verify()) { Console.WriteLine("signature verified."); } else { Console.WriteLine("signature verification failed."); } }
/// <summary> /// Create PGP-decrypting stream around a PGP-encrypted input source stream /// </summary> /// <param name="privatekeysource">Input stream containing private keyring bundle</param> /// <param name="privatekeypassphrase">Passphrase to access private key (if required)</param> /// <param name="encryptedinput">Input stream containing source data to be decrypted</param> /// <returns> /// A StreamStack object, from which decrypted data can be read /// </returns> /// <remarks> /// - Caller is responsible for disposing of returned StreamStack (BEFORE disposing of original encryptedinput Stream) /// - Caller is also still responsible for disposing of encryptedinput stream (AFTER disposing of returned StreamStack) /// - Source data stream will be read synchronously (due to limitation in PGP library; all source data must be available to perform decryption, /// but source library does not provide async option). If this is a concern, caller should consider asynchronously pulling source data into local /// stream first and passing local stream to this function (if increased use of memory outweighs waiting for blocked thread to perform I/O) /// </remarks> public static async Task <StreamStack> GetDecryptionStream(Stream privatekeysource, string privatekeypassphrase, Stream encryptedinput) { var decryptionstream = new StreamStack(); try { // Open decoder stream and push on to return value stack: decryptionstream.PushStream(PgpUtilities.GetDecoderStream(encryptedinput)); // Create object factory (using stream at top of stack) to extract encrypted data: var factory = new PgpObjectFactory(decryptionstream.GetStream()); var encrypteddata = factory.GetEncryptedData() ?? throw new ArgumentException("No PGP-encrypted data found"); // Extract private key from key source (using key ID required by encrypted data object), use to open // clear stream and push on to return value stack: decryptionstream.PushStream(encrypteddata.GetDataStream(await ExtractPrivateKey(privatekeysource, privatekeypassphrase, encrypteddata.KeyId))); // Create new factory from clear stream and extract first PGP object: factory = new PgpObjectFactory(decryptionstream.GetStream()); var message = factory.NextPgpObject(); while (message != null) { // If object is literal data, push de-literalization stream on to return value stack and return: if (message is PgpLiteralData cleardata) { decryptionstream.PushStream(cleardata.GetInputStream()); return(decryptionstream); } // Otherwise if this is compressed data, we need to push decompression stream on to return value // stack, then create a new object factory to extract data from decompressed source: else if (message is PgpCompressedData compresseddata) { decryptionstream.PushStream(compresseddata.GetDataStream()); factory = new PgpObjectFactory(decryptionstream.GetStream()); } // Extract next message object from factory and continue: message = factory.NextPgpObject(); } // If this point is reached, no literal packet was ever found throw new ArgumentException("Invalid PGP data (no payload found)"); } catch { decryptionstream.Dispose(); throw; } }
private void doTestMissingSubpackets(byte[] signature) { PgpObjectFactory f = new PgpObjectFactory(signature); object obj = f.NextPgpObject(); while (!(obj is PgpSignatureList)) { obj = f.NextPgpObject(); if (obj is PgpLiteralData) { Stream input = ((PgpLiteralData)obj).GetDataStream(); Streams.Drain(input); } } PgpSignature sig = ((PgpSignatureList)obj)[0]; if (sig.Version > 3) { PgpSignatureSubpacketVector v = sig.GetHashedSubPackets(); if (v.GetKeyExpirationTime() != 0) { Fail("key expiration time not zero for missing subpackets"); } if (!sig.HasSubpackets) { Fail("HasSubpackets property was false with packets"); } } else { if (sig.GetHashedSubPackets() != null) { Fail("hashed sub packets found when none expected"); } if (sig.GetUnhashedSubPackets() != null) { Fail("unhashed sub packets found when none expected"); } if (sig.HasSubpackets) { Fail("HasSubpackets property was true with no packets"); } } }
/// <summary> /// PGP-decrypt all data from source stream into destination stream /// </summary> /// <param name="privatekeysource">Input stream containing private keyring bundle</param> /// <param name="privatekeypassphrase">Passphrase to access private key (if required)</param> /// <param name="encryptedinput">Input stream containing source data to be decrypted</param> /// <param name="clearoutput">Output stream to receive decrypted data</param> /// <remarks> /// Destination data stream will be written asynchronously, but source data stream will be read synchronously (due to limitation in PGP /// library; all source data must be available to perform decryption, but source library does not provide async option). If this is a concern, /// caller should consider asynchronously pulling source data into local stream first and passing local stream to this function (if increased /// use of memory outweighs waiting for blocked thread to perform I/O) /// </remarks> public static async Task Decrypt(Stream privatekeysource, string privatekeypassphrase, Stream encryptedinput, Stream clearoutput) { // Create object factory using DecoderStream to read PGP data from source, use factory to extract encrypted data: using (var decoder = PgpUtilities.GetDecoderStream(encryptedinput)) { var encrypteddata = new PgpObjectFactory(decoder).GetEncryptedData() ?? throw new ArgumentException("No PGP-encrypted data found"); // Extract private key from key source (using key ID required by encrypted data object), use to open clear stream: using (var clearsource = encrypteddata.GetDataStream(await ExtractPrivateKey(privatekeysource, privatekeypassphrase, encrypteddata.KeyId))) { // Create new object factory from clear stream and use to write cleartext data to destination: await new PgpObjectFactory(clearsource).WriteClearData(clearoutput); } } }
private void ValidateData( byte[] compressed) { PgpObjectFactory pgpFact = new PgpObjectFactory(compressed); PgpCompressedData c1 = (PgpCompressedData) pgpFact.NextPgpObject(); Stream pIn = c1.GetDataStream(); byte[] bytes = Streams.ReadAll(pIn); pIn.Close(); if (!AreEqual(bytes, Data)) { Fail("compression test failed"); } }
// Note: I was able to extract the private key into xml format .Net expecs with this public static string GetPrivateKeyXml(string inputData) { Stream inputStream = IoHelper.GetStream(inputData); PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); PgpObject pgp = null; if (pgpFactory != null) { pgp = pgpFactory.NextPgpObject(); } PgpEncryptedDataList encryptedData = null; if (pgp is PgpEncryptedDataList) { encryptedData = (PgpEncryptedDataList)pgp; } else { encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } Stream privateKeyStream = File.OpenRead(PrivateKeyOnlyPath); // find secret key PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpPrivateKey privateKey = null; foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpKeyRing, pked.KeyId, Password.ToCharArray()); if (privateKey != null) { //pubKeyData = pked; break; } } // get xml: RsaPrivateCrtKeyParameters rpckp = ((RsaPrivateCrtKeyParameters)privateKey.Key); RSAParameters dotNetParams = DotNetUtilities.ToRSAParameters(rpckp); RSA rsa = RSA.Create(); rsa.ImportParameters(dotNetParams); string xmlPrivate = rsa.ToXmlString(true); return(xmlPrivate); }
private static void Decrypt(PgpCompressedData objCompressed, Stream outputStream) { using (var compressedStream = objCompressed.GetDataStream()) { var factory = new PgpObjectFactory(compressedStream); var obj = factory.NextPgpObject(); if (obj is PgpOnePassSignatureList) { Decrypt((PgpLiteralData)factory.NextPgpObject(), outputStream); } else { Decrypt((PgpLiteralData)obj, outputStream); } } }
private static void Main() { if (!File.Exists("MANIFEST.json.asc")) { return; } Stream inputStream = File.OpenRead("MANIFEST.json.asc"); Stream keyIn = File.OpenRead("gpg"); // https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/openpgp/examples/DetachedSignatureProcessor.cs inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpSignatureList p3; PgpObject o = pgpFact.NextPgpObject(); if (o is PgpCompressedData c1) { pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); Stream dIn = File.OpenRead("MANIFEST.json"); PgpSignature sig = p3[0]; PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { sig.Update((byte)ch); } dIn.Close(); Console.WriteLine(sig.Verify() ? "signature verified." : "signature verification failed."); }
public void DecryptFile(Stream outStream, Stream inputStream, char[] passPhrase) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc = null; PgpObject o = pgpF.NextPgpObject(); // // the first object might be a PGP marker packet. // if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] buf = new byte[1 << 16]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { outStream.Write(buf, 0, len); } // Finally verify the integrity if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit."); } } }
/// <summary> /// Verify the signature against the file. /// </summary> /// <param name="fileName"> /// File to validate /// </param> /// <param name="signatureStream"> /// Signature to validate. /// </param> /// <param name="keyStream"> /// Public key to use for signature validation. /// </param> /// <returns> /// The <see cref="bool"/> flag indicating verification success; false means /// the signature is invalid. /// </returns> public static bool VerifyDetachedFileSignature(string fileName, Stream signatureStream, Stream keyStream) { signatureStream = PgpUtilities.GetDecoderStream(signatureStream); var objectFactory = new PgpObjectFactory(signatureStream); PgpSignatureList signatureList; var @object = objectFactory.NextPgpObject(); if (@object is PgpCompressedData) { var compressedData = (PgpCompressedData)@object; objectFactory = new PgpObjectFactory(compressedData.GetDataStream()); signatureList = (PgpSignatureList)objectFactory.NextPgpObject(); } else { signatureList = (PgpSignatureList)@object; } var pgpPubRingCollection = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyStream)); var signature = signatureList[0]; var key = pgpPubRingCollection.GetPublicKey(signature.KeyId); signature.InitVerify(key); using (var fileDataStream = File.OpenRead(fileName)) { int read; var buffer = new byte[PgpCommon.BufferSize]; while ((read = fileDataStream.Read(buffer, 0, buffer.Length)) > 0) { signature.Update(buffer, 0, read); } } if (!signature.Verify()) { Console.WriteLine("signature verification failed."); return(false); } Console.WriteLine("signature verified."); return(true); }
private byte[] DecryptMessageBuffered( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); MemoryStream bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks); } Stream unc = ld.GetInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { bOut.Write(buf, 0, len); } if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return(bOut.ToArray()); }
private static PgpEncryptedDataList getEncryptedDataList(Stream encodedFile) { PgpObjectFactory factory = new PgpObjectFactory(encodedFile); PgpObject pgpObject = factory.NextPgpObject(); PgpEncryptedDataList encryptedDataList; if (pgpObject is PgpEncryptedDataList) { encryptedDataList = (PgpEncryptedDataList)pgpObject; } else { encryptedDataList = (PgpEncryptedDataList)factory.NextPgpObject(); } return(encryptedDataList); }
/*.......................................................................檔案數認證開始*/ /*首先傳送端將訊息經過雜湊演算法計算後得到一個雜湊值,再利用它的私有鑰匙向雜湊值加密成為一個數位簽章(DS),接著,再將數位簽章附加在訊息後面一併傳送出去; * 接收端收到訊息之後,以同樣的雜湊演算計算出雜湊值(H’),並利用傳送端的公開鑰匙將 DS 解密,得到另一端的雜湊值(H)。 * 接著,比較兩個雜湊值,如果相同的話,則可以確定該訊息的『完整性』(雜湊值相同),此外也可以確定其『不可否認性』(私有鑰匙與公開鑰匙配對)。*/ /* * 簽章後的hash值 -> 公鑰(對方)解密 -> hash值 * 解密後的文章 -> hash -> 解密後文章的hash值 */ private static void VerifyFile( Stream inputStream, //預計數位認證原始檔案的資料流 Stream keyIn, //簽名方(對方)公鑰的資料流 string outputFileName //預計匯出(數位認證後檔案)的完整路徑 ) { inputStream = PgpUtilities.GetDecoderStream(inputStream); //串流陣列化 byte Array PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); 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(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); //取出公鑰 Stream fileOutput = File.Create(outputFileName); //預計匯出檔案建立 ops.InitVerify(key); //驗證公鑰是否符合 int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); //進行解密 fileOutput.WriteByte((byte)ch); //寫入預計匯出檔案 } fileOutput.Close(); fileOutput.Dispose(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) //Hash值比較 { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); } }
public static PgpOnePassSignatureList GetPgpOnePassSignatureList(Stream encodedFile) { PgpObjectFactory factory = new PgpObjectFactory(encodedFile); PgpObject pgpObject = factory.NextPgpObject(); PgpOnePassSignatureList pgpOnePassSignatureList; if (pgpObject is PgpOnePassSignatureList) { pgpOnePassSignatureList = (PgpOnePassSignatureList)pgpObject; } else { pgpOnePassSignatureList = (PgpOnePassSignatureList)factory.NextPgpObject(); } return(pgpOnePassSignatureList); }
private static void DecryptCompressedData(PgpObject message, string outputFile) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory objectFactory; using (Stream compDataIn = cData.GetDataStream()) { objectFactory = new PgpObjectFactory(compDataIn); } message = objectFactory.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = objectFactory.NextPgpObject(); } PipeStreamToFile(outputFile, (PgpLiteralData)message); }
private string Decrypt(Stream input, PgpSecretKey secretKey, string passPhrase) { input = PgpUtilities.GetDecoderStream(input); PgpObjectFactory pgpObjF = new PgpObjectFactory(input); PgpEncryptedDataList enc; PgpObject obj = pgpObjF.NextPgpObject(); if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else { enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject(); } PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First(); Stream clear; PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passPhrase.ToCharArray()); clear = pbe.GetDataStream(privateKey); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; Stream compDataIn = cData.GetDataStream(); PgpObjectFactory o = new PgpObjectFactory(compDataIn); message = o.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = o.NextPgpObject(); } var ld = (PgpLiteralData)message; var unc = ld.GetInputStream(); var reader = new StreamReader(unc); return(reader.ReadToEnd()); } throw new NotImplementedException(); }
/** * verify the passed in file as being correctly signed. */ private static void VerifyFile( Stream inputStream, Stream keyIn) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); 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(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); IPgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); Stream fos = File.Create(p2.FileName); ops.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); fos.WriteByte((byte)ch); } fos.Close(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); } }
/// <summary> /// Get the encrypted data list from the input stream. /// </summary> /// <param name="inputStream"> /// Input stream. /// </param> /// <returns> /// Returns the encrypted data list. /// </returns> private static PgpEncryptedDataList GetEncryptedDataListFromStream(Stream inputStream) { inputStream = PgpUtilities.GetDecoderStream(inputStream); var objectFactory = new PgpObjectFactory(inputStream); PgpEncryptedDataList encryptedDataList; PgpObject pgpObject = objectFactory.NextPgpObject(); if (pgpObject is PgpEncryptedDataList) { encryptedDataList = (PgpEncryptedDataList)pgpObject; } else { encryptedDataList = (PgpEncryptedDataList)objectFactory.NextPgpObject(); } return(encryptedDataList); }
private static IEnumerable <T> ParseObjects <T>(Stream stream) where T : PgpObject { var factory = new PgpObjectFactory(stream); while (factory.NextPgpObject() is {} obj) { if (obj is T target) { yield return(target); } if (obj is PgpCompressedData compressed) { foreach (var result in ParseObjects <T>(compressed.GetDataStream())) { yield return(result); } } } }
private byte[] DecryptBytes(bool ignoreIntegrityCheck, Stream armoredIn) { var factory = new PgpObjectFactory(armoredIn); while (true) { var obj = factory.NextPgpObject(); if (obj is PgpMarker) { continue; } var ret = DecryptHandlePgpObject(obj); if (Context.FailedIntegrityCheck && !ignoreIntegrityCheck) { throw new VerifyException("Data not integrity protected."); } return(ret); } }
/** * decrypt the passed in message stream * * @param encrypted The message to be decrypted. * @param passPhrase Pass phrase (key) * * @return Clear text as a byte array. I18N considerations are * not handled by this routine * @exception IOException * @exception PgpException */ public static byte[] Decrypt( byte[] encrypted, char[] passPhrase) { Stream inputStream = new MemoryStream(encrypted); inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc = null; PgpObject o = pgpF.NextPgpObject(); // // the first object might be a PGP marker packet. // if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); return(Streams.ReadAll(unc)); }
private void ReadBackTest( PgpLiteralDataGenerator generator) { Random rand = new Random(); byte[] buf = new byte[MAX]; rand.NextBytes(buf); for (int i = 1; i != MAX; i++) { MemoryStream bOut = new MemoryStream(); Stream outputStream = generator.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, PgpLiteralData.Console, i, DateTime.UtcNow); outputStream.Write(buf, 0, i); generator.Close(); PgpObjectFactory fact = new PgpObjectFactory(bOut.ToArray()); PgpLiteralData data = (PgpLiteralData)fact.NextPgpObject(); Stream inputStream = data.GetInputStream(); for (int count = 0; count != i; count++) { if (inputStream.ReadByte() != (buf[count] & 0xff)) { Fail("failed readback test - length = " + i); } } } }
private void DoTestSignedEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey); PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject(); PgpOnePassSignature ops = sList[0]; PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } Stream dIn = lData .GetInputStream(); ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed 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; }
/** * 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 messageTest( string message, string type) { ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(Encoding.ASCII.GetBytes(message))); string[] headers = aIn.GetArmorHeaders(); if (headers == null || headers.Length != 1) { Fail("wrong number of headers found"); } if (!"Hash: SHA256".Equals(headers[0])) { Fail("header value wrong: " + headers[0]); } // // read the input, making sure we ingore the last newline. // MemoryStream bOut = new MemoryStream(); int ch; while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText()) { bOut.WriteByte((byte)ch); } PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); MemoryStream lineOut = new MemoryStream(); Stream sigIn = new MemoryStream(bOut.ToArray(), false); int lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte) '\r'); sig.Update((byte) '\n'); ProcessLine(sig, lineOut.ToArray()); } while (lookAhead != -1); } if (!sig.Verify()) { Fail("signature failed to verify m_in " + type); } }
private void doSigVerifyTest( string publicKeyFile, string sigFile) { PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile); PgpObjectFactory pgpFact = loadSig(sigFile); 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(publicKey.GetPublicKey()); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); Assert.IsTrue(ops.Verify(p3[0])); }
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); } }
private byte[] DecryptMessageBuffered( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); MemoryStream bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks); } Stream unc = ld.GetInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { bOut.Write(buf, 0, len); } if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bOut.ToArray(); }
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)); }
private void DoTestEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } }
private void verifySignature( byte[] encodedSig, HashAlgorithmTag hashAlgorithm, IPgpPublicKey pubKey, byte[] original) { PgpObjectFactory pgpFact = new PgpObjectFactory(encodedSig); 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(); PgpSignature sig = p3[0]; DateTime creationTime = sig.CreationTime; // Check creationTime is recent if (creationTime.CompareTo(DateTime.UtcNow) > 0 || creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0) { Fail("bad creation time in signature: " + creationTime); } if (sig.KeyId != pubKey.KeyId) { Fail("key id mismatch in signature"); } if (!ops.Verify(sig)) { Fail("Failed generated signature check - " + hashAlgorithm); } sig.InitVerify(pubKey); for (int i = 0; i != original.Length; i++) { sig.Update(original[i]); } sig.Update(original); if (!sig.Verify()) { Fail("Failed generated signature check against original data"); } }
private void MixedTest( PgpPrivateKey pgpPrivKey, PgpPublicKey pgpPubKey) { byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // literal data // MemoryStream bOut = new MemoryStream(); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( bOut, PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, DateTime.UtcNow); lOut.Write(text, 0, text.Length); lGen.Close(); byte[] bytes = bOut.ToArray(); PgpObjectFactory f = new PgpObjectFactory(bytes); CheckLiteralData((PgpLiteralData)f.NextPgpObject(), text); MemoryStream bcOut = new MemoryStream(); PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Aes128, true, new SecureRandom()); encGen.AddMethod(pgpPubKey); encGen.AddMethod("password".ToCharArray(), HashAlgorithmTag.Sha1); Stream cOut = encGen.Open(bcOut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); byte[] encData = bcOut.ToArray(); // // asymmetric // PgpObjectFactory pgpF = new PgpObjectFactory(encData); PgpEncryptedDataList encList = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData)pgpFact.NextPgpObject(), text); // // PBE // pgpF = new PgpObjectFactory(encData); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1]; clear = encPbe.GetDataStream("password".ToCharArray()); pgpF = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text); }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // 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."); // } } } }
public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } }
private void TestDecrypt(PgpSecretKeyRing secretKeyRing) { PgpObjectFactory pgpF = new PgpObjectFactory(testMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId); // PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder()); // clear = encP.getDataStream(pgpPrivKey, "BC"); // // bOut.reset(); // // while ((ch = clear.read()) >= 0) // { // bOut.write(ch); // } // // out = bOut.toByteArray(); // // if (!AreEqual(out, text)) // { // fail("wrong plain text in Generated packet"); // } }
public override void PerformTest() { // // test immediate close // MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); aOut.Close(); byte[] data = bOut.ToArray(); if (data.Length != 0) { Fail("No data should have been written"); } // // multiple close // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aOut.Close(); int mc = markerCount(bOut.ToArray()); if (mc < 1) { Fail("No end marker found"); } if (mc > 1) { Fail("More than one end marker found"); } // // writing and reading single objects // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); PgpObjectFactory fact = new PgpObjectFactory(aIn); int count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 1) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); fact = new PgpObjectFactory(aIn); count = 0; while (fact.NextPgpObject() != null) { count++; } if (count != 2) { Fail("wrong number of objects found: " + count); } // // writing and reading multiple objects - in single block // bOut = new MemoryStream(); aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); // does not close underlying stream aOut = new ArmoredOutputStream(bOut); aOut.Write(sample, 0, sample.Length); aOut.Close(); aIn = new ArmoredInputStream( new MemoryStream(bOut.ToArray(), false)); count = 0; bool atLeastOne; do { atLeastOne = false; fact = new PgpObjectFactory(aIn); while (fact.NextPgpObject() != null) { atLeastOne = true; count++; } } while (atLeastOne); if (count != 2) { Fail("wrong number of objects found: " + count); } blankLineTest(); }
private void doTestMissingSubpackets(byte[] signature) { PgpObjectFactory f = new PgpObjectFactory(signature); object obj = f.NextPgpObject(); while (!(obj is PgpSignatureList)) { obj = f.NextPgpObject(); if (obj is PgpLiteralData) { Stream input = ((PgpLiteralData)obj).GetDataStream(); Streams.Drain(input); } } PgpSignature sig = ((PgpSignatureList)obj)[0]; if (sig.Version > 3) { var v = sig.GetHashedSubPackets(); if (v.GetKeyExpirationTime() != 0) { Fail("key expiration time not zero for missing subpackets"); } if (!sig.HasSubpackets) { Fail("HasSubpackets property was false with packets"); } } else { if (sig.GetHashedSubPackets() != null) { Fail("hashed sub packets found when none expected"); } if (sig.GetUnhashedSubPackets() != null) { Fail("unhashed sub packets found when none expected"); } if (sig.HasSubpackets) { Fail("HasSubpackets property was true with no packets"); } } }
private void EncryptDecryptTest() { SecureRandom random = SecureRandom.GetInstance("SHA1PRNG"); byte[] text = Encoding.ASCII.GetBytes("hello world!"); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random)); AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair(); PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); MemoryStream ldOut = new MemoryStream(); Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow); pOut.Write(text, 0, text.Length); pOut.Close(); byte[] data = ldOut.ToArray(); MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); cPk.AddMethod(ecdhKeyPair.PublicKey); Stream cOut = cPk.Open(new UncloseableStream(cbOut), data.Length); cOut.Write(data, 0, data.Length); cOut.Close(); PgpObjectFactory pgpF = new PgpObjectFactory(cbOut.ToArray()); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey); pgpF = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpF.NextPgpObject(); clear = ld.GetInputStream(); MemoryStream bOut = new MemoryStream(); int ch; while ((ch = clear.ReadByte()) >= 0) { bOut.WriteByte((byte)ch); } byte[] output = bOut.ToArray(); if (!AreEqual(output, text)) { Fail("wrong plain text in Generated packet"); } }
public override void PerformTest() { // // RSA tests // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing); IPgpSecretKey secretKey = pgpPriv.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass); try { doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA V3 wrong key test failed."); } catch (PgpException) { // expected } // // certifications // PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey); PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey); sig.InitVerify(secretKey.PublicKey); if (!sig.VerifyCertification(secretKey.PublicKey)) { Fail("revocation verification failed."); } PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing); IPgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey(); IPgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass); sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME); hashedGen.SetSignerUserId(true, TEST_USER_ID); hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS); hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS); hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(unhashedGen.Generate()); sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey); byte[] sigBytes = sig.GetEncoded(); PgpObjectFactory f = new PgpObjectFactory(sigBytes); sig = ((PgpSignatureList) f.NextPgpObject())[0]; sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } var hashedPcks = sig.GetHashedSubPackets(); var unhashedPcks = sig.GetUnhashedSubPackets(); if (hashedPcks.Count != 6) { Fail("wrong number of hashed packets found."); } if (unhashedPcks.Count != 1) { Fail("wrong number of unhashed packets found."); } if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID)) { Fail("test userid not matching"); } if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME) { Fail("test signature expiration time not matching"); } if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId) { Fail("wrong issuer key ID found in certification"); } int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs); SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 1) { Fail("wrong number of critical packets found."); } if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId) { Fail("wrong critical packet found in tag list."); } // // no packets passed // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); sGen.SetHashedSubpackets(null); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets"); } try { sig.VerifyCertification(secretKey.PublicKey); Fail("failed to detect non-key signature."); } catch (InvalidOperationException) { // expected } // // override hash packets // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); hashedGen = new PgpSignatureSubpacketGenerator(); DateTime creationTime = new DateTime(1973, 7, 27); hashedGen.SetSignatureCreationTime(false, creationTime); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets in override test"); } if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime)) { Fail("hasSubpacket test for creation time failed"); } DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime(); if (!sigCreationTime.Equals(creationTime)) { Fail("creation of overridden date failed."); } prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs); if (hashedPcks.GetKeyExpirationTime() != 0) { Fail("unexpected key expiration time found"); } if (hashedPcks.GetSignatureExpirationTime() != 0) { Fail("unexpected signature expiration time found"); } if (hashedPcks.GetSignerUserId() != null) { Fail("unexpected signer user ID found"); } criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 0) { Fail("critical packets found when none expected"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets in override test"); } // // general signatures // doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // // DSA Tests // pgpPriv = new PgpSecretKeyRing(dsaKeyRing); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass); try { doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA V3 wrong key test failed."); } catch (PgpException) { // expected } doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // special cases // doTestMissingSubpackets(nullPacketsSubKeyBinding); doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1)); // keyflags doTestKeyFlagsValues(); }
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(); }