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(); }
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(); }
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(); }
/// <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 public PGP key, in armored ASCII format. /// </summary> /// <param name="key">Key to retrieve.</param> /// <returns>Armored ASCII format representing public key</returns> public static string GetAsciiArmoredPublicKey(PgpPublicKey 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()); } } }
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); }
/// <summary> /// Write the <see cref="PgpPublicKey"/> to file. /// </summary> /// <param name="outputPath"> /// Path to write the key to. /// </param> /// <param name="publicKey"> /// The key to write. /// </param> /// <param name="armor"> /// Should the file be written as ASCII armor? /// </param> public static void WriteKey(string outputPath, PgpPublicKey publicKey, bool armor) { using (var fs = new FileStream(outputPath, FileMode.Create)) { var outputStream = (Stream)fs; if (armor) { outputStream = new ArmoredOutputStream(fs); } publicKey.Encode(outputStream); outputStream.Flush(); if (armor) { outputStream.Dispose(); } } }
public void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); var firstUserId = pgpPub.GetPublicKey().GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); // // write a public key // MemoryStream bOut = new MemoryStream(); pgpPub.Encode(bOut); Assert.AreEqual(testPubKey, bOut.ToArray()); // // Read the public key // PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3); // // write a V3 public key // bOut = new MemoryStream(); pgpPubV3.Encode(bOut); // // Read a v3 private key // var passP = "FIXCITY_QA"; { PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3); PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey(); PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP); // // write a v3 private key // bOut = new MemoryStream(); pgpPriv2.Encode(bOut); byte[] result = bOut.ToArray(); Assert.AreEqual(testPrivKeyV3, result); } // // Read the private key // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass); // // write a private key // bOut = new MemoryStream(); pgpPriv.Encode(bOut); Assert.AreEqual(testPrivKey, bOut.ToArray()); // // test encryption // /*var c = pubKey; * * // c.Init(Cipher.ENCRYPT_MODE, 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 // var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(sig1); var signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); literalMessage.GetStream().CopyTo(Stream.Null); Assert.True(signedMessage.Verify(pgpPub.GetPublicKey(signedMessage.KeyId))); // // encrypted message - read subkey // pgpPriv = new PgpSecretKeyRing(subKey); // // encrypted message // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(enc1); var encKeyId = encryptedMessage.KeyIds.First(); pgpPrivKey = pgpPriv.GetSecretKey(encKeyId).ExtractPrivateKey(pass); compressedMessage = (PgpCompressedMessage)encryptedMessage.DecryptMessage(pgpPrivKey); literalMessage = (PgpLiteralMessage)compressedMessage.ReadMessage(); Assert.AreEqual("test.txt", literalMessage.FileName); byte[] bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(text, bytes); // // encrypt - short message // byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; MemoryStream cbOut = new MemoryStream(); var messageGenerator = new PgpMessageGenerator(cbOut); using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5)) { encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId)); using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow)) { literalStream.Write(shortText); } } cbOut.Position = 0; encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut); pgpPrivKey = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass); //Assert.AreEqual(SymmetricKeyAlgorithmTag.Cast5, ((PgpPublicKeyEncryptedData)encryptedMessage.Methods[0]).GetSymmetricAlgorithm(pgpPrivKey)); literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey); Assert.AreEqual("", literalMessage.FileName); bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(shortText, bytes); // // encrypt // cbOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(cbOut); using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5)) { encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId)); using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow)) { literalStream.Write(text); } } cbOut.Position = 0; encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut); pgpPrivKey = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass); literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey); bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(text, bytes); // // 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 // var passPhrase = "hello"; var rsa = RSA.Create(1024); var keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase); var secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey(); PgpPublicKey key = new PgpPublicKey(secretKey); firstUserId = key.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase); key = PgpPublicKey.RemoveCertification(key, firstUserId, firstUserId.SelfCertifications[0]); Assert.NotNull(key); byte[] keyEnc = key.GetEncoded(); key = PgpPublicKey.AddCertification(key, firstUserId.UserId, firstUserId.SelfCertifications[0]); keyEnc = key.GetEncoded(); var revocation = PgpCertification.GenerateKeyRevocation( secretKey, secretKey.ExtractPrivateKey(passPhrase), key); key = PgpPublicKey.AddCertification(key, revocation); keyEnc = key.GetEncoded(); PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc); key = tmpRing.GetPublicKey(); revocation = key.KeyCertifications.Where(c => c.SignatureType == PgpSignatureType.KeyRevocation).FirstOrDefault(); Assert.NotNull(revocation); Assert.IsTrue(revocation.Verify(key)); // // use of PgpKeyPair // PgpKeyPair pgpKp = new PgpKeyPair(rsa, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; k1.GetEncoded(); MixedTest(k2, k1); // // key pair generation - AES_256 encryption. -- XXX // //kp = kpg.GenerateKeyPair(); rsa = RSA.Create(1024); keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase /*, encAlgorithm: PgpSymmetricKeyAlgorithm.Aes256*/); secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey(); secretKey.ExtractPrivateKey(passPhrase); secretKey.Encode(new MemoryStream()); // // secret key password changing. // const string newPass = "******"; secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass); secretKey.ExtractPrivateKey(newPass); secretKey.Encode(new MemoryStream()); key = new PgpPublicKey(secretKey); key.Encode(new MemoryStream()); firstUserId = key.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); pgpPrivKey = secretKey.ExtractPrivateKey(newPass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); DateTime testDateTime = new DateTime(1973, 7, 27); bOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(bOut); using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip)) using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime)) { literalStream.Write(dataBytes); } // // verify generated signature // bOut.Position = 0; compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut); signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDateTime, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(secretKey)); // // signature generation - version 3 // bOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(bOut); using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip)) using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1, version: 3)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime)) { literalStream.Write(dataBytes); } // // verify generated signature // bOut.Position = 0; compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut); signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDateTime, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(secretKey)); // // extract PGP 8 private key // pgpPriv = new PgpSecretKeyRing(pgp8Key); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass); // // other sig tests // PerformTestSig(PgpHashAlgorithm.Sha256, secretKey, pgpPrivKey); PerformTestSig(PgpHashAlgorithm.Sha384, secretKey, pgpPrivKey); PerformTestSig(PgpHashAlgorithm.Sha512, secretKey, pgpPrivKey); }