private static void ExportKeyPair( Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSignatureSubpacketGenerator signHashGen = new PgpSignatureSubpacketGenerator(); signHashGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify | PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); signHashGen.SetPreferredSymmetricAlgorithms(false, new int[] { (int)SymmetricKeyAlgorithmTag.Aes256, (int)SymmetricKeyAlgorithmTag.Aes192, (int)SymmetricKeyAlgorithmTag.Aes128, (int)SymmetricKeyAlgorithmTag.Blowfish }); signHashGen.SetPreferredHashAlgorithms(false, new int[] { (int)HashAlgorithmTag.Sha512, (int)HashAlgorithmTag.Sha384, (int)HashAlgorithmTag.Sha256, (int)HashAlgorithmTag.Sha224, (int)HashAlgorithmTag.RipeMD160, (int)HashAlgorithmTag.Tiger192 }); signHashGen.SetPreferredCompressionAlgorithms(false, new int[] { (int)CompressionAlgorithmTag.ZLib, (int)CompressionAlgorithmTag.BZip2, (int)CompressionAlgorithmTag.Zip }); signHashGen.SetTrust(false, 8, 255); PgpSignatureSubpacketVector signSubpktVector = signHashGen.Generate(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.PositiveCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.UtcNow, identity, SymmetricKeyAlgorithmTag.Aes256, passPhrase, signSubpktVector, //null, null, new SecureRandom() ); secretKey.Encode(secretOut); if (armor) { secretOut.Close(); publicOut = new ArmoredOutputStream(publicOut); } PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); if (armor) { publicOut.Close(); } }
private static void ExportKeyPair(Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSecretKey secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, identity, SymmetricKeyAlgorithmTag.Cast5, 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 void SaveKey(PgpSecretKey key, string publicPath, string secretPath) { using (FileStream pubStream = new FileStream(publicPath, FileMode.Create)) key.PublicKey.Encode(pubStream); using (FileStream secStream = new FileStream(secretPath, FileMode.Create)) key.Encode(secStream); }
public Task <string> GenerateGPGKey(string identifier, string password, int bits = 3072) { return(Task.Run(() => { using (var ms = new MemoryStream()) { var s = new ArmoredOutputStream(ms); var kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), bits, 25)); var kp = kpg.GenerateKeyPair(); var secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, identifier, SymmetricKeyAlgorithmTag.Cast5, password.ToCharArray(), null, null, new SecureRandom() ); secretKey.Encode(s); s.Close(); ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return reader.ReadToEnd(); } })); }
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); }
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(); }
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(); }
/// <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); } }
/// <summary> /// Final key pair creation /// </summary> /// <param name="secretOut"></param> /// <param name="publicOut"></param> /// <param name="publicKey"></param> /// <param name="privateKey"></param> /// <param name="identity"></param> /// <param name="passphrase"></param> /// <param name="armor"></param> public static void ExportKeyPair( Stream secretOut, Stream publicOut, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passphrase, bool armor) { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } // Prepare a strong Secure Random with seed SecureRandom secureRandom = PgpEncryptionUtil.GetSecureRandom(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.UtcNow, identity, SymmetricKeyAlgorithmTag.Aes256, passphrase, null, null, secureRandom ); secretKey.Encode(secretOut); if (armor) { secretOut.Dispose(); publicOut = new ArmoredOutputStream(publicOut); } PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); if (armor) { publicOut.Dispose(); } }
/// <summary> /// Returns actual secret key, in armored ASCII format. /// </summary> /// <param name="key">Key to retrieve.</param> /// <returns>Armored ASCII format representing private key.</returns> public static string GetAsciiArmoredSecretKey(PgpSecretKey key) { using (var memStream = new MemoryStream()) { using (var armored = new ArmoredOutputStream(memStream)) { key.Encode(armored); armored.Flush(); } memStream.Flush(); memStream.Position = 0; using (var sr = new StreamReader(memStream)) { return(sr.ReadToEnd()); } } }
public void UpdateDbSecretKey(PgpSecretKey key, string keyExportName) { Stream outFile = File.Create(keyExportName); Stream outArmor = new ArmoredOutputStream(outFile); string secKey = string.Empty; key.Encode(outArmor); outArmor.Close(); using (StreamReader rdr = new StreamReader(outFile)) { rdr.BaseStream.Position = 0; secKey = rdr.ReadToEnd(); } KeyStores updKey = m_keyStoreDb.KeyStores.Find(key.KeyId); updKey.ArmouredKeyFile = secKey; m_keyStoreDb.SaveChanges(); }
private Keypair Armor(AsymmetricCipherKeyPair keyPair, string email) { var privateKey = keyPair.Private; var publicKey = keyPair.Public; var memOut = new MemoryStream(); var secretOut = new ArmoredOutputStream(memOut); var secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, email, SymmetricKeyAlgorithmTag.Null, null, null, null, new SecureRandom() ); secretKey.Encode(secretOut); secretOut.Close(); var memPublicOut = new MemoryStream(); Stream publicOut = new ArmoredOutputStream(memPublicOut); var key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); var privateKeyStr = Encoding.Default.GetString(memOut.ToArray()); var publicKeyStr = Encoding.Default.GetString(memPublicOut.ToArray()); var pair = new Keypair { PrivateKey = privateKeyStr, PublicKey = publicKeyStr }; return(pair); }
private Keypair Armor(AsymmetricCipherKeyPair keyPair, String email) { AsymmetricKeyParameter privateKey = keyPair.Private; AsymmetricKeyParameter publicKey = keyPair.Public; MemoryStream memOut = new MemoryStream(); ArmoredOutputStream secretOut = new ArmoredOutputStream(memOut); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.Now, email, SymmetricKeyAlgorithmTag.Null, null, null, null, new SecureRandom() ); secretKey.Encode(secretOut); secretOut.Close(); MemoryStream memPublicOut = new MemoryStream(); Stream publicOut = new ArmoredOutputStream(memPublicOut); PgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); publicOut.Close(); String privateKeyStr = System.Text.Encoding.Default.GetString(memOut.ToArray()); String publicKeyStr = System.Text.Encoding.Default.GetString(memPublicOut.ToArray()); Keypair pair = new Keypair(); pair.PrivateKey = privateKeyStr; pair.PublicKey = publicKeyStr; return(pair); }
private static void ExportKeyPair( AsymmetricCipherKeyPair keyPair, string userName, char[] passPhrase, out string publicKey, out string privateKey) { PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, keyPair.Public, keyPair.Private, DateTime.Now, userName, SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom()); using (MemoryStream stream = new MemoryStream()) { using (ArmoredOutputStream outStream = new ArmoredOutputStream(stream)) { secretKey.Encode(outStream); } privateKey = Encoding.ASCII.GetString(stream.ToArray()); } using (MemoryStream stream = new MemoryStream()) { using (ArmoredOutputStream outStream = new ArmoredOutputStream(stream)) { secretKey.PublicKey.Encode(outStream); } publicKey = Encoding.ASCII.GetString(stream.ToArray()); } }
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(); }
public void TestMethod1() { string secretKeyFile = @"-----BEGIN PGP PRIVATE KEY BLOCK----- Version: BCPG C# v1.7.4137.9688 lQc0BFTbeXUBEACgRx6VZYo0M8Vhv7D+ukhEPAIQHmbv41oae3vCINyEk+qdlkRQ qa+prxLyM3wvHi2WyUQUG67TgEhOKGiu5iRT3SDf7/o2+GyzkcJxVf4SsauvPNM9 chRtayHhtgNbkz+qS3G+zGgO52ck/W9J4EvxzeMaV+hN9TJm4nurZ52ZxqjxXDX2 9/loc639n/OCQTx3BKNPwt8TE3vaHUi7QScfL3Yj/zL3FDR8ct2Ymh4xWM2GjTb6 3mPWAt0pOfFOS0wxWpWYg9gl3p6iw8Sl7O5cqlxNlpA3b1b4mdF1v96kNfxkT4MI lNhfeNQ6e9cUZbMSJxt/gzY29xERa7kYpVC5QOgI57VZg/hsO8Uoh55H7LgKQ8Zw y4IQ/BZxBvMgBMVjYOHyhfC1rx81btPZbMHN6rwQFlXgXc+pbKTSzxmsCh00lc9z Ib653ByqHLeF4H++T6aU7L15C+8xOuFctF1wYLGjnr6ZX5tZINuyOqq2ifQ0wkkk xu7Ev/AIhE9oOYmn8HfwbUZOb28FbSqYssxzI76QTaPzOULJ+q/M94Z6WC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PlD8gx7ZDdAB9bMOQ6ZgIzeyz3H8MkrO03TJJ2ZQ /zw8KKfzGzE89hO7z7cX+0UNODY++AbS21+0Cc7eN/DAehe0bjedYg8PPJ/xJ7uL A+GoSqVuY2ilY2E3A5fw+x57Of8FibUlCx1lyYFaAyQ87kivNSsD9S/PyZ2q516h GIrQTgk34Pda4qZ/PtWGcJoT6mwHTz85HqBp0NO4/NvJG+ySw5kqVaR0W8yJ7Jat mqcuSIOyrw9X69uzoIzMNv2vmzN3F3czg5VGRcQVcDU0GVhq8VFUBBhQLUGiNFJM QO8KIwcFabhhu5ymAGTnyBBfetDr+0pqOLol0WKDFz4IF9DeLnESRqcl00Evx7/o viUOB7IZCHwFa3yRoyM8ZC2/p3phK8dreV2xPaPyyNbkl0768Spoa7s+59D9MoXC TP0+SvCeBf8jJpJ6/O/xUAvyPRvyk75+H6kOu0+4G7erK0AABb1WQvmYah1wPzD3 1ptfooPAKf193dtiOC2AoJdGu/oFmffgh0WhcbPCKlHv0zecx0DTGDkAQWAe9L+i BQ7R6w== =Z4JC -----END PGP PRIVATE KEY BLOCK-----"; File.WriteAllText(Path.Combine(@"C:\Users\John\BcPGP", "testuser1@example_com_secret.asc"), secretKeyFile); MemoryStream msSec = new MemoryStream(Encoding.UTF8.GetBytes(secretKeyFile)); PgpSecretKeyRing secRing = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(msSec)); char[] passPhrase = new char[] { 't', 'e', 's', 't', 'u', 's', 'e', 'r' }; PgpPublicKeyRing pubRing = new PgpPublicKeyRing(secRing.GetPublicKey().GetEncoded()); PgpPublicKeyRing newRing = new PgpPublicKeyRing( new MemoryStream(RevokePublicKey(secRing.GetSecretKey(), passPhrase, pubRing.GetPublicKey(), true))); msSec.Close(); Assert.IsTrue(newRing.GetPublicKey().IsRevoked()); Stream fos = File.Create(@"C:\Users\John\BcPGP\RevokedKey.asc"); ArmoredOutputStream aOut = new ArmoredOutputStream(fos); newRing.Encode(aOut); aOut.Close(); fos.Close(); PgpSecretKey newSecret = PgpSecretKey.ReplacePublicKey(secRing.GetSecretKey(), newRing.GetPublicKey()); Stream foSec = File.Create(@"C:\Users\John\BcPGP\SecretRevokedKey.asc"); ArmoredOutputStream sOut = new ArmoredOutputStream(foSec); newSecret.Encode(sOut); sOut.Close(); foSec.Close(); Assert.IsTrue(newSecret.PublicKey.IsRevoked()); }
/// <summary> /// Export the public/private keypair. /// </summary> /// <param name="secretPath"> /// The secret output path. /// </param> /// <param name="publicPath"> /// The public output path. /// </param> /// <param name="publicKey"> /// The public key. /// </param> /// <param name="privateKey"> /// The private key. /// </param> /// <param name="identity"> /// The identity for the key. /// </param> /// <param name="passPhrase"> /// The pass phrase for the secret key file. /// </param> /// <param name="creationDate"> /// Date/time the key was created. /// </param> /// <param name="publicKeyAlgorithm"> /// The public key algorithm. /// </param> /// <param name="symmetricAlgorithm"> /// The symmetric key algorithm. /// </param> /// <param name="armor"> /// Should the keys be written using ASCII armor? /// </param> /// <returns> /// The <see cref="PgpSecretKey"/>. /// </returns> public static PgpSecretKey ExportKeyPair( string secretPath, string publicPath, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, string identity, char[] passPhrase, DateTime creationDate, PublicKeyAlgorithmTag publicKeyAlgorithm = PublicKeyAlgorithmTag.RsaGeneral, SymmetricKeyAlgorithmTag symmetricAlgorithm = SymmetricKeyAlgorithmTag.Aes256, bool armor = true) { var secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, publicKeyAlgorithm, publicKey, privateKey, creationDate, identity, symmetricAlgorithm, passPhrase, null, null, new SecureRandom()); if (secretPath != null) { using (var secretOut = (Stream) new FileInfo(secretPath).OpenWrite()) { var secretOutputStream = secretOut; if (armor) { secretOutputStream = new ArmoredOutputStream(secretOut); } secretKey.Encode(secretOutputStream); secretOutputStream.Flush(); if (armor) { secretOutputStream.Dispose(); } } } if (publicPath != null) { using (var publicOut = (Stream) new FileInfo(publicPath).OpenWrite()) { var publicOutputStream = publicOut; if (armor) { publicOutputStream = new ArmoredOutputStream(publicOut); } var key = secretKey.PublicKey; key.Encode(publicOutputStream); publicOutputStream.Flush(); if (armor) { publicOutputStream.Dispose(); } } } return(secretKey); }