/// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static Result PGPSignFile(Input input) { HashAlgorithmTag digest = input.HashFunction.ConvertEnum <HashAlgorithmTag>(); using (var privateKeyStream = File.OpenRead(input.PrivateKeyFile)) { PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { signatureSubpacketGenerator.SetSignerUserId(false, (string)enumerator.Current); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); } using (var outputStream = File.Create(input.OutputFile)) { ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream); BcpgOutputStream bcbgOutputStream = new BcpgOutputStream(armoredOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcbgOutputStream); FileInfo file = new FileInfo(input.InputFile); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); Stream literalDataOut = literalDataGenerator.Open(bcbgOutputStream, PgpLiteralData.Binary, file); using (var fileIn = file.OpenRead()) { int ch; while ((ch = fileIn.ReadByte()) >= 0) { literalDataOut.WriteByte((byte)ch); signatureGenerator.Update((byte)ch); } fileIn.Close(); literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcbgOutputStream); armoredOutputStream.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return(ret); } } } }
public PgpPrivateKey FindSecretKey(long keyId) { PgpSecretKey pgpSecKey = SecretKeys.GetSecretKey(keyId); if (pgpSecKey == null) { return(null); } return(pgpSecKey.ExtractPrivateKey(_passPhrase.ToCharArray())); }
/// <summary> /// Search a secret key ring collection for a secret key corresponding to keyID if it exists. /// </summary> /// <param name="secretKeyRingBundle"></param> /// <param name="keyID"></param> /// <param name="passPhrase"></param> /// <returns></returns> /// <exception cref="PgpException"></exception> internal static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle, long keyId, char[] passPhrase) { PgpSecretKey _pgpSecretKey = secretKeyRingBundle.GetSecretKey(keyId); if (_pgpSecretKey == null) { return(null); } return(_pgpSecretKey.ExtractPrivateKey(passPhrase)); }
private string GetSecretKey(PgpSecretKey secretKey) { var secretMemStream = new MemoryStream(); var secretArmoredStream = new ArmoredOutputStream(secretMemStream); secretKey.Encode(secretArmoredStream); secretArmoredStream.Close(); var ascPgpSecretKey = Encoding.ASCII.GetString(secretMemStream.ToArray()); return(ascPgpSecretKey); }
private string GetPublicKey(PgpSecretKey secretKey) { var pubMemStream = new MemoryStream(); var pubArmoredStream = new ArmoredOutputStream(pubMemStream); secretKey.PublicKey.Encode(pubArmoredStream); pubArmoredStream.Close(); var ascPgpPublicKey = Encoding.ASCII.GetString(pubMemStream.ToArray()); return(ascPgpPublicKey); }
private PgpPrivateKey FindKeyById(PgpSecretKeyRingBundle privRings, long keyId) { PgpSecretKey pgpSecKey = privRings.GetSecretKey(keyId); if (pgpSecKey == null) { return(null); } return(pgpSecKey.ExtractPrivateKey(null)); }
public static PgpSecretKeyRing ReplacePublicKeys(PgpSecretKeyRing secretRing, PgpPublicKeyRing publicRing) { IList list = Platform.CreateArrayList(secretRing.keys.Count); foreach (PgpSecretKey key in secretRing.keys) { PgpPublicKey publicKey = publicRing.GetPublicKey(key.KeyId); list.Add(PgpSecretKey.ReplacePublicKey(key, publicKey)); } return(new PgpSecretKeyRing(list)); }
private static PgpPrivateKey GetPrivateKey(PgpSecretKey secretKey, string?passphrase) { try { return(secretKey.ExtractPrivateKey(passphrase?.ToCharArray())); } catch (PgpException) { throw new WrongPassphraseException(); } }
private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyId, char[] pass) { PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId); if (pgpSecKey == null) { return(null); } return(pgpSecKey.ExtractPrivateKey(pass)); }
/// <summary> /// Return the first key we can use to encrypt. /// Note: A file can contain multiple keys (stored in "key rings") /// </summary> private PgpSecretKey GetFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle) { foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings()) { PgpSecretKey key = kRing.GetSecretKeys().Cast <PgpSecretKey>().Where(k => k.IsSigningKey).FirstOrDefault(); if (key != null) { return(key); } } return(null); }
public PgpSecretKey GetSecretKey(long keyId) { foreach (PgpSecretKeyRing keyRing in GetKeyRings()) { PgpSecretKey secretKey = keyRing.GetSecretKey(keyId); if (secretKey != null) { return(secretKey); } } return(null); }
protected void ExportKeyPair( Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (secretOut == null) { throw new ArgumentException("secretOut"); } if (publicOut == null) { throw new ArgumentException("publicOut"); } if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSecretKey secretKey = new PgpSecretKey( certificationLevel: PgpSignatureType, algorithm: (PublicKeyAlgorithmTag)(int)PublicKeyAlgorithm, pubKey: publicKey, privKey: privateKey, time: DateTime.Now, id: identity, encAlgorithm: (SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, passPhrase: passPhrase, hashedPackets: null, unhashedPackets: null, rand: new SecureRandom() // ,"BC" ); secretKey.Encode(secretOut); secretOut.Close(); if (armor) { publicOut = new ArmoredOutputStream(publicOut); } PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); }
public void ExportPublicKeyFromDbSecret(long keyId, string saveFileName) { PgpSecretKey secretKey = ReadSecretKey(keyId); Stream outFile = File.Create(saveFileName); outFile = new ArmoredOutputStream(outFile); PgpPublicKey publicKey = secretKey.PublicKey; publicKey.Encode(outFile); outFile.Close(); }
private void ExportKeyPair( Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (secretOut == null) { throw new ArgumentException("secretOut"); } if (publicOut == null) { throw new ArgumentException("publicOut"); } if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSecretKey secretKey = new PgpSecretKey( PgpSignatureType, (PublicKeyAlgorithmTag)(int)PublicKeyAlgorithm, publicKey, privateKey, DateTime.Now, identity, (SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, passPhrase, null, null, new SecureRandom() // ,"BC" ); secretKey.Encode(secretOut); secretOut.Close(); if (armor) { publicOut = new ArmoredOutputStream(publicOut); } PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey); foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures()) { certification.InitVerify(pubKeyRing.GetPublicKey()); if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey())) { Fail("self certification does not verify"); } } if (pubKeyRing.GetPublicKey().BitStrength != 256) { Fail("incorrect bit strength returned"); } // // Read the private key // PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey privKey = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd); GenerateAndSign(); // // sExpr // byte[] msg = Encoding.ASCII.GetBytes("hello world!"); PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKey, false), "test".ToCharArray()); PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null)); signGen.Update(msg); PgpSignature sig = signGen.Generate(); sig.InitVerify(key.PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } }
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> /// Standard workflow... /// </summary> /// <param name="OverpassQuery">An Overpass query.</param> /// <param name="FilenamePrefix">A file name prefix.</param> public static void RunAll(this OverpassQuery OverpassQuery, String FilenamePrefix, PgpSecretKey SecretKey, String Passphrase) { OverpassQuery. ToFile(FilenamePrefix + ".json"). ToGeoJSONFile(FilenamePrefix + ".geojson"). SignGeoJSON(FilenamePrefix + ".geojson.sig", SecretKey, Passphrase). SignGeoJSON(FilenamePrefix + ".geojson.bsig", SecretKey, Passphrase, ArmoredOutput: false). ContinueWith(task => Console.WriteLine(FilenamePrefix + ".* files are ready!")). Wait(); }
private static void LoadKey() { using (var s = File.OpenRead(Configuration.MasterGPGKeyPath)) { masterSecretKey = ReadSecretKey(s); } var fingerPrint = Tools.H16FP(masterSecretKey.PublicKey.GetFingerprint().ToHexString()); Logger.Debug(GpgToolsLog, $"Loaded key {fingerPrint}"); if (!Configuration.ExternalKeyLoad) { UnlockKey(Configuration.MasterGPGKeyPassword); } }
private PgpSecretKey ReadSecretKey(Stream privateKeyStream) { using (Stream inputStream = PgpUtilities.GetDecoderStream(privateKeyStream)) { SecretKeys = new PgpSecretKeyRingBundle(inputStream); PgpSecretKey foundKey = GetFirstSecretKey(SecretKeys); if (foundKey != null) { return(foundKey); } } throw new ArgumentException("Can't find signing key in key ring."); }
public void Setup() { // Read the public key var pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // Read the private key var sKey = new PgpSecretKeyRing(testPrivKey); secretKey = sKey.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pass); }
private PgpPrivateKey GetPrivateKey(string password, string private_key_path) { PgpSecretKey secret_key = GetSecretKey(private_key_path); PgpPrivateKey private_key = secret_key.ExtractPrivateKey(password.ToCharArray()); if (private_key == null) { return(null); } return(private_key); }
/// <summary> /// Generate a private/public keypair /// </summary> /// <param name="privatePath">Private Path</param> /// <param name="publicPath">Public Path</param> public static bool GenerateKeypair(String privatePath, String publicPath) { Generate gen = new Generate(); gen.ShowDialog(); if (gen.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(false); } else { IAsymmetricCipherKeyPairGenerator kpg = new RsaKeyPairGenerator(); kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x13), new SecureRandom(), 1024, 8)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); FileStream privOut = new FileInfo(privatePath).OpenWrite(); FileStream pubOut = new FileInfo(publicPath).OpenWrite(); Stream privateOut = new ArmoredOutputStream(privOut); Stream publicOut = pubOut; PgpSecretKey privateKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.Now, gen.Idendity, SymmetricKeyAlgorithmTag.Cast5, gen.Passphrase.ToCharArray(), null, null, new SecureRandom() ); privateKey.Encode(privateOut); privOut.Close(); publicOut = new ArmoredOutputStream(publicOut); PgpPublicKey key = privateKey.PublicKey; key.Encode(publicOut); pubOut.Close(); // write decrypt comparison PGPLib lib = new PGPLib(File.ReadAllText("key_local/public.key"), File.ReadAllText("key_local/private.key"), gen.Passphrase); File.WriteAllText("key_local/validation.bin", lib.Encrypt("PGPSteam")); return(true); } }
private PgpSecretKey ReadSecretKey(string privateKeyp) { using (Stream keyIn = File.OpenRead(privateKeyp)) using (Stream iStream = PgpUtilities.GetDecoderStream(keyIn)) { PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(iStream); PgpSecretKey fKey = GetFirstSecretKey(secretKeyRingBundle); if (fKey != null) { return(fKey); } } throw new ArgumentException("No PGP Key Found"); }
/// <summary>Return the PGP secret key associated with the given key id.</summary> /// <param name="keyId">The ID of the secret key to return.</param> internal PgpSecretKey GetSecretKey(long keyId) { foreach (PgpSecretKeyRing secRing in GetSecretKeyRings()) { PgpSecretKey sec = secRing.GetSecretKey(keyId); if (sec != null) { return(sec); } } return(null); }
public static PgpPrivateKey ReadPrivateKey( string keyIn, string passPhrase) { PgpSecretKey secretKey = ReadSecretKey(keyIn); PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passPhrase.ToCharArray()); if (privateKey != null) { return(privateKey); } throw new ArgumentException("No private key found in secret key."); }
private PgpSecretKey ReadSecretKey(string privateKeyPath, bool toEncrypt) { using (Stream keyIn = File.OpenRead(privateKeyPath)) { using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) { PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(inputStream); PgpSecretKey foundKey = toEncrypt ? GetFirstSecretKey(secretKeyRingBundle) : GetLastSecretKey(secretKeyRingBundle); if (foundKey != null) { return(foundKey); } } } throw new Exception("Unable to find signing key in key ring."); }
public void DoTestEncMessage() { var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(encMessage); var publicKeyRing = new PgpPublicKeyRing(testPubKey); var publicKey = publicKeyRing.GetPublicKey(encryptedMessage.KeyIds.First()); var secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test", publicKey); var privateKey = secretKey.ExtractPrivateKey(""); var compressedMessage = (PgpCompressedMessage)encryptedMessage.DecryptMessage(privateKey); var literalMessage = (PgpLiteralMessage)compressedMessage.ReadMessage(); Assert.AreEqual("test.txt", literalMessage.FileName); }
private PgpSecretKey ReadSecretKey(string privateKeyPath) { using (Stream keyIn = File.OpenRead(privateKeyPath)) using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) { PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(inputStream); PgpSecretKey foundKey = GetFirstSecretKey(secretKeyRingBundle); if (foundKey != null) { return(foundKey); } } throw new ArgumentException("Can't find signing key in key ring."); }
private static PgpPrivateKey FindSecretKey(Stream keyIn, long keyId, char[] pass) { PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId); if (pgpSecKey == null) { return(null); } return(pgpSecKey.ExtractPrivateKey(pass)); }
// http://stackoverflow.com/questions/20572737/sign-and-verify-xml-file-in-c-sharp public void SignFile(string hashAlgorithm, string fileName, System.IO.Stream privateKeyStream , string privateKeyPassword, System.IO.Stream outStream) { PgpSecretKey pgpSec = ReadSigningSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = null; pgpPrivKey = pgpSec.ExtractPrivateKey(privateKeyPassword.ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, ParseHashAlgorithm(hashAlgorithm)); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); foreach (string userId in pgpSec.PublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); spGen.SetSignerUserId(false, userId); sGen.SetHashedSubpackets(spGen.Generate()); } CompressionAlgorithmTag compression = PreferredCompression(pgpSec.PublicKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(compression); BcpgOutputStream bOut = new BcpgOutputStream(cGen.Open(outStream)); sGen.GenerateOnePassVersion(false).Encode(bOut); System.IO.FileInfo file = new System.IO.FileInfo(fileName); System.IO.FileStream fIn = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); System.IO.Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file); int ch = 0; while ((ch = fIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } fIn.Close(); sGen.Generate().Encode(bOut); lGen.Close(); cGen.Close(); outStream.Close(); }
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(); }
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(); }
protected override string GetPasswordForKey (PgpSecretKey key) { // prompt the user (or a secure password cache) for the password for the specified secret key. return "password"; }
public void Sign (MimeMessage message, PgpSecretKey key) { // digitally sign our message body using our custom GnuPG cryptography context using (var ctx = new MyGnuPGContext ()) { message.Body = MultipartSigned.Create (ctx, key, DigestAlgorithm.Sha1, message.Body); } }