/// <summary> /// Encrypts an input file stream given the provided Public Key File. /// </summary> /// <param name="outputFileStream">File Stream of the new encrypted output file.</param> /// <param name="inputFilePath">Path of existing unencrypted input file.</param> /// <param name="publicKey">PgpPublicKey that will be used to encrypt the file.</param> /// <param name="armor">Use ASCII Armor</param> /// <param name="withIntegrityCheck">Include Integrity Check</param> /// <exception cref="ArgumentException"></exception> /// <exception cref="FileNotFoundException"></exception> public static void EncryptFile(Stream outputFileStream, string inputFilePath, PgpPublicKey publicKey, bool armor = true, bool withIntegrityCheck = true) { // Parameter Checks if (String.IsNullOrEmpty(inputFilePath)) { throw new ArgumentException("Input File Name Parameter is invalid."); } if (!File.Exists(inputFilePath)) { throw new FileNotFoundException("Input File does not exist."); } if (armor) { outputFileStream = new ArmoredOutputStream(outputFileStream); } try { PgpEncryptedDataGenerator _encryptedDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); _encryptedDataGen.AddMethod(publicKey); Stream _encryptedOutStream = _encryptedDataGen.Open(outputFileStream, new byte[1 << 16]); PgpCompressedDataGenerator _compressedDataGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); PgpUtilities.WriteFileToLiteralData(_compressedDataGen.Open(_encryptedOutStream), PgpLiteralData.Binary, new FileInfo(inputFilePath), new byte[1 << 16]); _compressedDataGen.Close(); _encryptedOutStream.Close(); if (armor) { outputFileStream.Close(); } } catch (PgpException ex) { Console.Error.WriteLine(ex); Exception underlyingException = ex.InnerException; if (underlyingException != null) { Console.Error.WriteLine(underlyingException.Message); Console.Error.WriteLine(underlyingException.StackTrace); } } }
/// <summary> /// Creates a writable PGP storage that will encrypt the files that is /// created through this storage with the given <paramref name="publicKey"/>. /// </summary> /// <param name="storage">The underlying storage to create the file against.</param> /// <param name="publicKey">The public key used to encrypt the files with PGP.</param> /// <exception cref="ArgumentNullException">If <paramref name="storage"/> is null.</exception> /// <exception cref="ArgumentNullException">If <paramref name="publicKey"/> is null.</exception> public WritablePgpStorage(IStorage storage, PgpPublicKey publicKey) : this(storage) { Storage = storage ?? throw new ArgumentNullException(nameof(storage)); PublicKey = publicKey ?? throw new ArgumentNullException(nameof(publicKey)); }
/// <summary> /// Constructs a new symmetric key packet /// </summary> public SymKeyPacket(byte specifier, KeyParameter key, AbstractPgpCrypt pgpCrypt, PgpPublicKey pgpPublicKey) : base(specifier, pgpCrypt.Encrypt(key.GetKey(), pgpPublicKey.GetKey())) { }
private void doTestSig( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(TEST_DATA, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Binary, "_CONSOLE", TEST_DATA.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(TEST_DATA, 0, TEST_DATA.Length); sGen.Update(TEST_DATA); lGen.Close(); sGen.Generate().Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, TEST_DATA); }
private void doTestTextSigV3( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey, byte[] data, byte[] canonicalData) { PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(data, false); sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( new UncloseableStream(bOut), PgpLiteralData.Text, "_CONSOLE", data.Length * 2, DateTime.UtcNow); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Write(data, 0, data.Length); sGen.Update(data); lGen.Close(); PgpSignature sig = sGen.Generate(); if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0)) { Fail("creation time not set in v3 signature"); } sig.Encode(bOut); verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData); }
private static bool IsGoodUidSignature(PgpSignature sig, PgpPublicKey masterpk, string uid) { sig.InitVerify(masterpk); return sig.VerifyCertification(uid, masterpk); }
private void PerformTestSig( HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check - " + hashAlgorithm); } }
internal OpenPgpDigitalSignature(PgpPublicKeyRing keyring, PgpPublicKey pubkey, PgpSignature signature) { SignerCertificate = pubkey != null ? new OpenPgpDigitalCertificate(keyring, pubkey) : null; Signature = signature; }
public PgpSignature GenerateCertification(string id, PgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); UpdateWithIdData(180, Strings.ToUtf8ByteArray(id)); return(Generate()); }
internal OpenPgpDigitalSignature(PgpPublicKey pubkey, PgpOnePassSignature signature) { SignerCertificate = pubkey != null ? new OpenPgpDigitalCertificate(pubkey) : null; OnePassSignature = signature; }
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."); // } } } }
/// <summary> /// Encrypt a file as specified by the input file path. /// </summary> /// <param name="inputFile"> /// The file to encrypt. /// </param> /// <param name="outputFile"> /// The file to write the encrypted content to. /// </param> /// <param name="publicKeyFile"> /// The path to the public key file to use for encryption. /// </param> /// <param name="symmetricKeyAlgorithm"> /// Encryption algorithm. /// </param> /// <param name="armor"> /// Should the encrypted file be written using ASCII armor? /// </param> /// <param name="withIntegrityCheck"> /// Should the integrity be verified? /// </param> /// <param name="compressionAlgorithm"> /// Compression algorithm to use. /// </param> public static void EncryptFile( string inputFile, string outputFile, string publicKeyFile, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm = SymmetricKeyAlgorithmTag.Aes256, bool armor = true, bool withIntegrityCheck = true, CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip) { try { using (Stream publicKeyStream = File.OpenRead(publicKeyFile)) { PgpPublicKey encKey = PgpKeyHelper.ReadPublicKey(publicKeyStream); using (var memoryStream = new MemoryStream()) { var compressedDataGenerator = new PgpCompressedDataGenerator(compressionAlgorithm); WriteFileToLiteralData( compressedDataGenerator.Open(memoryStream), PgpLiteralData.Binary, new FileInfo(inputFile)); compressedDataGenerator.Close(); var encryptedDataGenerator = new PgpEncryptedDataGenerator( symmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom()); encryptedDataGenerator.AddMethod(encKey); var bytes = memoryStream.ToArray(); using (Stream outputStream = File.Create(outputFile)) { if (armor) { using (var armoredStream = new ArmoredOutputStream(outputStream)) using (var encryptedStream = encryptedDataGenerator.Open(armoredStream, bytes.Length)) { encryptedStream.Write(bytes, 0, bytes.Length); } } else { using ( Stream encryptedOutputStream = encryptedDataGenerator.Open( outputStream, bytes.Length)) { encryptedOutputStream.Write(bytes, 0, bytes.Length); } } } } } } catch (PgpException exception) { PgpCommon.DumpException(exception); throw; } }
internal PubMethod(PgpPublicKey pubKey) { this.pubKey = pubKey; }
private static void VerifySignature(PgpOnePassSignatureList onePassSigList, PgpSignatureList signatureList, PgpPublicKey pubKey, byte[] original) { PgpOnePassSignature ops = onePassSigList[0]; ops.InitVerify(pubKey); ops.Update(original); PgpSignatureList p3 = signatureList; PgpSignature sig = p3[0]; if (sig.KeyId != pubKey.KeyId) { throw new PgpException("key id mismatch in signature."); } if (!ops.Verify(sig)) { throw new PgpException("Failed generated signature check."); } sig.InitVerify(pubKey); for (int i = 0; i < original.Length; i++) { sig.Update(original[i]); } //sig.Update(original); if (!sig.Verify()) { throw new PgpException("Failed generated signature check against original data."); } }
private static byte[] SignPublicKey( PgpSecretKey secretKey, string secretKeyPass, PgpPublicKey keyToBeSigned, string notationName, string notationValue, bool armor) { Stream os = new MemoryStream(); if (armor) { os = new ArmoredOutputStream(os); } PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey( secretKeyPass.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator( secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.DirectKey, pgpPrivKey); BcpgOutputStream bOut = new BcpgOutputStream(os); sGen.GenerateOnePassVersion(false).Encode(bOut); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); bool isHumanReadable = true; spGen.SetNotationData(true, isHumanReadable, notationName, notationValue); PgpSignatureSubpacketVector packetVector = spGen.Generate(); sGen.SetHashedSubpackets(packetVector); bOut.Flush(); if (armor) { os.Close(); } return PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded(); }
public PgpSignature GenerateCertification(PgpUserAttributeSubpacketVector userAttributes, PgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); try { MemoryStream memoryStream = new MemoryStream(); UserAttributeSubpacket[] array = userAttributes.ToSubpacketArray(); foreach (UserAttributeSubpacket userAttributeSubpacket in array) { userAttributeSubpacket.Encode(memoryStream); } UpdateWithIdData(209, memoryStream.ToArray()); } catch (IOException exception) { throw new PgpException("cannot encode subpacket array", exception); } return(Generate()); }
private void CheckUidSig(PgpPublicKey pk, string uid) { foreach (PgpSignature sig in pk.GetSignaturesForId(uid)) { if (!IsGoodUidSignature(sig, pk, uid)) { Fail("Bad self-signature found for '" + uid + "'"); } } }
public PgpSignature GenerateCertification(PgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); return(Generate()); }
/** * Generated signature test * * @param sKey * @param pgpPrivKey * @return test result */ public void GenerateTest( PgpSecretKeyRing sKey, PgpPublicKey pgpPubKey, PgpPrivateKey pgpPrivKey) { string data = "hello world!"; MemoryStream bOut = new MemoryStream(); byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator(); enumerator.MoveNext(); string primaryUserId = (string) enumerator.Current; spGen.SetSignerUserId(true, primaryUserId); sGen.SetHashedSubpackets(spGen.Generate()); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData) pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pgpPubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte) ch); } PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } }
private void UpdateWithPublicKey(PgpPublicKey key) { byte[] encodedPublicKey = GetEncodedPublicKey(key); Update(153, (byte)(encodedPublicKey.Length >> 8), (byte)encodedPublicKey.Length); Update(encodedPublicKey); }
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 bool Verify(PgpPublicKey pgpPublicKey) { // 1 Verify the header signature immutable block: make sure all records are marked as immutable var immutableRegionSize = this.ImmutableRegionSize; var immutableEntryCount = -immutableRegionSize / Marshal.SizeOf <IndexHeader>(); if (this.Package.Signature.Records.Count != immutableEntryCount) { return(false); } // Store the header data and the header + payload data in substreams. This enables us to calculate hashes and // verify signatures using these data ranges. using (Stream headerStream = new SubStream( this.Package.Stream, this.Package.HeaderOffset, this.Package.PayloadOffset - this.Package.HeaderOffset, leaveParentOpen: true, readOnly: true)) using (Stream headerAndPayloadStream = new SubStream( this.Package.Stream, this.Package.HeaderOffset, this.Package.Stream.Length - this.Package.HeaderOffset, leaveParentOpen: true, readOnly: true)) { // Verify the SHA1 hash. This one covers the header block SHA1 sha = SHA1.Create(); var calculatedShaValue = sha.ComputeHash(headerStream); var actualShaValue = this.Sha1Hash; if (!calculatedShaValue.SequenceEqual(actualShaValue)) { return(false); } // Verify the MD5 hash. This one covers the header and the payload block MD5 md5 = MD5.Create(); var calculatedMd5Value = md5.ComputeHash(headerAndPayloadStream); var actualMd5Value = this.MD5Hash; if (!calculatedMd5Value.SequenceEqual(actualMd5Value)) { return(false); } // Verify the PGP signatures // 3 for the header var headerPgpSignature = this.HeaderPgpSignature; headerStream.Position = 0; if (!PgpSigner.VerifySignature(headerPgpSignature, pgpPublicKey, headerStream)) { return(false); } var headerAndPayloadPgpSignature = this.HeaderAndPayloadPgpSignature; headerAndPayloadStream.Position = 0; if (!PgpSigner.VerifySignature(headerAndPayloadPgpSignature, pgpPublicKey, headerAndPayloadStream)) { return(false); } } // Verify the signature size (header + compressed payload) var headerSize = this.HeaderAndPayloadSize; if (headerSize != this.Package.Stream.Length - this.Package.HeaderOffset) { return(false); } // Verify the payload size (header + uncompressed payload) var expectedDecompressedPayloadSize = this.UncompressedPayloadSize; long actualDecompressedPayloadLength = 0; using (Stream payloadStream = RpmPayloadReader.GetDecompressedPayloadStream(this.Package)) { actualDecompressedPayloadLength = payloadStream.Length; } if (expectedDecompressedPayloadSize != actualDecompressedPayloadLength) { return(false); } return(true); }
private void doTestSigV3( PublicKeyAlgorithmTag encAlgorithm, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { byte[] bytes = generateV3BinarySig(privKey, encAlgorithm, hashAlgorithm); verifySignature(bytes, hashAlgorithm, pubKey, TEST_DATA); }
/// <summary> /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified} /// </summary> public static Result PGPVerifySignFile(Input input) { using (var inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile))) using (var keyStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile))) { PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpOnePassSignatureList signatureList = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature onePassSignature = signatureList[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dataIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(keyStream); PgpPublicKey key = pgpRing.GetPublicKey(onePassSignature.KeyId); string outputPath; if (String.IsNullOrWhiteSpace(input.OutputFolder)) { outputPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName); } else { outputPath = Path.Combine(input.OutputFolder, p2.FileName); } using (var outputStream = File.Create(outputPath)) { onePassSignature.InitVerify(key); int ch; while ((ch = dataIn.ReadByte()) >= 0) { onePassSignature.Update((byte)ch); outputStream.WriteByte((byte)ch); } outputStream.Close(); } bool verified; // Will throw Exception if file is altered try { PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; verified = onePassSignature.Verify(firstSig); } catch (Exception) { Result retError = new Result { FilePath = input.OutputFolder, Verified = false }; return(retError); } Result ret = new Result { FilePath = outputPath, Verified = verified }; return(ret); } }
private void verifySignature( byte[] encodedSig, HashAlgorithmTag hashAlgorithm, PgpPublicKey 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"); } }
/// <summary> /// Creates a writable PGP storage that will both encrypt and sign the files /// created through this storage with PGP. /// </summary> /// <param name="storage">The storage to create the signed and encrypted files against.</param> /// <param name="publicKey">The public key used to encrypt the files with PGP.</param> /// <param name="privateKey">The private key used to sign the files with PGP.</param> /// <param name="password">The password that protects the private key.</param> /// <exception cref="ArgumentNullException">If <paramref name="storage"/> is null.</exception> /// <exception cref="ArgumentNullException">If <paramref name="publicKey"/> is null.</exception> /// <exception cref="ArgumentNullException">If <paramref name="privateKey"/> is null.</exception> public WritablePgpStorage(IStorage storage, PgpPublicKey publicKey, PgpSecretKeyRing privateKey, string password) : this(storage, privateKey, password) { PublicKey = publicKey ?? throw new ArgumentNullException(nameof(publicKey)); }