static void test()
        {
            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 32));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            RsaKeyParameters pubKey = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters prKey  = (RsaKeyParameters)keyPair_s.Private;

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, prKey);
            byte[] plain_byte = BitConverter.GetBytes(10);

            byte[] enc = cipher.ProcessBlock(plain_byte, 0, plain_byte.Length);

            Org.BouncyCastle.Math.BigInteger test = new Org.BouncyCastle.Math.BigInteger(enc);
            Console.WriteLine(test);

            test = test.Multiply(new Org.BouncyCastle.Math.BigInteger(BitConverter.GetBytes(2)));

            test = test.Mod(prKey.Modulus);

            Console.WriteLine(test);

            byte[] new_enc = test.ToByteArray();

            cipher.Init(false, pubKey);

            byte[] dec = cipher.ProcessBlock(new_enc, 0, new_enc.Length);

            Console.WriteLine(BitConverter.ToInt32(dec));
        }
示例#2
0
        public string StereotypedAttack(string leftText, string rightText, int unknownLength, BigInteger cipher, string h)
        {
            RsaEngine rsa = new RsaEngine();

            rsa.Init(true, publicKey);

            string     solution;
            BigInteger left  = ParseBinaryBE(Encoding.Default.GetBytes(leftText));
            BigInteger right = ParseBinaryBE(Encoding.Default.GetBytes(rightText));

            using (StereotypedAttack_Wrapper stereotypedAttack = new StereotypedAttack_Wrapper(GetModulusNToString(), GetPublicExponentToString(), left.ToString(), right.ToString(), unknownLength, cipher.ToString(), h))
            {
                stereotypedAttack.Attack();
                solution = stereotypedAttack.GetSolution();
            }

            if (string.IsNullOrEmpty(solution))
            {
                throw new Exception(Languages.errorNoSolutionFound);
            }

            BigInteger bigInteger;

            BigInteger.TryParse(solution, out bigInteger);
            solution = Encoding.Default.GetString(bigInteger.ToByteArray().Reverse().ToArray());
            return(solution);
        }
示例#3
0
        public int GetBlockSize()
        {
            RsaEngine rsa = new RsaEngine();

            rsa.Init(true, publicKey);
            return(rsa.GetInputBlockSize());
        }
示例#4
0
        public static MemoryStream DecryptRsa(Stream inputStream, string pemKey)
        {
            AsymmetricKeyParameter keyParameter = ReadPem(pemKey);
            var engine = new RsaEngine();

            engine.Init(false, keyParameter);

            var outputStream    = new MemoryStream();
            int inputBlockSize  = engine.GetInputBlockSize();
            int outputBlockSize = engine.GetOutputBlockSize();

            byte[] inputBlock = new byte[inputBlockSize];
            while (inputStream.Read(inputBlock, 0, inputBlock.Length) > 0)
            {
                byte[] outputBlock = engine.ProcessBlock(inputBlock, 0, inputBlockSize);

                int requiredPadding = outputBlockSize - outputBlock.Length;
                if (requiredPadding > 0)
                {
                    byte[] paddedOutputBlock = new byte[outputBlockSize];
                    outputBlock.CopyTo(paddedOutputBlock, requiredPadding);
                    outputBlock = paddedOutputBlock;
                }

                outputStream.Write(outputBlock, 0, outputBlock.Length);
            }

            outputStream.Seek(0, SeekOrigin.Begin);
            return(outputStream);
        }
        public byte[] TransformRaw(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            int rsaKeyBitLength  = ((RsaKeyParameters)Key).Modulus.BitLength;
            int rsaKeyByteLength = (rsaKeyBitLength + 7) / 8;

            if (buffer.Length < rsaKeyByteLength)
            {
                byte[] extended = new byte[rsaKeyByteLength];
                Array.Copy(buffer, 0, extended, extended.Length - buffer.Length, buffer.Length);
                buffer = extended;
            }

            if (buffer.Length > rsaKeyByteLength)
            {
                throw new ArgumentOutOfRangeException(nameof(buffer), "Too long buffer to decrypt");
            }

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(false, Key);
            return(TransformInternal(buffer, cipher));
        }
示例#6
0
        public static string Decrypt(string CipherText, string mod, string exp)
        {
            var Modulus  = HelperFunctions.FromHexToByte(mod);
            var Exponent = HelperFunctions.FromHexToByte(exp);

            var CipherTextBytes = Convert.FromBase64String(CipherText);

            var modulus  = new BigInteger(1, Modulus);
            var exponent = new BigInteger(1, Exponent);

            var Parameters = new RsaKeyParameters(true, modulus, exponent);
            var RSAengine  = new RsaEngine();

            RSAengine.Init(false, Parameters);

            var blockSize = RSAengine.GetInputBlockSize();

            var output = new List <byte>();

            for (var chunkPosition = 0; chunkPosition < CipherTextBytes.Length; chunkPosition += blockSize)
            {
                var chunkSize = Math.Min(blockSize, CipherTextBytes.Length - chunkPosition * blockSize);
                output.AddRange(RSAengine.ProcessBlock(CipherTextBytes, chunkPosition, chunkSize));
            }

            var output2   = output.ToArray();
            var PlainText = Encoding.ASCII.GetString(output2);

            return(PlainText);
        }
示例#7
0
        public static byte[] Encrypt(byte[] data, AsymmetricKeyParameter pubKey)
        {
            var cipher = new RsaEngine();

            cipher.Init(true, pubKey);
            return(cipher.ProcessBlock(data, 0, data.Length));
        }
示例#8
0
        public static byte[] RsaEncrypt(byte[] bytesToEncrypt)
        {
            bytesToEncrypt = new byte[128 - bytesToEncrypt.Length].Concat(bytesToEncrypt).ToArray();

            try
            {
                var encryptEngine = new RsaEngine(); // new Pkcs1Encoding (new RsaEngine());


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

                    encryptEngine.Init(true, keyParameter);
                }

                byte[] encrypted = encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);
                return(encrypted);
            }
            catch
            {
                return(new byte[0] {
                });
            }
        }
示例#9
0
        public byte[] Decrypt(byte[] data)
        {
            var engine = new RsaEngine();

            engine.Init(false, PrivateKey);
            return(engine.ProcessBlock(data, 0, data.Length));
        }
示例#10
0
        public byte[] Decrypt(byte[] raw)
        {
            RsaEngine eng = new RsaEngine();

            eng.Init(false, _privateKey);
            return(eng.ProcessBlock(raw, 0, raw.Length));
        }
示例#11
0
        public static string Encrypt2(string publicKeyFileName, string inputMessage)
        {
            //AsymmetricCipherKeyPair keyPair = GetPublicKey("");
            AsymmetricKeyParameter keyPair = GetPublicKey(publicKeyFileName);
            UTF8Encoding           utf8enc = new UTF8Encoding();

            try
            {
                // Converting the string message to byte array
                byte[] inputBytes = utf8enc.GetBytes(inputMessage);

                AsymmetricKeyParameter publicKey = keyPair;//ReadAsymmetricKeyParameter(publicKeyFileName);

                // Creating the RSA algorithm object
                IAsymmetricBlockCipher cipher = new RsaEngine();

                // Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
                cipher.Init(true, publicKey);

                //Encrypting the input bytes
                byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);

                String encrypt = Convert.ToBase64String(cipheredBytes);

                return(encrypt);
            }
            catch (Exception ex)
            {
                // Any errors? Show them
                throw new Exception("Encrypt string fail, detail as folowing", ex);
            }
        }
示例#12
0
        /// <returns>signature</returns>
        public byte[] Sign(byte[] data)
        {
            var signer = new RsaEngine();

            signer.Init(forEncryption: true, parameters: KeyPair.Private);
            return(signer.ProcessBlock(data, 0, data.Length));
        }
示例#13
0
        /// <summary>
        /// 使用私钥解密
        /// </summary>
        /// <param name="encryptString">待解密字符串</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="desKey">私钥解密字符串</param>
        /// <param name="result">返回解密后的字符串</param>
        /// <returns></returns>
        public static bool DecryptByPrivateKey(string encryptString, string privateKey, string pwd, ref string result)
        {
            _error = "";

            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();

            //解密
            try
            {
                engine.Init(false, GetPrivateKeyParameter(privateKey, pwd));

                byte[] byteData = Convert.FromBase64String(encryptString);
                if (byteData.Length > 172)
                {
                    _error = "非加密字符串";
                    return(false);
                }

                byteData = engine.ProcessBlock(byteData, 0, byteData.Length);
                result   = Encoding.UTF8.GetString(byteData);
                return(true);
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return(false);
            }
        }
        public byte[] TransformRaw(byte[] buffer, int outputLength)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, Key);
            if (outputLength > cipher.GetOutputBlockSize())
            {
                throw new ArgumentOutOfRangeException(nameof(outputLength), "Too large output length");
            }

            byte[] transformed = TransformInternal(buffer, cipher);
            if (transformed.Length == outputLength)
            {
                return(transformed);
            }

            byte[] truncated = new byte[outputLength];
            Array.Copy(transformed, transformed.Length - outputLength, truncated, 0, outputLength);
            return(truncated);
        }
示例#15
0
        public override void init(Key key, byte mode)
        {
            var rsaKey        = (RSAPrivateKey)key;
            var rsaParameters = new RsaKeyParameters(true, new BigInteger(rsaKey.Modulus.ToHexa('\0'), 16), new BigInteger(rsaKey.Exponent.ToHexa('\0'), 16));

            rsa.Init(true, rsaParameters);
        }
        public static byte[] ring_sign(RsaKeyParameters[] P, string m, RsaKeyParameters Ks, byte[][] X)
        {
            Console.WriteLine("Ring signing");
            byte[] k1 = Encoding.UTF8.GetBytes(m);

            byte[] k = new byte[64];

            for (int i = 0; i < k1.Length; ++i)
            {
                k[i] = (byte)(k[i] + k1[i]);
            }


            byte[][] y = new byte[11][];

            for (int i = 0; i < 11; ++i)
            {
                IAsymmetricBlockCipher cipher = new RsaEngine();
                cipher.Init(true, P[i]);

                y[i] = cipher.ProcessBlock(X[i], 0, X[i].Length);
            }

            byte[] ring = y[0];
            for (int i = 1; i < 11; ++i)
            {
                ring = exclusiveOR(ring, k);
                ring = exclusiveOR(ring, y[i]);
            }

            byte[] v = ring;
            return(v);
        }
示例#17
0
        public static string RSAText(byte[] input, string keyString, bool encrypt)
        {
            TextReader             reader    = new StringReader(keyString);
            PemReader              pemReader = new PemReader(reader);
            AsymmetricKeyParameter pemKey;

            if (encrypt)
            {
                pemKey = (AsymmetricKeyParameter)pemReader.ReadObject();
            }
            else
            {
                AsymmetricCipherKeyPair keyAckp = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                pemKey = keyAckp.Private;
            }

            RsaEngine engineEncDec = new RsaEngine();

            engineEncDec.Init(encrypt, pemKey);
            string engineOutput;

            try
            {
                engineOutput = Convert.ToBase64String(engineEncDec.ProcessBlock(input, 0, input.Length));
            }
            catch (Org.BouncyCastle.Crypto.DataLengthException)
            {
                throw (new KriviUnosException("Datoteka je prevelika za RSA šifriranje"));
            }
            return(engineOutput);
        }
示例#18
0
        /// <summary>
        /// (使用java格式密钥)解密
        /// </summary>
        /// <param name="data">密文</param>
        /// <param name="isPrivateKey">是否使用私钥解密</param>
        /// <returns></returns>
        public static string JDecrypt(string data, bool isPrivateKey = true)
        {
            string key = null;

            RsaKeyParameters keyParam = null;

            if (isPrivateKey)
            {
                key      = _rsakeys.JPrivateKey;
                keyParam = (RsaKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(key));
            }
            else
            {
                key      = _rsakeys.JPublicKey;
                keyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(key));
            }

            byte[] cipherbytes = Convert.FromBase64String(data);

            RsaEngine rsa = new RsaEngine();

            rsa.Init(false, keyParam);

            cipherbytes = rsa.ProcessBlock(cipherbytes, 0, cipherbytes.Length);

            return(Encoding.UTF8.GetString(cipherbytes));
        }
        public static void ring_verify(RsaKeyParameters[] P, byte[] v, byte[][] X, string m)
        {
            Console.WriteLine("Ring signature verification");

            byte[][] y = new byte[11][];

            for (int i = 0; i < 11; ++i)
            {
                IAsymmetricBlockCipher cipher = new RsaEngine();
                cipher.Init(true, P[i]);

                y[i] = cipher.ProcessBlock(X[i], 0, X[i].Length);
            }

            byte[] k1 = Encoding.UTF8.GetBytes(m);

            byte[] k = new byte[64];

            for (int i = 0; i < k1.Length; ++i)
            {
                k[i] = (byte)(k[i] + k1[i]);
            }


            byte[] ring = y[0];
            for (int i = 1; i < 11; ++i)
            {
                ring = exclusiveOR(ring, k);
                ring = exclusiveOR(ring, y[i]);
            }
            Console.WriteLine("v: " + ByteArrayToString(v));
            Console.WriteLine("ring: " + ByteArrayToString(ring));
        }
示例#20
0
        /// <summary>
        /// 字符串解密(私钥加密公钥解密)
        /// </summary>
        /// <param name="encryptString">密文</param>
        /// <param name="publicKey">公钥</param>
        /// <returns>遇到解密失败将会返回原字符串</returns>
        public static string DecryptString(string dncryptString, string publicKey)
        {
            string source = string.Empty;

            byte[] decryptData   = Convert.FromBase64String(dncryptString);
            byte[] publicKeyData = Convert.FromBase64String(publicKey);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();

            //还原
            AsymmetricKeyParameter publicKeyObj = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyData);

            //公钥解密
            engine.Init(false, publicKeyObj);
            try
            {
                decryptData = engine.ProcessBlock(decryptData, 0, decryptData.Length);
                source      = Encoding.UTF8.GetString(decryptData);
            }
            catch (Exception)
            {
                source = dncryptString;
                //throw new Exception("failed - exception " + e.ToString());
            }
            return(source);
        }
示例#21
0
        ///<summary>
        ///
        /// Metodo para descriptografia assimétrica RSA utilizando BouncyCastle
        ///
        ///</summary>
        public static string decifraAssimetrica(string caminhoChave, string conteudoCifrado)
        {
            try
            {
                byte[] conteudoCifradoBytes = Convert.FromBase64String(conteudoCifrado);

                //lendo chave privada
                AsymmetricCipherKeyPair chavePrivadaParametros = retornaParametrosChavePrivada(caminhoChave);

                //decifrando texto
                IAsymmetricBlockCipher decifra = new RsaEngine();
                decifra.Init(false, chavePrivadaParametros.Private);
                byte[] conteudoDecifradoBytes = decifra.ProcessBlock(conteudoCifradoBytes, 0, conteudoCifradoBytes.Length);

                string conteudoDecifrado = Encoding.UTF8.GetString(conteudoDecifradoBytes);

                return(conteudoDecifrado);
            }
            catch (excecao.excecao ex)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
            catch (NullReferenceException nu)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
        }
示例#22
0
        /// <returns>signature</returns>
        public byte[] SignBlindedData(byte[] blindedData)
        {
            var signer = new RsaEngine();

            signer.Init(forEncryption: false, parameters: KeyPair.Private);
            return(signer.ProcessBlock(blindedData, 0, blindedData.Length));
        }
        public byte[] Sign(byte[] blindedContent)
        {
            RsaEngine engine = new RsaEngine();

            engine.Init(true, keys.Private);
            return(engine.ProcessBlock(blindedContent, 0, blindedContent.Length));
        }
示例#24
0
        private void checkForPkcs1Exception(RsaKeyParameters pubParameters, RsaKeyParameters privParameters, byte[] inputData, string expectedMessage)
        {
            IAsymmetricBlockCipher eng = new RsaEngine();

            eng.Init(true, privParameters);

            byte[] data = null;

            try
            {
                data = eng.ProcessBlock(inputData, 0, inputData.Length);
            }
            catch (Exception e)
            {
                Fail("RSA: failed - exception " + e.ToString(), e);
            }

            eng = new Pkcs1Encoding(eng);

            eng.Init(false, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);

                Fail("missing data block not recognised");
            }
            catch (InvalidCipherTextException e)
            {
                if (!e.Message.Equals(expectedMessage))
                {
                    Fail("RSA: failed - exception " + e.ToString(), e);
                }
            }
        }
示例#25
0
        /// <summary>
        /// 使用公钥加密
        /// </summary>
        /// <param name="s">待加密字符串</param>
        /// <param name="publicKey">公钥</param>
        /// <param name="result">返回加密后的字符串</param>
        /// <returns></returns>
        public static bool EncryptByPublicKey(string s, string publicKey, ref string result)
        {
            _error = "";

            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();

            try
            {
                engine.Init(true, GetPublicKeyParameter(publicKey));
                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
                if (byteData.Length > 128)
                {
                    _error = "加密字符串长度不能超过128位";
                    return(false);
                }
                byte[] ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                result = Convert.ToBase64String(ResultData);
                return(true);
                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return(false);
            }
        }
        public byte[] blindSignature(byte[] input)
        {
            RsaEngine rsaEngine = new RsaEngine();

            rsaEngine.Init(true, bobKeyPair.Private);
            byte[] blindSignedMessage = rsaEngine.ProcessBlock(input, 0, input.Length);
            return(blindSignedMessage);
        }
示例#27
0
文件: RSA.cs 项目: Devwarlt/RotMG_Lib
        private RSA(TextReader pubPem)
        {
            object obj = new PemReader(pubPem).ReadObject();

            key    = (obj as RsaKeyParameters);
            engine = new RsaEngine();
            engine.Init(true, key);
        }
示例#28
0
        public static string Decrypt(byte[] input)
        {
            InitializeEncryption();
            var decryptEngine = new RsaEngine();

            decryptEngine.Init(false, keys.Public);
            return(decryptEngine.ProcessBlock(input, 0, input.Length).ToStringUTF());
        }
示例#29
0
        public static byte[] BouncyCastleRsaEncrypt(byte[] data, string exponent, string modulus)
        {
            var engine        = new RsaEngine();
            var keyParameters = new RsaKeyParameters(false, new BigInteger(HexDecode(modulus)), new BigInteger(HexDecode(exponent)));

            engine.Init(true, keyParameters);
            return(engine.ProcessBlock(data, 0, data.Length));
        }
示例#30
0
        public void TestRsa()
        {
            var generator = new RsaKeyPairGenerator();

            generator.Init(new RsaKeyGenerationParameters(new BigInteger("11", 16), new SecureRandom(), 128, 6));
            var pair      = generator.GenerateKeyPair();
            var rsaEngine = new RsaEngine();

            rsaEngine.Init(true, pair.Public);
            var data  = Encoding.UTF8.GetBytes("Hello world");
            var xdata = rsaEngine.ProcessBlock(data, 0, data.Length);

            rsaEngine.Init(false, pair.Private);
            var rdata = rsaEngine.ProcessBlock(xdata, 0, xdata.Length);

            Assert.AreEqual("Hello world", Encoding.UTF8.GetString(rdata));
        }