コード例 #1
0
 static void RsaDecrypt(string data, string keyContainerName, string keyFilePath, CspProviderFlags flags, bool showHelp)
 {
     if (showHelp)
     {
         List <Parameter> parms = new List <Parameter>
         {
             new Parameter {
                 Key = "data", Type = typeof(string), HelpText = "Text to decrypt"
             },
             new Parameter {
                 Key = "[kcn]", Type = typeof(string), HelpText = "Key container name"
             },
             new Parameter {
                 Key = "[keyFile]", Type = typeof(string), HelpText = "Path to key file"
             }
         };
         ConsoleColor defaultColor = Console.ForegroundColor;
         Console_WriteLine($"Parameter options for Rsa decrypt:\r\n", ConsoleColor.Green);
         WriteMethodParametersHelp(parms);
         Console.WriteLine("\r\nNote:");
         Console.WriteLine("Specify either key container name or path to key file.");
         Console.ForegroundColor = defaultColor;
     }
     else
     {
         Console.WriteLine("Decrypting data using Rsa algorithm.\r\n");
         Console.WriteLine(RsaHelpers.Decrypt(keyContainerName: keyContainerName, filePath: keyFilePath, flags: flags, value: data));
     }
 }
コード例 #2
0
        public void EncryptDecrypt_FromFile()
        {
            RsaHelpers.GenerateRsaKeys(pubPrivFilePath: _pubPrivFilePath, pubOnlyFilePath: _pubOnlyFilePath);
            string _cipherText = RsaHelpers.Encrypt(filePath: _pubOnlyFilePath, value: _plainText);

            Assert.AreEqual(_plainText, RsaHelpers.Decrypt(filePath: _pubPrivFilePath, value: _cipherText));
        }
コード例 #3
0
ファイル: CertManager.cs プロジェクト: LostSoulfly/BifrostLSF
        public static void CheckCertAuthority(string caPath = "")
        {
            if (string.IsNullOrWhiteSpace(caPath))
            {
                caPath = CertManager.caPath;
            }

            if (_certAuthority == null)
            {
                if (string.IsNullOrWhiteSpace(caPath))
                {
                    caPath = $"{Environment.MachineName}.ca";
                }
                else if (!caPath.ToLower().Contains(".ca"))
                {
                    caPath = Path.Combine(caPath, $"{Environment.MachineName}.ca");
                }

                var privCaKeyPath = caPath.ToLower().Replace(".ca", ".privkey");

                if (String.IsNullOrWhiteSpace(_certificateAuthorityPrivateKey))
                {
                    _certificateAuthorityPrivateKey = File.ReadAllText($"{privCaKeyPath}");
                }

                string caPrivKey = _certificateAuthorityPrivateKey;
                _certAuthority = (AsymmetricCipherKeyPair)RsaHelpers.PemDeserialize(caPrivKey);
            }

            if (String.IsNullOrWhiteSpace(_certificateAuthorityPublicKey))
            {
                _certificateAuthorityPublicKey = RsaHelpers.PemSerialize(_certAuthority.Public);
            }
        }
コード例 #4
0
ファイル: CertManager.cs プロジェクト: LostSoulfly/BifrostLSF
        public static (string certAuthority, string clientPrivateKey, byte[] clientSignKey) GenerateKeys(string caPath = "")
        {
            CheckCertAuthority(caPath);

            logger.Trace("Generating new keys..");
            var key        = new RSACryptoServiceProvider(2048);
            var parameters = key.ExportParameters(true);
            var pair       = DotNetUtilities.GetRsaKeyPair(parameters);

            string pub  = RsaHelpers.PemSerialize(pair.Public);
            string priv = RsaHelpers.PemSerialize(pair);

            if (_certAuthority != null)
            {
                logger.Trace("Signing keys..");
                var signature = RsaHelpers.SignData(Encoding.UTF8.GetBytes(pub), _certAuthority);

                logger.Trace("Verifying key signature...");
                if (RsaHelpers.VerifyData(Encoding.UTF8.GetBytes(pub), signature, _certAuthority))
                {
                    logger.Trace("Signature validated!");

                    return(_certificateAuthorityPublicKey, priv, signature);
                }
                logger.Error("Signature validation failed!");
            }
            return(null, null, null);
        }
コード例 #5
0
 public void Encrypt_NullAndEmptyInputs()
 {
     Assert.Throws <ArgumentException>(() => RsaHelpers.Encrypt());
     Assert.Throws <ArgumentException>(() => RsaHelpers.Encrypt(filePath: _pubOnlyFilePath));
     Assert.Throws <ArgumentException>(() => RsaHelpers.Encrypt(keyContainerName: _kcn));
     Assert.Throws <ArgumentException>(() => RsaHelpers.Encrypt(value: _plainText));
     Assert.Throws <ArgumentException>(() => RsaHelpers.Encrypt(filePath: _pubOnlyFilePath, value: string.Empty));
 }
コード例 #6
0
        public void EncryptDecrypt_FromContainer()
        {
            RsaHelpers.GenerateRsaKeys(keyContainerName: _kcn);
            string _encryptedText = RsaHelpers.Encrypt(keyContainerName: _kcn, value: _plainText);

            Assert.AreEqual(_plainText, RsaHelpers.Decrypt(keyContainerName: _kcn, value: _encryptedText));
            Assert.Throws <FormatException>(() => RsaHelpers.Decrypt(keyContainerName: _kcn, value: _encryptedText + "x"));
        }
コード例 #7
0
        public void EncryptDecrypt_FromFile_LongKey()
        {
            RsaHelpers.GenerateRsaKeys(pubPrivFilePath: _pubPrivFilePath, pubOnlyFilePath: _pubOnlyFilePath, keySize: 16384);
            _plainText = "password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__password__";
            string _cipherText = RsaHelpers.Encrypt(filePath: _pubOnlyFilePath, value: _plainText);

            Assert.AreEqual(_plainText, RsaHelpers.Decrypt(filePath: _pubPrivFilePath, value: _cipherText));
        }
コード例 #8
0
    static void RsaGenKey(string keyContainerName, string keyFile, int keySize, bool showHelp)
    {
        if (showHelp)
        {
            List <Parameter> parms = new List <Parameter>
            {
                new Parameter {
                    Key = "[kcn]", Type = typeof(string), HelpText = "Key container name"
                },
                new Parameter {
                    Key = "[keyFile]", Type = typeof(string), HelpText = "Path to key files"
                },
                new Parameter {
                    Key = "[keySize]", Type = typeof(int), HelpText = "Key size"
                }
            };
            ConsoleColor defaultColor = Console.ForegroundColor;
            Console_WriteLine($"Parameter options for Rsa genkey:\r\n", ConsoleColor.Green);
            WriteMethodParametersHelp(parms);
            Console.WriteLine("\r\nNote:");
            Console.WriteLine("Specify either key container name or path to key files.\r\n");
            Console.WriteLine("If keyFile is specified, action will create the following 2 files:");
            Console.WriteLine("1. {keyFile}.pubPriv (public and private key)");
            Console.WriteLine("2. {keyFile}.pubOnly (public key only)");
            Console.ForegroundColor = defaultColor;
        }
        else
        {
            Console.WriteLine("Generating Rsa key pair.\r\n");
            if (string.IsNullOrWhiteSpace(keyFile))
            {
                RsaHelpers.GenerateRsaKeys(keyContainerName: keyContainerName, keySize: keySize);
            }
            else
            {
                RsaHelpers.GenerateRsaKeys(keyContainerName: keyContainerName, pubPrivFilePath: $"{keyFile}.pubPriv", pubOnlyFilePath: $"{keyFile}.pubOnly", keySize: keySize);
            }

            if (!string.IsNullOrWhiteSpace(keyContainerName))
            {
                Console.WriteLine($"Created public/private keypair in user profile key store.");
            }
            if (!string.IsNullOrWhiteSpace(keyFile))
            {
                Console.WriteLine($"Created public/private keypair in [{keyFile}.pubPriv].");
                Console.WriteLine($"Created public key (only) in [{keyFile}.pubOnly].");
            }
        }
    }
コード例 #9
0
        public void GenerateRsaKeys_FileOnly()
        {
            if (File.Exists(_pubPrivFilePath))
            {
                File.Delete(_pubPrivFilePath);
            }
            if (File.Exists(_pubOnlyFilePath))
            {
                File.Delete(_pubOnlyFilePath);
            }

            RsaHelpers.GenerateRsaKeys((string)null, _pubPrivFilePath, _pubOnlyFilePath);
            Assert.IsTrue(File.Exists(_pubPrivFilePath));
            Assert.IsTrue(File.Exists(_pubOnlyFilePath));
        }
コード例 #10
0
        public void GenerateRsaKeys_ContainerAndFile()
        {
            if (File.Exists(_pubPrivFilePath))
            {
                File.Delete(_pubPrivFilePath);
            }
            if (File.Exists(_pubOnlyFilePath))
            {
                File.Delete(_pubOnlyFilePath);
            }

            RsaHelpers.GenerateRsaKeys(_kcn, _pubPrivFilePath, _pubOnlyFilePath);
            Assert.IsTrue(RsaHelpers.KeyContainerExists(_kcn));
            Assert.IsTrue(File.Exists(_pubPrivFilePath));
            Assert.IsTrue(File.Exists(_pubOnlyFilePath));
        }
コード例 #11
0
ファイル: CertManager.cs プロジェクト: LostSoulfly/BifrostLSF
        public static void GenerateCertificateAuthority(string caPath = "")
        {
            string privCaKeyPath;

            if (string.IsNullOrWhiteSpace(caPath))
            {
                caPath = CertManager.caPath;
            }

            if (string.IsNullOrWhiteSpace(caPath))
            {
                caPath = $"{Environment.MachineName}.ca";
            }
            else if (!caPath.ToLower().Contains(".ca"))
            {
                caPath = Path.Combine(caPath, $"{Environment.MachineName}.ca");
            }

            privCaKeyPath = caPath.ToLower().Replace(".ca", ".privkey");

            // This is the CA pub/priv key. If they don't exist for this machine, create new ones..
            if (!File.Exists($"{caPath}") || !File.Exists($"{privCaKeyPath}"))
            {
                logger.Info("CA files don't exist, generating..");

                var CertificateAuthority = new RSACryptoServiceProvider(2048);

                var parameters = CertificateAuthority.ExportParameters(true);
                var pair       = DotNetUtilities.GetRsaKeyPair(parameters);

                //write the CA pub/priv keys
                WriteFile($"{caPath}", RsaHelpers.PemSerialize(pair.Public));
                WriteFile($"{privCaKeyPath}", RsaHelpers.PemSerialize(pair));
                _certificateAuthorityPrivateKey = RsaHelpers.PemSerialize(pair);
                _certificateAuthorityPublicKey  = RsaHelpers.PemSerialize(pair.Public);
            }

            CheckCertAuthority(caPath);

            return;
        }
コード例 #12
0
ファイル: CertManager.cs プロジェクト: LostSoulfly/BifrostLSF
        public static RsaKeyParameters RetrievePublicCertificateByHash(string hash)
        {
            if (_knownCertificates == null)
            {
                LoadKnownCertificates();
            }

            lock (_knownCertificateLock)
            {
                var item = _knownCertificates.FirstOrDefault(x => x.hash == hash);

                if (item != null)
                {
                    return((RsaKeyParameters)RsaHelpers.PemDeserialize(item.publicKey));
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #13
0
        private static void Main(string[] args)
        {
            string action = "";

            string ca_path  = "";
            string key_name = "";

            BifrostNext.BifrostLSF.Utilities.LogVersion();

            OptionSet set = new OptionSet();

            set = new OptionSet()
            {
                { "action=", "Sets the action.", a => action = a.ToLower() },
                { "ca|ca-path=", "Sets the certificate authority file name.", c => ca_path = c },
                { "k|key|key-name=", "Sets the key file name(also used for signature file paths).", k => key_name = k },
                { "?|h|help", "Shows help.", h => ShowHelp(set) }
            };
            set.Parse(args);

            if (string.IsNullOrWhiteSpace(ca_path) && (action == "generate-ca" || action == "sign-key"))
            {
                Console.WriteLine("You have to specify a valid filename using --ca when using {0}!", action);
                Console.WriteLine("Try certmanager --help for more info.");

                return;
            }

            if (string.IsNullOrWhiteSpace(key_name) && (action == "generate-key" || action == "sign-key"))
            {
                Console.WriteLine("You have to specify a valid key name using --key-name when using {0}!", action);
                Console.WriteLine("Try certmanager --help for more info.");

                return;
            }
            AsymmetricCipherKeyPair Pair = null;

            if (action == "sign-key" || action == "generate-key")
            {
                if (!File.Exists(ca_path))
                {
                    ca_path += ".privkey";

                    if (!File.Exists(ca_path))
                    {
                        Console.WriteLine("Invalid file path \"{0}\".", ca_path);
                        return;
                    }
                }

                Console.Write("Importing certificate authority from \"{0}\"...", ca_path);
                string pubkey = File.ReadAllText(ca_path);

                var pair = RsaHelpers.PemDeserialize(pubkey);
                Console.WriteLine("done.");

                if (pair is AsymmetricKeyParameter)
                {
                    Console.WriteLine("The certificate authority file you have specified only contains the public key. When using sign-key, you have to use the .privkey file, not the .ca file.");
                    Console.WriteLine("Exiting.");
                    return;
                }

                Pair = (AsymmetricCipherKeyPair)pair;
            }

            switch (action)
            {
            case "generate-ca":
            {
                Console.WriteLine("Generating new RSA-2048 keypair...");
                var CertificateAuthority = new RSACryptoServiceProvider(2048);

                var parameters = CertificateAuthority.ExportParameters(true);
                var pair       = DotNetUtilities.GetRsaKeyPair(parameters);

                WriteFile(string.Format("{0}.ca", ca_path), RsaHelpers.PemSerialize(pair.Public));
                WriteFile(string.Format("{0}.privkey", ca_path), RsaHelpers.PemSerialize(pair));
                break;
            }

            case "generate-key":
            {
                Console.WriteLine("Generating new RSA-2048 keypair...");
                var key        = new RSACryptoServiceProvider(2048);
                var parameters = key.ExportParameters(true);
                var pair       = DotNetUtilities.GetRsaKeyPair(parameters);

                string pub  = RsaHelpers.PemSerialize(pair.Public);
                string priv = RsaHelpers.PemSerialize(pair);

                Console.WriteLine("Saving keypair...");
                WriteFile(string.Format("{0}.privkey", key_name), priv);
                WriteFile(string.Format("{0}.pub", key_name), pub);

                if (Pair != null)
                {
                    Console.WriteLine("Signing keypair...");
                    var signature = RsaHelpers.SignData(Encoding.UTF8.GetBytes(pub), Pair);
                    WriteFile(string.Format("{0}.sign", key_name), signature);

                    Console.WriteLine("Verifying signature...");

                    if (!RsaHelpers.VerifyData(Encoding.UTF8.GetBytes(pub), signature, Pair))
                    {
                        Console.WriteLine("Failed!");
                    }
                }
                break;
            }

            case "sign-key":
            {
                if (!File.Exists(key_name))
                {
                    key_name += ".pub";
                    if (!File.Exists(key_name))
                    {
                        Console.WriteLine("Invalid file path \"{0}\".", key_name);
                        return;
                    }
                }

                Console.WriteLine("Reading public key from \"{0}\"...", key_name);
                string pub = File.ReadAllText(key_name);

                Console.WriteLine("Signing key...");
                var signature = RsaHelpers.SignData(Encoding.UTF8.GetBytes(pub), Pair);

                Console.WriteLine("Saving signature...");

                if (key_name.Split('/', '\\').Last().Contains("."))
                {
                    key_name = string.Join(".", key_name.Split('.').Where(str => !key_name.EndsWith(str)));
                }
                key_name += ".sign";

                WriteFile(key_name, signature);
                break;
            }

            default:
                ShowHelp(set);
                break;
            }

            Console.WriteLine("CertManager done. Exiting...");
        }
コード例 #14
0
 public void Decrypt_withPubOnlyKey()
 {
     RsaHelpers.GenerateRsaKeys(pubOnlyFilePath: _pubOnlyFilePath);
     Assert.Throws <CryptographicException>(() => RsaHelpers.Decrypt(filePath: _pubOnlyFilePath, value: _encryptedText));
 }
コード例 #15
0
 public void Encrypt_UsingCspFlagsUseExistingKey_InvalidKey()
 {
     Assert.Throws <CryptographicException>(() => RsaHelpers.Encrypt(keyContainerName: "nosuchkeycontainername", flags: CspProviderFlags.UseExistingKey, value: _plainText));
     Assert.Throws <CryptographicException>(() => RsaHelpers.Decrypt(keyContainerName: "nosuchkeycontainername", flags: CspProviderFlags.UseExistingKey, value: _encryptedText));
 }
コード例 #16
0
 public void Decrypt_BadValue()
 {
     RsaHelpers.GenerateRsaKeys(pubPrivFilePath: _pubPrivFilePath);
     Assert.Throws <FormatException>(() => RsaHelpers.Decrypt(filePath: _pubPrivFilePath, value: _encryptedText + "x"));
 }
コード例 #17
0
 public void Decrypt_FromContainer_InvalidContainerName()
 {
     Assert.Throws <CryptographicException>(() => RsaHelpers.Decrypt(keyContainerName: "nosuchcontainer", value: _encryptedText));
 }
コード例 #18
0
 public void Encrypt_FromFile_BadFile()
 {
     Assert.Throws <DirectoryNotFoundException>(() => RsaHelpers.Encrypt(filePath: _badFilePath, value: _plainText));
 }
コード例 #19
0
 public void GenerateRsaKeys_NullAndEmptyInputs()
 {
     Assert.Throws <ArgumentException>(() => RsaHelpers.GenerateRsaKeys((string)null, null, null));
     Assert.Throws <ArgumentException>(() => RsaHelpers.GenerateRsaKeys(string.Empty, string.Empty, string.Empty));
 }
コード例 #20
0
 public void GenerateRsaKeys_FileOnly_BadPath()
 {
     Assert.Throws <DirectoryNotFoundException>(() => RsaHelpers.GenerateRsaKeys((string)null, _badFilePath, null));
     Assert.Throws <DirectoryNotFoundException>(() => RsaHelpers.GenerateRsaKeys((string)null, null, _badFilePath));
 }