Esempio n. 1
0
        public static string RsaEncryptWithPrivate(string clearText)
        {
            var mod    = new BigInteger(Mod, 16);
            var pubExp = new BigInteger(PubExponent, 16);

            var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
            var pubParameters  = new RsaKeyParameters(false, mod, pubExp);
            var encryptEngine  = new Pkcs1Encoding(new RsaEngine());

            encryptEngine.Init(true, pubParameters);
            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encrypted);
        }
    public string RsaDecryptWithPublic(string base64Input, string publicKey)
    {
        var bytesToDecrypt = Convert.FromBase64String(base64Input);
        var decryptEngine  = new Pkcs1Encoding(new RsaEngine());

        using (var txtreader = new StringReader(publicKey))
        {
            var keyParameter = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();
            decryptEngine.Init(false, keyParameter);
        }
        var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

        return(decrypted);
    }
        public static bool EncryptBuffer(this AsymmetricKeyParameter PublicKey, byte[] aClearData, out string strHexedEncrypted)
        {
            strHexedEncrypted = null;
            try
            {
                var encryptEngine = new Pkcs1Encoding(new RsaEngine());
                encryptEngine.Init(true, PublicKey);
                strHexedEncrypted = encryptEngine.ProcessBlock(aClearData, 0, aClearData.Length).ToHexString();

                return(strHexedEncrypted.Length > 0);
            }
            catch (Exception e) { e.CatchMessage().TraceError("EncryptBuffer(): "); }
            return(false);
        }
    public string RsaEncryptWithPublic(string clearText, string publicKey)
    {
        var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
        var encryptEngine  = new Pkcs1Encoding(new RsaEngine());

        using (var txtreader = new StringReader(publicKey))
        {
            var keyParameter = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();
            encryptEngine.Init(true, keyParameter);
        }
        var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

        return(encrypted);
    }
Esempio n. 5
0
        public DecryptMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            this.next = next;
            using TextReader reader = new StringReader(configuration.GetPivateKey());
            PemObject pemObject         = new PemReader(reader).ReadPemObject();
            AsymmetricKeyParameter pkey = PrivateKeyFactory.CreateKey(pemObject.Content);

            this.pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());
            pkcs1Encoding.Init(false, pkey);
            var assembly = Assembly.GetExecutingAssembly();

            Type[] types          = assembly.GetTypes();
            Type[] apicontrollers = types.Where(type => type.GetCustomAttribute <ApiControllerAttribute>() != null).ToArray();
            foreach (Type ctrl in apicontrollers)
            {
                MethodInfo[]   controllerMethods = ctrl.GetMethods();
                RouteAttribute apiRoute          = ctrl.GetCustomAttribute <RouteAttribute>();
                if (apiRoute == null)
                {
                    throw new Exception($"{ctrl.Name} doesn't have a \"Route\" Attribute");
                }
                string ctrRoute = apiRoute.Template;
                foreach (MethodInfo meth in controllerMethods)
                {
                    EncryptAttribute encryptAttribute = meth.GetCustomAttribute <EncryptAttribute>();
                    if (encryptAttribute != null)
                    {
                        string            route;
                        HttpPostAttribute post = meth.GetCustomAttribute <HttpPostAttribute>();

                        if (post != null)
                        {
                            route = post.Template;
                        }
                        else
                        {
                            throw new Exception("Api Mehtod Be Encrypted Http Method Must Be POST ");
                        }
                        string key = "/" + ctrRoute + "/" + route;
                        if (this.ApiMap.ContainsKey(key))
                        {
                            throw new Exception("Api Method Route Repeat Exception!");
                        }

                        this.ApiMap.Add(key, encryptAttribute);
                    }
                }
            }
        }
Esempio n. 6
0
        private static string RsaEncrypt(string plainText, string key)
        {
            var bytesToEncrypt = Encoding.Unicode.GetBytes(plainText);
            var encryptEngine  = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(key))
            {
                var keyParameter = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();
                encryptEngine.Init(true, keyParameter);
            }

            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encrypted);
        }
Esempio n. 7
0
        public static string DekriptirajTekst(string kriptiraniTekst, string privatniKljuc)
        {
            var bytesToDecrypt = Convert.FromBase64String(kriptiraniTekst);
            var decryptEngine  = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(privatniKljuc))
            {
                var keyPair = (AsymmetricCipherKeyPair) new PemReader(txtreader).ReadObject();
                decryptEngine.Init(false, keyPair.Private);
            }

            var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

            return(decrypted);
        }
Esempio n. 8
0
        public byte[] RsaDecryptWithPrivate(byte[] bytesToDecrypt, string privateKey)
        {
            AsymmetricCipherKeyPair keyPair;

            var decryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(privateKey))
            {
                keyPair = (AsymmetricCipherKeyPair) new PemReader(txtreader).ReadObject();

                decryptEngine.Init(false, keyPair.Private);
            }

            return(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
        }
Esempio n. 9
0
        public static byte[] DecryptPKCS1ByRSASk(byte[] data, AsymmetricKeyParameter sk)
        {
            byte[] result = null;
            IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());

            cipher.Init(false, sk);
            try{
                result = cipher.ProcessBlock(data, 0, data.Length);
            }
            catch (InvalidCipherTextException e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
                result = null;
            }
            return(result);
        }
Esempio n. 10
0
        /// <summary>
        /// 私钥加密
        /// </summary>
        /// <param name="pContent">要加密的内容</param>
        /// <param name="pPrivateKey">私钥</param>
        /// <returns></returns>
        public static string PrivateKeyEncrypt(byte[] encryptedData, string pPrivateKey)
        {
            byte[]                 btPem     = Convert.FromBase64String(pPrivateKey);
            Asn1Object             pubKeyObj = Asn1Object.FromByteArray(btPem);//这里也可以从流中读取,从本地导入
            AsymmetricKeyParameter pubKey    = PrivateKeyFactory.CreateKey(btPem);
            IAsymmetricBlockCipher eng       = new Pkcs1Encoding(new RsaEngine());

            eng.Init(true, pubKey);//true表示加密


            encryptedData = eng.ProcessBlock(encryptedData, 0, encryptedData.Length);
            string result = Convert.ToBase64String(encryptedData);

            return(result);
        }
Esempio n. 11
0
 /// <summary>
 /// RSA解密
 /// </summary>
 /// <param name="pCerFilePath">cer证书文件路径</param>
 /// <param name="pDecryptContent">需要解密的内容</param>
 /// <returns></returns>
 public static byte[] RSADecrypt(string pCerFilePath, byte[] pDecryptContent)
 {
     using (FileStream fs = new FileStream(pCerFilePath, FileMode.Open))
     {
         Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
         Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] {
             cp.ReadCertificate(fs)
         };
         IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
         eng.Init(false, chain[0].GetPublicKey());
         var result = eng.ProcessBlock(pDecryptContent, 0, pDecryptContent.Length);
         //
         return(result);
     }
 }
Esempio n. 12
0
        public string DecryptByPublicKeyOnly(string source, string publicKey)
        {
            var                    publicKeyParams  = this.GetPublicKeyParameters(publicKey);
            BigInteger             biModulus        = new BigInteger(1, publicKeyParams.Item1);
            BigInteger             biExponent       = new BigInteger(1, publicKeyParams.Item2);
            RsaKeyParameters       publicParameters = new RsaKeyParameters(false, biModulus, biExponent);
            IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());

            eng.Init(false, publicParameters);
            //解密已加密的数据
            var encryptedData = Convert.FromBase64String(source);

            encryptedData = eng.ProcessBlock(encryptedData, 0, encryptedData.Length);
            return(Encoding.UTF8.GetString(encryptedData, 0, encryptedData.Length));
        }
Esempio n. 13
0
        /// <summary>
        /// 公钥加密
        /// </summary>
        /// <param name="data">待加密数据</param>
        /// <param name="publicKey">公钥</param>
        /// <returns></returns>
        public static string EncryptWithPublicKey(object data, string publicKey)
        {
            byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));

            Pkcs1Encoding encryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (StringReader txtReader = new StringReader(publicKey))
            {
                AsymmetricKeyParameter keyParameter = (AsymmetricKeyParameter) new PemReader(txtReader).ReadObject();
                encryptEngine.Init(true, keyParameter);
            }
            string encryptedText = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encryptedText);
        }
Esempio n. 14
0
        public static string KriptirajTekst(string razumljivTekst, string javniKljuc)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(razumljivTekst);
            var encryptEngine  = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(javniKljuc))
            {
                var keyParameter = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();
                encryptEngine.Init(true, keyParameter);
            }

            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encrypted);
        }
Esempio n. 15
0
        /// <summary>
        /// Encrypt data by public key
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string PublicEncrypt(string rawData)
        {
            BigInteger             biModulus        = new BigInteger(1, _btPemModulus);
            BigInteger             biExponent       = new BigInteger(1, _btPemPublicExponent);
            RsaKeyParameters       publicParameters = new RsaKeyParameters(false, biModulus, biExponent);
            IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());

            eng.Init(true, publicParameters);

            byte[] tmp = Encoding.UTF8.GetBytes(rawData);
            tmp = eng.ProcessBlock(tmp, 0, tmp.Length);
            string result = Convert.ToBase64String(tmp);

            return(result);
        }
Esempio n. 16
0
        public static String SignData(RsaPrivateCrtKeyParameters PrivateKey, String ToBeSigned)
        {
            byte[] Data     = Encoding.UTF8.GetBytes(ToBeSigned);
            byte[] sha1Hash = SHA1.Create().ComputeHash(Data);

            Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());

            pkcs1Encoding.Init(true, PrivateKey);
            int inputBlockSize = pkcs1Encoding.GetInputBlockSize();

            byte[] EncryptedData = pkcs1Encoding.ProcessBlock(sha1Hash, 0, sha1Hash.Length);

            var signedString = Convert.ToBase64String(EncryptedData);

            return(signedString);
        }
Esempio n. 17
0
        /// <summary>
        /// Encrypts data with the given public part of the asymmetric keypair using the RSA algorithm
        /// </summary>
        /// <param name="publicKey">the public part of the asymetric keypair</param>
        /// <param name="data">the original data to encrypt</param>
        /// <returns>the encrypted data in a base 64 string</returns>
        private string EncryptWithPublicKey(string publicKey, string data)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(data);
            var encryptEngine  = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(publicKey))
            {
                var keyParameter = (AsymmetricKeyParameter) new Org.BouncyCastle.OpenSsl.PemReader(txtreader).ReadObject();

                encryptEngine.Init(true, keyParameter);
            }

            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encrypted);
        }
Esempio n. 18
0
        public static string RSADecrypt(string encryptStr, string publicKeyStr, int secretLength)
        {
            var bytesToDecrypt = Convert.FromBase64String(encryptStr);
            var decryptEngine  = new Pkcs1Encoding(new RsaEngine(), secretLength);

            using (var sr = GetStreamReader(publicKeyStr))
            {
                var keyParameter = (AsymmetricKeyParameter) new PemReader(sr).ReadObject();
                decryptEngine.Init(false, keyParameter);
            }

            var processBlock = decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length);
            var decryptStr   = Encoding.UTF8.GetString(processBlock);

            return(decryptStr);
        }
Esempio n. 19
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string Encrypt(string data, string publicKey)
        {
            var rsaKeyParameters = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            var engine           = new Pkcs1Encoding(new RsaEngine());

            engine.Init(true, rsaKeyParameters);
            var input  = Encoding.UTF8.GetBytes(data);
            var output = new List <byte>();
            var size   = Math.Min(engine.GetInputBlockSize(), input.Length);

            for (var i = 0; i < input.Length; i += size)
            {
                output.AddRange(engine.ProcessBlock(input, i, size));
            }
            return(Convert.ToBase64String(output.ToArray()));
        }
Esempio n. 20
0
        private async Task Decrypt(Stream inputStream, Stream outputStream, PrivateKey privateKey, Func <string> passwordFinder)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }
            var encryptEngine = new Pkcs1Encoding(new RsaEngine());
            var keyReader     = new StringReader(privateKey.Value);
            var pr            = passwordFinder != null ? new PemReader(keyReader, new PasswordFinder {
                Get = passwordFinder
            }) : new PemReader(keyReader);
            var keyParameter = (AsymmetricCipherKeyPair)pr.ReadObject();

            encryptEngine.Init(false, keyParameter?.Private ?? throw new ArgumentException("Private key was null"));
            await ProcessStream(inputStream, outputStream, encryptEngine);
        }
Esempio n. 21
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="privateKey"></param>
        /// <param name="isPKCS8"></param>
        /// <returns></returns>
        public static string Decrypt(string content, string privateKey, bool isPKCS8 = true)
        {
            var privateKeyParameters = getPrivateKeyParameters(privateKey, isPKCS8);
            var input  = Convert.FromBase64String(content);
            var engine = new Pkcs1Encoding(new RsaEngine());

            engine.Init(false, privateKeyParameters);
            var output = new List <byte>();
            var size   = Math.Min(engine.GetInputBlockSize(), input.Length);

            for (var i = 0; i < input.Length; i += size)
            {
                output.AddRange(engine.ProcessBlock(input, i, size));
            }
            return(Encoding.UTF8.GetString(output.ToArray()));
        }
        public static bool DecryptBuffer(this AsymmetricKeyParameter PrivateKey, string strHexedEncrypted, out byte[] aData)
        {
            aData = null;
            try
            {
                byte[] aEncryptedData = strHexedEncrypted.ToByteArray();
                var    decryptEngine  = new Pkcs1Encoding(new RsaEngine());
                decryptEngine.Init(false, PrivateKey);

                aData = decryptEngine.ProcessBlock(aEncryptedData, 0, aEncryptedData.Length);

                return(aData.Length > 0);
            }
            catch (Exception e) { e.CatchMessage().TraceError("DecryptBuffer(): "); }
            return(false);
        }
Esempio n. 23
0
        /// <summary>
        /// 公钥解密
        /// </summary>
        /// <param name="pContent">要解密的内容</param>
        /// <param name="pPublicKey">公钥</param>
        /// <returns></returns>
        public static string PublicKeyDecrypt(string pContent, string pPublicKey)
        {
            byte[] btPem = Convert.FromBase64String(pPublicKey);
            //加密、解密
            Asn1Object             pubKeyObj = Asn1Object.FromByteArray(btPem);//这里也可以从流中读取,从本地导入
            AsymmetricKeyParameter pubKey    = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj));
            IAsymmetricBlockCipher eng       = new Pkcs1Encoding(new RsaEngine());

            eng.Init(false, pubKey);
            //解密已加密的数据
            byte[] encryptedData = Convert.FromBase64String(pContent);
            encryptedData = eng.ProcessBlock(encryptedData, 0, encryptedData.Length);
            string result = Encoding.UTF8.GetString(encryptedData, 0, encryptedData.Length);

            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// 私钥加密
        /// </summary>
        /// <param name="s"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string EncryptByPrivateKey(string s, string key)
        {
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());

            try
            {
                engine.Init(true, GetPrivateKeyParameter(key));
                byte[] byteData   = System.Text.Encoding.UTF8.GetBytes(s);
                var    ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return(Convert.ToBase64String(ResultData));
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Esempio n. 25
0
        private byte[] RsaProcessor(byte[] data, int offset, int length, AsymmetricKeyParameter key)
        {
            Boolean forEncryption = !key.IsPrivate;

            _engine.Init(forEncryption, key);

            var blockSize = _engine.GetInputBlockSize();

            var result = new List <byte>();

            for (var i = offset; i < offset + length; i += blockSize)
            {
                var currentSize = Math.Min(blockSize, offset + length - i);
                result.AddRange(_engine.ProcessBlock(data, i, currentSize));
            }
            return(result.ToArray());
        }
Esempio n. 26
0
        public static string RSAEncrypt(byte[] bytesToEncrypt)
        {
            try
            {
                var publicKey     = TransformKey(KeyType.PublicKey);
                var encryptEngine = new Pkcs1Encoding(new RsaEngine());
                encryptEngine.Init(true, publicKey);

                var encrypted = encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length).ToBase64();
                return(encrypted);
            }
            catch (Exception e)
            {
                FileHelper.WriteFile(ErrorHelper.FormatError(e), FileHelper.ErrorPath, true);
                return(null);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Decrypt an encrypted text with RSA.
        /// </summary>
        /// <param name="encryptedText">The encrypted text.</param>
        /// <param name="privateKeyPath">The private key path.</param>
        /// <param name="chosenEncoding">The chosen encoding.</param>
        /// <returns>Returns a decrypted text.</returns>
        public static string Decrypt(string encryptedText, string privateKeyPath, string chosenEncoding = "UTF8")
        {
            var bytesToDecrypt = Encoding.Unicode.GetBytes(encryptedText);

            var decryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = System.IO.File.OpenText(privateKeyPath))
            {
                var privateKey = (AsymmetricCipherKeyPair) new PemReader(txtreader).ReadObject();

                decryptEngine.Init(false, privateKey.Private);
            }

            var decrypted = GeneralUtils.Encode(bytesToDecrypt, x => decryptEngine.ProcessBlock(x, 0, x.Length), chosenEncoding);

            return(decrypted);
        }
Esempio n. 28
0
        /// <summary>
        /// Encrypt a plain text with RSA and base64 encode it.
        /// </summary>
        /// <param name="clearText">The plain text.</param>
        /// <param name="publicKeyPath">The public key path.</param>
        /// <returns>Returns an encrypted and base64 encoded text.</returns>
        public static string EncryptAndBase64Encode(string clearText, string publicKeyPath)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);

            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = File.OpenText(publicKeyPath))
            {
                var publicKey = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();

                encryptEngine.Init(true, publicKey);
            }

            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));

            return(encrypted);
        }
Esempio n. 29
0
        /// <summary>
        /// Encrypt a plain text with RSA.
        /// </summary>
        /// <param name="plainText">The plain text.</param>
        /// <param name="publicKeyPath">The public key path.</param>
        /// <returns>Returns an encrypted text.</returns>
        public static string Encrypt(string plainText, string publicKeyPath)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(plainText);

            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = File.OpenText(publicKeyPath))
            {
                var publicKey = (AsymmetricKeyParameter) new PemReader(txtreader).ReadObject();

                encryptEngine.Init(true, publicKey);
            }

            var encrypted = GeneralUtils.Encode(bytesToEncrypt, x => encryptEngine.ProcessBlock(x, 0, x.Length), "Unicode");

            return(encrypted);
        }
Esempio n. 30
0
        public static string EncryptByPrivateKey(string s, string key)
        {
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());

            try
            {
                engine.Init(true, GetPrivateKeyParameter(key));
                var byteData   = Encoding.UTF8.GetBytes(s);
                var resultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return(Convert.ToBase64String(resultData));
                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }