Пример #1
1
        public static void ExportImportPublicOnly()
        {
            byte[] expectedExport = ByteUtils.HexToByteArray(
                "0602000000a40000525341310004000001000100e19a01644b82962a224781d1f60c2cc373b"
                + "798df541343f63c638f45fa96e11049c8d9e88bd56483ec3c2d56e9460d2b1140191841761c1523840221b0e"
                + "b6401dc4d09c54bf75cea25d9e191572fb2ec92c3559b35b3ef3fa695171bb1fddeb469792e49f0d17c769d0"
                + "a37f6a4a6584af39878eb21f9ba9eae8be9c39eac6ae0");

            byte[] exported;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.CspTestKey);

                exported = rsa.ExportCspBlob(includePrivateParameters: false);
            }

            Assert.Equal(expectedExport, exported);

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(exported);

                byte[] exported2 = rsa.ExportCspBlob(includePrivateParameters: false);

                Assert.Equal(exported, exported2);

                Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(includePrivateParameters: true));
            }
        }
            /// <summary>Extracts a <see cref="Key"/> from the given certificate.</summary>
            public Initializer FromCertificate(X509Certificate2 certificate)
            {
                // Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24.
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

                byte[] privateKeyBlob = rsa.ExportCspBlob(true);
                Key = new RSACryptoServiceProvider();
                Key.ImportCspBlob(privateKeyBlob);
                return(this);
            }
Пример #3
0
 public static StrongNameKeyPair GenerateStrongNameKeyPair()
 {
     using (var provider = new RSACryptoServiceProvider(1024, new CspParameters {
         KeyNumber = 2
     }))
     {
         byte[] keyPairArray = provider.ExportCspBlob(true);
         return(new StrongNameKeyPair(keyPairArray));
     }
 }
Пример #4
0
        public WobUtils(String iss, X509Certificate2 cert)
        {
            issuer  = iss;
            origins = WebConfigurationManager.AppSettings["Origins"].Split(' ');
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;

            byte[] privateKeyBlob = rsa.ExportCspBlob(true);
            key = new RSACryptoServiceProvider();
            key.ImportCspBlob(privateKeyBlob);
        }
Пример #5
0
        public static DiaryHeader CreateHeader(RSACryptoServiceProvider rsa, string passphrase)
        {
            var header = new DiaryHeader();

            header.PublicKey = rsa.ExportCspBlob(false);
            var privateBlob = rsa.ExportCspBlob(true);

            var rij = Rijndael.Create();

            var encryptedStream = new MemoryStream();

            using (var cs = new CryptoStream(encryptedStream, rij.CreateEncryptor(GetKey(passphrase), GetIV(passphrase)), CryptoStreamMode.Write))
            {
                cs.Write(privateBlob, 0, privateBlob.Length);
            }

            header.PrivateKeyEncrypted = encryptedStream.ToArray();

            return(header);
        }
Пример #6
0
        static void Test1()
        {
            var rsa        = new RSACryptoServiceProvider(2048);
            var pubKey     = rsa.ExportCspBlob(false);
            var privateKey = rsa.ExportCspBlob(true);

            var    b = new RSACrypto().Encrypt(pubKey, System.Text.Encoding.UTF8.GetBytes("hello."));
            var    c = new RSACrypto().Decrypt(privateKey, b);
            string s = string.Empty;



            //var rsa1 = new RSACryptoServiceProvider(1024);
            //rsa1.ImportCspBlob(pubKey);
            //var secret = rsa1.Encrypt(System.Text.Encoding.UTF8.GetBytes("hello."), false);

            //var rsa2 = new RSACryptoServiceProvider(1024);
            //rsa2.ImportCspBlob(privateKey);
            //var plain = rsa2.Decrypt(secret, false);
        }
Пример #7
0
        // generate private, public key pair
        public static Tuple <string, string> GenerateKeyPair()
        {
            string privateKey;
            string publicKey;

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    privateKey = Convert.ToBase64String(rsa.ExportCspBlob(true));
                    publicKey  = Convert.ToBase64String(rsa.ExportCspBlob(false));
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }

            return(new Tuple <string, string>(privateKey, publicKey));
        }
Пример #8
0
        public string CreateKey()
        {
            using (var publicPrivate = new RSACryptoServiceProvider())
            {
                File.WriteAllBytes(_signPath, publicPrivate.ExportCspBlob(true));
            }

            return(LoadKey()
                ? _publicKey
                : null);
        }
Пример #9
0
        public static void Main(string[] args)
        {
            if (File.Exists("key_ras") || File.Exists("key_ras.pub"))
            {
                Console.WriteLine("key pairs existed!");
            }
            var rsa = new RSACryptoServiceProvider();

            File.WriteAllText("key_ras", rsa.ToXmlString(true));
            File.WriteAllText("key_ras.pub", Convert.ToBase64String(rsa.ExportCspBlob(false)));
        }
Пример #10
0
            public static AsymmetricEncryptionKey CreateFromString(String key, Boolean containsPrivateKey)
            {
                var cspBlob = HexEncoding.GetBytes(key);

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportCspBlob(cspBlob);
                    var    publicKey  = BitConverter.ToString(rsa.ExportCspBlob(false)).Replace("-", "");
                    String privateKey = "";
                    if (containsPrivateKey)
                    {
                        privateKey = BitConverter.ToString(rsa.ExportCspBlob(true)).Replace("-", "");
                    }
                    return(new AsymmetricEncryptionKey()
                    {
                        PublicKey = publicKey,
                        PrivateKey = privateKey,
                    });
                }
            }
        public CertInfo(X509Certificate2 cert)
        {
            Issuer       = cert.Issuer;
            Subject      = cert.Subject;
            SerialNumber = cert.SerialNumber;
            NotBefore    = cert.NotBefore;
            NotAfter     = cert.NotAfter;
            RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey;

            CspBlob = provider.ExportCspBlob(true);
        }
Пример #12
0
        /// <summary>
        /// Generate private key.
        /// </summary>
        /// <returns>private key as string</returns>
        public static string CreatePrivateKey()
        {
            CspParameters cspParams = new CspParameters {
                ProviderType = 1
            };

            using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams);
            string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));

            return(privateKey);
        }
Пример #13
0
        public HandshakeWindow()
        {
            InitializeComponent();
            instructions.Text = "Welcome to FaceCrypt, a program to allow for secure communications with your friends over Facebook Chat (and other IM applications).\nThis program is open-source, so you can (AND SHOULD) validate that we didn't put any backdoors in it (we reside in the US, so we may be required by law to install backdoors)\nThe only way to protect against backdoors is to analyze the code yourself.\nThis software makes use of public key cryptography to securely exchange encryption keys between two people over an insecure connection (such as Facebook), which enables future communications over the same medium.\nThis software relies on a secondary out-of-band message channel (other than Facebook), to verify your friend's identity.\nTo start, we have generated public/private key combination.\n You should NEVER give your private key to anyone, but give your public key to your friend, so they can verify your identity.\nWe will start by exchanging public keys. Your public key has been copied to your clipboard. Paste this key into the Facebook chat window, and send it.\n\n\n Copy and paste your friend's public key into this window.";
            msp = new RSACryptoServiceProvider();
            Clipboard.SetText(Convert.ToBase64String(msp.ExportCspBlob(false)));
            DispatcherTimer timer = new DispatcherTimer();

            timer.Interval = TimeSpan.FromSeconds(1);
            ApplicationCommands.Paste.CanExecuteChanged += Paste_CanExecuteChanged;
        }
Пример #14
0
        static void ConvertPfx2Snk()
        {
            X509Certificate2         cert     = new X509Certificate2(@"C:\Users\baenz\source\repos\ArtsCouncil\ArtsCouncil.Plugins\Perplex.pfx", "Perplex4ever", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey;

            byte[] array = provider.ExportCspBlob(!provider.PublicOnly);
            using (FileStream fs = new FileStream(@"C:\Users\baenz\source\repos\ArtsCouncil\ArtsCouncil.Plugins\Perplex.snk", FileMode.Create, FileAccess.Write))
            {
                fs.Write(array, 0, array.Length);
            }
        }
Пример #15
0
        public GroupCertificateVerificationTest()
        {
            _private_key = new RSACryptoServiceProvider(512);
            byte[] blob = _private_key.ExportCspBlob(false);
            RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();

            rsa_pub.ImportCspBlob(blob);
            CertificateMaker cm = new CertificateMaker("US", "UFL", "ACIS", "David Wolinsky",
                                                       "*****@*****.**", rsa_pub, "davidiw");

            _ca_cert = cm.Sign(cm, _private_key);
        }
Пример #16
0
        /// <summary>
        /// Generate public key using private key.
        /// </summary>
        /// <param name="privateKey">Private key as string</param>
        /// <returns>public key as string</returns>
        public static string CreatePublicKey(string privateKey)
        {
            CspParameters cspParams = new CspParameters {
                ProviderType = 1
            };

            using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
            rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
            string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));

            return(publicKey);
        }
        private RSACryptoServiceProvider getCertificateKey(X509Certificate2 certificate)
        {
            RSACryptoServiceProvider key = certificate.PrivateKey as RSACryptoServiceProvider;

            byte[]        privateKeyBlob = key.ExportCspBlob(true);
            CspParameters cp             = new CspParameters(24);

            key = new RSACryptoServiceProvider(cp);
            key.ImportCspBlob(privateKeyBlob);

            return(key);
        }
Пример #18
0
        /// <summary>
        /// Generates a 1024 bit the strong-name key pair that can be written to an SNK file.
        /// </summary>
        /// <returns>A strong-name key pair array.</returns>
        public static byte[] GenerateStrongNameKeyPair()
        {
#pragma warning disable S4426 // Cryptographic keys should not be too short
            using (var provider = new RSACryptoServiceProvider(1024, new CspParameters()
            {
                KeyNumber = 2
            }))
#pragma warning restore S4426 // Cryptographic keys should not be too short
            {
                return(provider.ExportCspBlob(!provider.PublicOnly));
            }
        }
Пример #19
0
 public static byte[] ExportBlob(bool machineLevel, string containerName, KeyNumber keyNumber, bool includePrivateParameters)
 {
     using (var rspCsp = new RSACryptoServiceProvider(new CspParameters
     {
         KeyContainerName = containerName,
         KeyNumber = (int)keyNumber,
         Flags = CspProviderFlags.UseExistingKey | (machineLevel ? CspProviderFlags.UseMachineKeyStore : 0)
     }))
     {
         return(rspCsp.ExportCspBlob(includePrivateParameters));
     }
 }
        private void GenKey()
        {
            switch (m_asynAlg)
            {
            case SMSAsyncAlgo.RSA:
                //  var csp = new CspParameters(1, "Microsoft Strong Cryptographic Provider");
                m_rsa       = new RSACryptoServiceProvider();// 2048, csp);
                m_publicKey = m_rsa.ExportCspBlob(false);

                break;
            }
        }
Пример #21
0
        private void GenerateKeyFile(string filename)
        {
            CspParameters parms = new CspParameters();

            parms.KeyNumber = 2;
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(parms);

            byte[] array = provider.ExportCspBlob(!provider.PublicOnly);

            using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                fs.Write(array, 0, array.Length);
        }
Пример #22
0
        /// <summary>
        /// Creates new instance of Pkcs11RsaProvider class
        /// </summary>
        /// <param name="certContext">Internal context for Pkcs11X509Certificate2 class</param>
        internal Pkcs11RsaProvider(Pkcs11X509CertificateContext certContext)
        {
            _certContext            = certContext ?? throw new ArgumentNullException(nameof(certContext));
            base.KeySizeValue       = _certContext.CertificateInfo.ParsedCertificate.GetRSAPublicKey().KeySize;
            base.LegalKeySizesValue = new KeySizes[] { new KeySizes(base.KeySizeValue, base.KeySizeValue, 0) };

            // Load csp blob from public key RSACryptoServiceProvider
            X509Certificate2         cert      = new X509Certificate2(certContext.CertificateInfo.RawData);
            RSACryptoServiceProvider RSApubkey = (RSACryptoServiceProvider)cert.PublicKey.Key;

            this._cspBlob = RSApubkey.ExportCspBlob(false);
        }
Пример #23
0
 private void BeforeSerialization()
 {
     // Encrypt plaintext password before saving.
     if (!string.IsNullOrEmpty(Password))
     {
         UnicodeEncoding          byteConverter = new UnicodeEncoding();
         byte[]                   dataToEncrypt = byteConverter.GetBytes(Password);
         RSACryptoServiceProvider rsa           = new RSACryptoServiceProvider();
         blob = rsa.ExportCspBlob(true);
         encryptedPassword = rsa.Encrypt(dataToEncrypt, false);
     }
 }
Пример #24
0
        public static byte[] GetEncrypted(string value, bool OAEP, out byte[] cspBlob)
        {
            CspParameters cspParams = new CspParameters();

            cspParams.KeyContainerName = "RainstormStudios";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams))
            {
                rsa.PersistKeyInCsp = true;
                cspBlob             = rsa.ExportCspBlob(true);
                return(rsa.Encrypt(Array.ConvertAll <char, byte>(value.ToCharArray(), new Converter <char, byte>(Convert.ToByte)), OAEP));
            }
        }
Пример #25
0
        public void TestRsa()
        {
            var dwKeySize = 2048;

            using (var originRsaProvider = new RSACryptoServiceProvider(dwKeySize))
            {
                var rsaKey = new RsaKeys
                {
                    PrivateKey        = originRsaProvider.ExportCspBlob(true),
                    PublicKey         = originRsaProvider.ExportCspBlob(false),
                    DoubleWordKeySize = originRsaProvider.KeySize
                };

                var publicProvider  = rsaKey.CreateRsaPublicProvider();
                var privateProvider = rsaKey.CreateRsaProvider();

                var originalEncyptedText = originRsaProvider.Encrypt(Encoding.UTF8.GetBytes(testData), true).EncodeBase64();
                var publicEncyptedText   = publicProvider.Encrypt(Encoding.UTF8.GetBytes(testData), true).EncodeBase64();
                var privateEncyptedText  = privateProvider.Encrypt(Encoding.UTF8.GetBytes(testData), true).EncodeBase64();

                //self
                var originalDecyptedText1 = Encoding.UTF8.GetString(originRsaProvider.Decrypt(originalEncyptedText.DecodeBase64ToByteArray(), true));
                var privateDecyptedText1  = Encoding.UTF8.GetString(privateProvider.Decrypt(privateEncyptedText.DecodeBase64ToByteArray(), true));

                Assert.AreEqual(testData, originalDecyptedText1);
                Assert.AreEqual(testData, privateDecyptedText1);

                // from private
                var originalDecyptedText2 = Encoding.UTF8.GetString(originRsaProvider.Decrypt(privateEncyptedText.DecodeBase64ToByteArray(), true));
                var privateDecyptedText2  = Encoding.UTF8.GetString(privateProvider.Decrypt(originalEncyptedText.DecodeBase64ToByteArray(), true));
                Assert.AreEqual(testData, originalDecyptedText2);
                Assert.AreEqual(testData, privateDecyptedText2);

                // from public
                var originalDecyptedText3 = Encoding.UTF8.GetString(originRsaProvider.Decrypt(publicEncyptedText.DecodeBase64ToByteArray(), true));
                var privateDecyptedText3  = Encoding.UTF8.GetString(privateProvider.Decrypt(publicEncyptedText.DecodeBase64ToByteArray(), true));
                Assert.AreEqual(testData, originalDecyptedText3);
                Assert.AreEqual(testData, privateDecyptedText3);
            }
        }
Пример #26
0
        // Generating assymetric RSA keys (4096 bits) method

        public static void GenerateNewPairKey() // better to use offline & on another device.
        {
            if (File.Exists(_folderPath + "privateKey") || File.Exists(_folderPath + "publicKey"))
            {
                Print("Already existing RSA key files has been found in app folder. Please move them or rename them. RSA Key Gen has been aborted");
                return;
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096);

            byte[] _privateKey = rsa.ExportCspBlob(true);
            byte[] _publicKey  = rsa.ExportCspBlob(false);
            File.WriteAllBytes(_folderPath + "privateKey", rsa.ExportCspBlob(true));
            File.WriteAllBytes(_folderPath + "publicKey", rsa.ExportCspBlob(false));
            rsa.Clear();
            if (File.Exists(_folderPath + "QRMYKEYS.exe"))
            {
                Print("RSA public and private keys successfully created and saved in app folder! ");
                Process.Start(_folderPath + "QRMYKEYS.exe");
                Print("QR Code of your assymetric keys will be generated... ");
                // Print("Please (4 security) use QRMYKEYS, print output and delete key files ");
            }
        }
Пример #27
0
 public override void ImportFromBytes(IKeyStore keyStore, byte[] bytes, int keySize = 1024)
 {
     using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize))
     {
         rsa.PersistKeyInCsp = false;
         rsa.ImportCspBlob(bytes);
         keyStore.PublicKey.Key = rsa.ExportCspBlob(false);
         if (!rsa.PublicOnly)
         {
             keyStore.PrivateKey.Key = bytes;
         }
     }
 }
Пример #28
0
        /// <summary>
        /// RSA加密(自动生成公钥私钥)
        /// </summary>
        /// <param name="text">文本</param>
        /// <param name="strPublicKey">公钥</param>
        /// <param name="strPrivateKey">私钥</param>
        /// <returns></returns>
        public static string RSA_Encrypt(string text, out string strPublicKey, out string strPrivateKey)
        {
            strPrivateKey = strPublicKey = String.Empty;
            try
            {
                byte[] dataToEncrypt = Encoding.UTF8.GetBytes(text);
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                strPublicKey  = Convert.ToBase64String(provider.ExportCspBlob(false));
                strPrivateKey = Convert.ToBase64String(provider.ExportCspBlob(true));

                //OAEP padding is only available on Microsoft Windows XP or later.
                byte[] bytesCypherText = provider.Encrypt(dataToEncrypt, false);
                provider.Dispose();
                string strCypherText = Convert.ToBase64String(bytesCypherText);
                return(strCypherText);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
Пример #29
0
        public SignatureSet GetSignature(byte[] data)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                var sigSet = new SignatureSet
                {
                    signature = rsa.SignData(data, hasher),
                    publicKey = rsa.ExportCspBlob(false)
                };

                return(sigSet);
            }
        }
Пример #30
0
        private byte[] ReceiveData(Socket handler)
        {
            RSACryptoServiceProvider cryptoProvider = InitializeAsymmetricCyphering();

            byte[] publicKey = cryptoProvider.ExportCspBlob(false);
            handler.Send(publicKey);
            byte[] encryptedSymmetricKey = new byte[512];
            handler.Receive(encryptedSymmetricKey);
            byte[] encryptedData = DataExtensions.ReceiveMessageBySocket(handler);
            byte[] symmetricKey  = cryptoProvider.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.Pkcs1);
            cryptoProvider.Dispose();
            return(encryptedData.Decrypt(symmetricKey).Decompress());
        }
Пример #31
0
        private RSACryptoServiceProvider getSignKey()
        {
            X509Certificate2         certificate = new X509Certificate2("server.pfx", "", X509KeyStorageFlags.Exportable);
            RSACryptoServiceProvider signKey     = certificate.PrivateKey as RSACryptoServiceProvider;

            byte[]        privateKeyBlob = signKey.ExportCspBlob(true);
            CspParameters cp             = new CspParameters(24);

            signKey = new RSACryptoServiceProvider(cp);
            signKey.ImportCspBlob(privateKeyBlob);

            return(signKey);
        }
Пример #32
0
 public static void Main(String []args) {
   int keysize = 1024;
   if(args.Length == 1) {
     try {
       keysize = Int32.Parse(args[0]);
     }
     catch { 
       Console.WriteLine("Default key size is 1024, specify 512 or 2048 as an input parameter.");
       return;
     }
   } 
   RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keysize);
   // Create public key file
   byte[] rsa_public = rsa.ExportCspBlob(false);
   FileStream public_file = File.Open("rsa_public", FileMode.Create);
   public_file.Write(rsa_public, 0, rsa_public.Length);
   public_file.Close();
   // Create private key file
   byte[] rsa_private = rsa.ExportCspBlob(true);
   FileStream private_file = File.Open("rsa_private", FileMode.Create);
   private_file.Write(rsa_private, 0, rsa_private.Length);
   private_file.Close();
 }
Пример #33
0
        public static void ExportImportPublicPrivate()
        {
            // This blob contains the private key of TestData.CspTestKey. The guidelines for the TestData class
            // as to key security/sanity apply to this blob as well.
            byte[] expectedExport = ByteUtils.HexToByteArray(
                "0702000000a40000525341320004000001000100e19a01644b82962a224781d1f60c2cc373b"
                + "798df541343f63c638f45fa96e11049c8d9e88bd56483ec3c2d56e9460d2b1140191841761c1523840221b0e"
                + "b6401dc4d09c54bf75cea25d9e191572fb2ec92c3559b35b3ef3fa695171bb1fddeb469792e49f0d17c769d0"
                + "a37f6a4a6584af39878eb21f9ba9eae8be9c39eac6ae07bb43a9f6e29e584b47303f8ac70384ba4f1a4b7d77"
                + "fb4c931c2a194584b9d6060d39ba798e20698221ac615b083bbdaf2b6f39c05c570276945728800b1aae1531"
                + "511b5878dae8820a178f8cc3cca5426ce761ef3247bce9375318a03c3d5779ed339d2f9d04d6265d0a99057c"
                + "c1af86b656541f4f6b062d8407968aaf794fee33273c0fd4735d688e0e8161f5c9f360c2fc1caed9a2b48a53"
                + "3ea4d26b9ac50a0e7e7ca94c6bd6edfd3fe448650b66fa99c57b50e3737fae9d26300fee06649472a664190e"
                + "a603126718f896bbfe0671401f31414678d173d32c486c8fbb6334fe90c77f7c2a04ee9c3e3ab85d948357f7"
                + "15e5d706031e013f0951eeb1e506c5af71cfec07bbc637d5b7c788fdad21ec5f250ef069d00a5c9bb6e2fe06"
                + "01b91f36121885011cd7186093ee25c2a5dd6b3cfea3d8b1627148ab0a47610b8d99743ac008b62f8a054c18"
                + "4b8b9f862beebc70af40408999bead5a09baec588375be03cfa636b018d7d9948f1abae4d5463c5c5d210a0b"
                + "42589a90a2bc01b1bb027f6c859de82ace0c60237d96574a1752e38b56326c7eae33cf7590da6728ff1de184"
                + "c654fccba0866732e576747107cef935d43aa5f477178aafee834a53a3d14");

            byte[] exported;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.CspTestKey);

                exported = rsa.ExportCspBlob(includePrivateParameters: true);
            }

            Assert.Equal(expectedExport, exported);

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(exported);
                byte[] exported2 = rsa.ExportCspBlob(includePrivateParameters: true);
                Assert.Equal<byte>(exported, exported2);
            }
        }
Пример #34
0
    static int GenerateKeyFile(string fileName)
    {
        // do not overwrite if the file already exists
        var keyFile = GetFileName(fileName);
        if (File.Exists(keyFile))
        {
            return 0;
        }

        // generate key pair and export it as a blob
        var parms = new CspParameters();
        parms.KeyNumber = 2;
        var provider = new RSACryptoServiceProvider(KeySize, parms);
        var array = provider.ExportCspBlob(!provider.PublicOnly);

        File.WriteAllBytes(keyFile, array);
        return 0;
    }
Пример #35
0
    public bool GenerateCACert(string group)
    {
        if(!Context.Request.IsLocal) {
          throw new Exception("Call must be made locally!");
        }

        string private_path = GetGroupPrivatePath(group);
        Directory.CreateDirectory(private_path);

        private_path += "private_key";
        RSACryptoServiceProvider private_key = new RSACryptoServiceProvider(2048);
        byte[] private_blob = private_key.ExportCspBlob(true);
        using(FileStream fs = File.Open(private_path, FileMode.Create)) {
          fs.Write(private_blob, 0, private_blob.Length);
        }

        string data_path = GetGroupDataPath(group);
        Directory.CreateDirectory(data_path);

        RSACryptoServiceProvider public_key = new RSACryptoServiceProvider();
        public_key.ImportCspBlob(private_key.ExportCspBlob(false));

        CertificateMaker cm = new CertificateMaker(string.Empty, group,
        string.Empty, "admin", string.Empty, public_key, string.Empty);
        Certificate cert = cm.Sign(cm, private_key);

        string cacert_path = GetGroupDataPath(group) + "cacert";
        byte[] cert_data = cert.X509.RawData;
        using(FileStream fs = File.Open(cacert_path, FileMode.Create)) {
          fs.Write(cert_data, 0, cert_data.Length);
        }

        return true;
    }
        public static void NamedKey_DefaultProvider()
        {
            const int KeySize = 2048;

            CspParameters cspParameters = new CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
            };

            using (new RsaKeyLifetime(cspParameters))
            {
                byte[] privateBlob;
                string uniqueKeyContainerName;

                using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters))
                {
                    Assert.True(rsa.PersistKeyInCsp, "rsa.PersistKeyInCsp");
                    Assert.Equal(cspParameters.KeyContainerName, rsa.CspKeyContainerInfo.KeyContainerName);

                    uniqueKeyContainerName = rsa.CspKeyContainerInfo.UniqueKeyContainerName;
                    Assert.NotNull(uniqueKeyContainerName);
                    Assert.NotEqual(string.Empty, uniqueKeyContainerName);

                    privateBlob = rsa.ExportCspBlob(true);
                    Assert.True(rsa.CspKeyContainerInfo.Exportable, "rsa.CspKeyContainerInfo.Exportable");
                }

                // Fail if the key didn't persist
                cspParameters.Flags |= CspProviderFlags.UseExistingKey;

                using (var rsa = new RSACryptoServiceProvider(cspParameters))
                {
                    Assert.True(rsa.PersistKeyInCsp);
                    Assert.Equal(KeySize, rsa.KeySize);

                    Assert.Equal(uniqueKeyContainerName, rsa.CspKeyContainerInfo.UniqueKeyContainerName);

                    byte[] blob2 = rsa.ExportCspBlob(true);
                    Assert.Equal(privateBlob, blob2);
                }
            }
        }
Пример #37
0
        public static void RSAParametersToBlob_PublicOnly()
        {
            byte[] blob;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                blob = rsa.ExportCspBlob(false);
            }

            RSAParameters exported;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(blob);

                Assert.True(rsa.PublicOnly);

                exported = rsa.ExportParameters(false);
            }

            RSAParameters expected = new RSAParameters
            {
                Modulus = TestData.RSA1024Params.Modulus,
                Exponent = TestData.RSA1024Params.Exponent,
            };

            ImportExport.AssertKeyEquals(ref expected, ref exported);
        }
        public static void NamedKey_AlternateProvider()
        {
            const int KeySize = 512;

            CspParameters cspParameters = new CspParameters(PROV_RSA_FULL)
            {
                KeyContainerName = Guid.NewGuid().ToString(),
            };

            using (new RsaKeyLifetime(cspParameters))
            {
                byte[] privateBlob;
                string uniqueKeyContainerName;

                using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters))
                {
                    Assert.True(rsa.PersistKeyInCsp);
                    Assert.Equal(PROV_RSA_FULL, rsa.CspKeyContainerInfo.ProviderType);

                    privateBlob = rsa.ExportCspBlob(true);

                    Assert.Equal(cspParameters.KeyContainerName, rsa.CspKeyContainerInfo.KeyContainerName);

                    uniqueKeyContainerName = rsa.CspKeyContainerInfo.UniqueKeyContainerName;
                    Assert.NotNull(uniqueKeyContainerName);
                    Assert.NotEqual(string.Empty, uniqueKeyContainerName);
                }

                // Fail if the key didn't persist
                cspParameters.Flags |= CspProviderFlags.UseExistingKey;

                using (var rsa = new RSACryptoServiceProvider(cspParameters))
                {
                    Assert.True(rsa.PersistKeyInCsp);
                    Assert.Equal(KeySize, rsa.KeySize);

                    // Since we're specifying the provider explicitly it should still match.
                    Assert.Equal(PROV_RSA_FULL, rsa.CspKeyContainerInfo.ProviderType);

                    Assert.Equal(uniqueKeyContainerName, rsa.CspKeyContainerInfo.UniqueKeyContainerName);

                    byte[] blob2 = rsa.ExportCspBlob(true);
                    Assert.Equal(privateBlob, blob2);
                }
            }
        }
Пример #39
0
        public static void RSAParametersToBlob_PublicPrivate()
        {
            byte[] blob;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                blob = rsa.ExportCspBlob(true);
            }

            RSAParameters exported;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(blob);

                Assert.False(rsa.PublicOnly);

                exported = rsa.ExportParameters(true);
            }

            RSAParameters expected = TestData.RSA1024Params;

            ImportExport.AssertKeyEquals(ref expected, ref exported);
        }
        public static void NonExportable_Ephemeral()
        {
            CspParameters cspParameters = new CspParameters
            {
                Flags = CspProviderFlags.UseNonExportableKey,
            };

            using (var rsa = new RSACryptoServiceProvider(cspParameters))
            {
                // Ephemeral keys don't successfully request the exportable bit.
                Assert.ThrowsAny<CryptographicException>(() => rsa.CspKeyContainerInfo.Exportable);

                Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true));
                Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true));
            }
        }
        public static void NonExportable_Persisted()
        {
            CspParameters cspParameters = new CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
                Flags = CspProviderFlags.UseNonExportableKey,
            };

            using (new RsaKeyLifetime(cspParameters))
            {
                using (var rsa = new RSACryptoServiceProvider(cspParameters))
                {
                    Assert.False(rsa.CspKeyContainerInfo.Exportable, "rsa.CspKeyContainerInfo.Exportable");

                    Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true));
                    Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true));
                }
            }
        }
        public static void CreateKey_LegacyProvider_RoundtripBlob()
        {
            const int KeySize = 512;

            CspParameters cspParameters = new CspParameters(PROV_RSA_FULL);
            byte[] blob;

            using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters))
            {
                CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo;
                Assert.Equal(PROV_RSA_FULL, containerInfo.ProviderType);
                Assert.Equal(KeySize, rsa.KeySize);

                blob = rsa.ExportCspBlob(true);
            }

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(blob);

                CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo;

                // The provider information is not persisted in the blob
                Assert.Equal(PROV_RSA_AES, containerInfo.ProviderType);
                Assert.Equal(KeySize, rsa.KeySize);
            }
        }