示例#1
0
        public static EncryptorRSAKeys GenerateKeys(int keySize)
        {
            if (keySize % 2 != 0 || keySize < 512)
            {
                throw new Exception("Key should be multiple of two and greater than 512.");
            }

            var response = new EncryptorRSAKeys();

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

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

                response.PublicKey  = publicKeyWithSize;
                response.PrivateKey = privateKeyWithSize;

                provider.PersistKeyInCsp = false;
                provider.Clear();
            }

            return(response);
        }
示例#2
0
        private static byte[] Encrypt(byte[] data, int keySize, string publicKeyXml)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("Data are empty", "data");
            }
            int maxLength = GetMaxDataLength(keySize);

            if (data.Length > maxLength)
            {
                throw new ArgumentException(String.Format("Maximum data length is {0}", maxLength), "data");
            }
            if (!IsKeySizeValid(keySize))
            {
                throw new ArgumentException("Key size is not valid", "keySize");
            }
            if (String.IsNullOrEmpty(publicKeyXml))
            {
                throw new ArgumentException("Key is null or empty", "publicKeyXml");
            }

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                RSAKeyExtensions.FromXmlString(provider, publicKeyXml);
                return(provider.Encrypt(data, _optimalAsymmetricEncryptionPadding));
            }
        }
示例#3
0
        private static byte[] Decrypt(byte[] data, int keySize, string publicAndPrivateKeyXml)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("Data are empty", "data");
            }
            if (!IsKeySizeValid(keySize))
            {
                throw new ArgumentException("Key size is not valid", "keySize");
            }
            if (String.IsNullOrEmpty(publicAndPrivateKeyXml))
            {
                throw new ArgumentException("Key is null or empty", "publicAndPrivateKeyXml");
            }

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                RSAKeyExtensions.FromXmlString(provider, publicAndPrivateKeyXml);
                return(provider.Decrypt(data, _optimalAsymmetricEncryptionPadding));
            }
        }