Ejemplo n.º 1
0
            public RSAKeysTypes GenerateKeys(RSAKeySize rsaKeySize)
            {
                int keySize = (int)rsaKeySize;

                if (keySize % 2 != 0 || keySize < 512)
                {
                    throw new Exception("Key should be multiple of two and greater than 512.");
                }

                var rsaKeysTypes = new RSAKeysTypes();

                using (var provider = new RSACryptoServiceProvider(keySize))
                {
                    var publicKey  = provider.ToXmlString(false);
                    var privateKey = provider.ToXmlString(true);

                    var publicKeyWithSize  = IncludeKeyInEncryptionString(publicKey, keySize);
                    var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey, keySize);

                    rsaKeysTypes.PublicKey  = publicKeyWithSize;
                    rsaKeysTypes.PrivateKey = privateKeyWithSize;
                }

                return(rsaKeysTypes);
            }
        /// <summary>Makes a new set of keys and returns them as BASE64 encoded</summary>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public static (RSAKeyValues pk, RSAKeyValues sk) MakeKeys(RSAKeySize keySize)
        {
            int ks = (int)keySize;

            if (ks % 2 != 0 || ks < 512)
            {
                throw new System.Exception("Key should be multiple of two and greater than 512.");
            }

            using var provider = new RSACryptoServiceProvider(ks);

            // secret key
            RSAParameters sk = provider.ExportParameters(true);

            // public key
            RSAParameters pk = provider.ExportParameters(false);

            return(new RSAKeyValues(pk)
            {
                KeySize = keySize
            }, new RSAKeyValues(sk)
            {
                KeySize = keySize
            });
        }
Ejemplo n.º 3
0
        public RSAKeySetIdentity GenerateRSAKeyPair(RSAKeySize keySize)
        {
            RSAKeySetIdentity keySet;

            using (var rsa = new RSACryptoServiceProvider((int)keySize))
            {
                byte[] rsaPrivateKeyData = rsa.ExportCspBlob(true);
                byte[] rsaPublicKeyData  = rsa.ExportCspBlob(false);


                StringBuilder tmp = new StringBuilder(Convert.ToBase64String(rsaPrivateKeyData));
                for (int i = 64; i < tmp.Length; i += 66)
                {
                    tmp.Insert(i, "\r\n");
                }

                string privKey = BEGIN_RSA_PRIVATE_KEY + "\r\n" + tmp + "\r\n" + END_RSA_PRIVATE_KEY;

                tmp = new StringBuilder(Convert.ToBase64String(rsaPublicKeyData));
                for (int i = 64; i < tmp.Length; i += 66)
                {
                    tmp.Insert(i, "\r\n");
                }

                string pubKey = BEGIN_RSA_PUBLIC_KEY + "\r\n" + tmp + "\r\n" + END_RSA_PUBLIC_KEY;

                keySet = new RSAKeySetIdentity(privKey, pubKey);
            }

            return(keySet);
        }
        public RSACryptography(RSAKeySize RsaKeySize)
        {            
            KeySize = (int)RsaKeySize;

            if (KeySize % 2 != 0 || KeySize < 1024)
                throw new Exception("Key Size should Be Multiple Of two And Greater Than 1024");            
        }
Ejemplo n.º 5
0
 public void GenerateKeys(RSAKeySize rsaKeySize)
 {
     using (var provider = new RSACryptoServiceProvider((int)rsaKeySize))
     {
         PublicKey  = provider.ToXmlString(false);
         PrivateKey = provider.ToXmlString(true);
     }
 }
Ejemplo n.º 6
0
        public static PgpKeyRingGenerator GenerateKeyRing(String id, byte[] pass, RSAKeySize keysize)
        {
            RsaKeyPairGenerator kpg = new RsaKeyPairGenerator();

            kpg.Init(new KeyGenerationParameters(new SecureRandom(), 4096));

            AsymmetricCipherKeyPair rsakeys = kpg.GenerateKeyPair();

            PgpKeyPair rsakp_sign = new PgpKeyPair(PublicKeyAlgorithmTag.RsaSign, rsakeys, DateTime.UtcNow);
            PgpKeyPair rsakp_enc  = new PgpKeyPair(PublicKeyAlgorithmTag.RsaEncrypt, rsakeys, DateTime.UtcNow);

            PgpSignatureSubpacketGenerator signhashgen = new PgpSignatureSubpacketGenerator();

            signhashgen.SetKeyFlags(false, KeyFlags.SignData | KeyFlags.CertifyOther);
            signhashgen.SetPreferredSymmetricAlgorithms
                (false, new int[] {
                (int)SymmetricKeyAlgorithmTag.Aes256,
                (int)SymmetricKeyAlgorithmTag.Camellia256
            });

            signhashgen.SetPreferredHashAlgorithms
                (false, new int[] {
                (int)HashAlgorithmTag.Sha256,
                (int)HashAlgorithmTag.Sha384,
                (int)HashAlgorithmTag.Sha512
            });

            signhashgen.SetFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

            // Create a signature on the encryption subkey.
            PgpSignatureSubpacketGenerator enchashgen = new PgpSignatureSubpacketGenerator();

            enchashgen.SetKeyFlags(false, KeyFlags.EncryptComms | KeyFlags.EncryptStorage | KeyFlags.Authentication);

            PgpKeyRingGenerator pgpKeyRing = new PgpKeyRingGenerator(
                PgpSignature.DefaultCertification,
                rsakp_sign,
                id,
                SymmetricKeyAlgorithmTag.Aes256,
                pass,
                false,
                signhashgen.Generate(),
                null,
                new SecureRandom()
                );

            pgpKeyRing.AddSubKey(rsakp_enc, enchashgen.Generate(), null, HashAlgorithmTag.Sha512);

            return(pgpKeyRing);
        }
        public void GenerateKeys(RSAKeySize rsaKeySize)
        {
            using (var provider = new RSACryptoServiceProvider((int)rsaKeySize))
            {
                var publicKey  = provider.ToXmlString(false);
                var privateKey = provider.ToXmlString(true);

                var publicKeyWithSize  = IncludeKeyInEncryptionString(publicKey, (int)rsaKeySize);
                var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey, (int)rsaKeySize);

                PublicKey  = publicKeyWithSize;
                PrivateKey = privateKeyWithSize;
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Generates a new RSA key pair <see cref="Tuple"/> using the provided RSA key size parameter <paramref name="keySize"/>.<para> </para>
 /// Returns the RSA key pair <see cref="Tuple"/>, where the first item is the public key and the second is the private key.<para> </para>
 /// If generation failed for some reason, <c>null</c> is returned.
 /// </summary>
 /// <param name="keySize">The desired RSA key size. Can be 512-bit, 1024-bit, 2048-bit or 4096-bit.</param>
 /// <returns>The key pair <see cref="Tuple"/>, where the first item is the public RSA key and the second one is the private key (both PEM-formatted). If key generation failed, both tuple items are <c>null</c>.</returns>
 public ValueTuple <string, string> GenerateKeyPair(RSAKeySize keySize)
 {
     try
     {
         var keygen = new RsaKeyPairGenerator();
         keygen.Init(new KeyGenerationParameters(new SecureRandom(), (int)keySize));
         AsymmetricCipherKeyPair keyPair = keygen.GenerateKeyPair();
         return(keyPair.Public.ToPemString(), keyPair.Private.ToPemString());
     }
     catch (Exception e)
     {
         errorCallback?.Invoke($"{nameof(RSAKeygen)}::{nameof(GenerateKeyPair)}: RSA key pair generation failed. Thrown exception: {e.ToString()}");
         return(null, null);
     }
 }
Ejemplo n.º 9
0
        public RSAKeysTypes GenerateKeys(RSAKeySize rsaKeySize)
        {
            int keySize = (int)rsaKeySize;

            if (keySize % 2 != 0 || keySize < 512)
            {
                throw new Exception("Ключ должен быть кратен 2!");
            }
            var rsaKeysTypes = new RSAKeysTypes();

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                var publicKey          = provider.ToXmlString(false);
                var privateKey         = provider.ToXmlString(true);
                var publicKeyWithSize  = IncludeKeyInEncryptionString(publicKey);
                var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey);
                rsaKeysTypes.PublicKey  = publicKeyWithSize;
                rsaKeysTypes.PrivateKey = privateKeyWithSize;
            }
            return(rsaKeysTypes);
        }
Ejemplo n.º 10
0
        public static RSAKeyPair GenKeys(RSAKeySize keySize)
        {
            try
            {
                using (var provider = new RSACryptoServiceProvider((int)keySize))
                {
                    RSAKeyPair keys               = new RSAKeyPair();
                    var        publicKey          = provider.ToXmlString(false);
                    var        privateKey         = provider.ToXmlString(true);
                    var        publicKeyWithSize  = IncludeKeyInEncryptionString(publicKey);
                    var        privateKeyWithSize = IncludeKeyInEncryptionString(privateKey);
                    keys.PublicKey  = publicKeyWithSize;
                    keys.PrivateKey = privateKeyWithSize;

                    return(keys);
                }
            }
            catch (CryptographicException)
            {
                return(null);
            }
        }
Ejemplo n.º 11
0
        static public AppData GenerateRSAPrivateKey(RSAKeySize strength, string password, int iteration, Label label, IDispatcher dispatcher)
        {
            try
            {
                IDictionary attrs = new Hashtable
                {
                    { X509Name.CN, "commonname" },
                    { X509Name.O, "organization" },
                    { X509Name.OU, "organizationalUnit" },
                    { X509Name.L, "locality" },
                    { X509Name.ST, "state" },
                    { X509Name.C, "countryIso2Characters" },
                    { X509Name.EmailAddress, "emailAddress" }
                };

                UpdateStatus("1 of 16 Completed!\nCreating X509", "", label, dispatcher);
                X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

                UpdateStatus("2 of 16 Completed!\n1 of 3 RSA Key Pair\nInitializing", "X509 Generated", label, dispatcher);
                RsaKeyPairGenerator rsa = new RsaKeyPairGenerator();

                UpdateStatus("3 of 16 Completed!\n2 of 3 RSA Key Pair\nRandomizing", "", label, dispatcher);
                rsa.Init(new KeyGenerationParameters(GetSecureRandom(), (int)strength));

                UpdateStatus("4 of 16 Completed!\n3 of 3 RSA Key Pair\nGenerating", "Randomizing Done", label, dispatcher);
                AsymmetricCipherKeyPair asym = rsa.GenerateKeyPair();

                UpdateStatus("5 of 16 Completed!\n1 of 4 Encrypting RSA Key Pair: Initalizing", "RSA Keys Created", label, dispatcher);
                var generator = new Pkcs8Generator(asym.Private, Pkcs8Generator.PbeSha1_RC4_128);
                generator.IterationCount = iteration;

                UpdateStatus("6 of 16 Completed!\n2 of 4 Encrypting RSA Key Pair: Randomize", "", label, dispatcher);
                generator.SecureRandom = GetSecureRandom();

                UpdateStatus("7 of 16 Completed!\n3 of 4 Encrypting RSA Key Pair: Hashing", "Randomize Done", label, dispatcher);
                generator.Password = Hash512Iterate(password.ToByteArray(), iteration).ToBase64().ToCharArray();

                UpdateStatus("8 of 16 Completed!\n4 of 4 Encrypting RSA Key Pair: Finalizing", "Hashing Done", label, dispatcher);
                var pem = generator.Generate();

                string SecurePrivateKey = ConvertRSAPemToString(pem);

                UpdateStatus("9 of 16 Completed!\nStoring Encrypted RSA Key Pair", "RSA Key Pair Encrypted", label, dispatcher);
                AppData appData = new AppData
                {
                    RSAPrivateKey = SecurePrivateKey,
                    RSAPublicKey  = StringBuilder(asym, KeyType.PublicKey),
                };

                int id = App.AppDatabase.SaveDataAsync(appData).Result;
                if (id != 1)
                {
                    throw new Exception("GenerateRSAKey: RSA Save Key filed. id != 1");
                }

                appData.ID = 1;

                UpdateStatus("10 of 16 Completed!\nLoading RSA Key Pair", "RSA Key Pair Stored", label, dispatcher);

                if (!LoadRSAKey(password, iteration))
                {
                    throw new Exception("Generate KeyPair: Could not load RSA Keys");
                }

                UpdateStatus("11 of 16 Completed!\nCreating PKCS#10 CSR", "RSA Keys Loaded", label, dispatcher);

                Asn1SignatureFactory       signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id, asym.Private);
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(signatureFactory, subject, asym.Public, null);
                appData.CSR = StringBuilder(csr);

                UpdateStatus("12 of 16 Completed!\n1 of 4 AES Tasks: Creating Seed", "PKCS#10 CSR Created", label, dispatcher);
                appData.Seed = GenerateSeed(false).seed;

                UpdateStatus("13 of 16 Completed!\n2 of 4 AES Tasks: Creating Salt", "AES Seed Created", label, dispatcher);
                appData.Salt = GenerateSalt(false).salt;

                UpdateStatus("14 of 16 Completed!\n3 of 4 AES Tasks: Encrypting Iterations", "AES Salt Created", label, dispatcher);
                appData.Iterations = RSAEncrypt(iteration.ToString());

                UpdateStatus("15 of 16 Completed!\n4 of 4 AES Tasks: Encrypting Certs", "Iterations Encrypted", label, dispatcher);
                appData = AESEncrypt(appData) as AppData;
                if (appData == null)
                {
                    throw new Exception("AES Encryption Failed during Key Generation");
                }

                UpdateStatus("16 of 16 Completed!\nFinishing up", "", label, dispatcher);
                App.AppDatabase.SaveDataAsync(appData).Wait();

                return(appData);
            }
            catch (Exception e)
            {
                FileHelper.WriteFile(ErrorHelper.FormatError(e), FileHelper.ErrorPath, true);
                return(null);
            }
        }
Ejemplo n.º 12
0
 public RSA(RSAKeySize keySize)
 {
     this.rsa = new RSACryptoServiceProvider((int)keySize);
     this.rsa.PersistKeyInCsp = false;
 }