Inheritance: IAsymmetricBlockCipher
        private static void Encrypt(OutMessage msg, RsaEngine engine)
        {
            var encrpted = engine.ProcessBlock(msg.Buffer, msg.WritePosition, 128);

            if (msg.WritePosition + 128 > msg.Size)
                msg.Size = msg.WritePosition + 128;

            Array.Copy(encrpted, 0, msg.Buffer, msg.WritePosition, 128);
            msg.Encrypted = true;
        }
Exemple #2
0
		private void doTestStrictPkcs1Length(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
		{
			IAsymmetricBlockCipher   eng = new RsaEngine();

			eng.Init(true, privParameters);

			byte[] data = null;

			try
			{
				data = eng.ProcessBlock(oversizedSig, 0, oversizedSig.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("oversized signature block not recognised");
			}
			catch (InvalidCipherTextException e)
			{
				if (!e.Message.Equals("block incorrect size"))
				{
					Fail("RSA: failed - exception " + e.ToString(), e);
				}
			}


			// Create the encoding with StrictLengthEnabled=false (done thru environment in Java version)
			Pkcs1Encoding.StrictLengthEnabled = false;

			eng = new Pkcs1Encoding(new RsaEngine());

			eng.Init(false, pubParameters);

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

			Pkcs1Encoding.StrictLengthEnabled = true;
		}
Exemple #3
0
    private static string decryptWithUserPublic(string content, AsymmetricCipherKeyPair clientKeyPair)
    {
        var bytesToDecrypt = Convert.FromBase64String(content);

        var decryptEngine = new Org.BouncyCastle.Crypto.Engines.RsaEngine();

        decryptEngine.Init(false, clientKeyPair.Public);

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

        return(decrypted);
    }
Exemple #4
0
    private static string encryptWithUserPrivate(string content, AsymmetricCipherKeyPair clientKeyPair)
    {
        var bytesToEncrypt = System.Text.Encoding.UTF8.GetBytes(content);
        var engine         = new Org.BouncyCastle.Crypto.Engines.RsaEngine();

        engine.Init(true, clientKeyPair.Private);

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

        return(cryptMessage);
    }
Exemple #5
0
        public static byte[] EncryptRSA(byte[] PlainData, AsymmetricKeyParameter Key)
        {
            RsaEngine Engine = new RsaEngine();
            Engine.Init(true, Key);

            int BlockSize = Engine.GetInputBlockSize();
            List<Byte> Output = new List<Byte>();

            for (int ChunkPosition = 0; ChunkPosition < PlainData.Length; ChunkPosition += BlockSize)
            {
                int ChunkSize = Math.Min(BlockSize, PlainData.Length -(ChunkPosition * BlockSize));
                Output.AddRange(Engine.ProcessBlock(PlainData, ChunkPosition, ChunkSize));
            }
            return Output.ToArray();
        }
Exemple #6
0
        static Rsa()
        {
            try
            {
                EncryptRsaEngine = new RsaEngine();
                EncryptRsaEngine.Init(true, new RsaKeyParameters(false, new BigInteger(OtM), new BigInteger(OtE)));

                DecryptRsaEngine = new RsaEngine();
                DecryptRsaEngine.Init(false, new RsaPrivateCrtKeyParameters(new BigInteger(OtM), new BigInteger(OtE),
                    new BigInteger(OtD), new BigInteger(OtP), new BigInteger(OtQ), new BigInteger(OtDp), new BigInteger(OtDq), new BigInteger(OtInverseq)));

            }
            catch (Exception e)
            {
                throw new Exception("Error initializing rsa engine.", e);
            }
        }
        static Rsa()
        {
            var openTibiaDecryptKey = new RsaPrivateCrtKeyParameters(new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE),
                new BigInteger(Constants.RSAKey.OpenTibiaE), new BigInteger(Constants.RSAKey.OpenTibiaP), new BigInteger(Constants.RSAKey.OpenTibiaQ),
                new BigInteger(Constants.RSAKey.OpenTibiaDP), new BigInteger(Constants.RSAKey.OpenTibiaDQ), new BigInteger(Constants.RSAKey.OpenTibiaInverseQ));

            openTibiaDecryptEngine = new RsaEngine();
            openTibiaDecryptEngine.Init(false, openTibiaDecryptKey);

            var realTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.RealTibiaM), new BigInteger(Constants.RSAKey.RealTibiaE));
            realTibiaEncryptEngine = new RsaEngine();
            realTibiaEncryptEngine.Init(true, realTibiaEncryptKey);

            var openTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE));
            openTibiaEncryptEngine = new RsaEngine();
            openTibiaEncryptEngine.Init(true, openTibiaEncryptKey);
        }
Exemple #8
0
    public static string encryptWithServerPublic(string content)
    {
        string publicKeyPath  = Application.dataPath + "/public_key.txt";
        var    bytesToEncrypt = System.Text.Encoding.UTF8.GetBytes(content);
        AsymmetricKeyParameter keyPair;

        using (var reader = System.IO.File.OpenText(publicKeyPath))
            keyPair = (AsymmetricKeyParameter) new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();

        //var engine = new Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding(new Org.BouncyCastle.Crypto.Engines.RsaEngine());
        var engine = new Org.BouncyCastle.Crypto.Engines.RsaEngine();

        engine.Init(true, keyPair);

        var encrypted = engine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);

        var cryptMessage = Convert.ToBase64String(encrypted);

        return(cryptMessage);
    }
Exemple #9
0
        /// <summary>
        /// Check an Active Authentication reply from the passport.
        /// </summary>
        /// <param name="publicKey">The AA public key read from the passport.</param>
        /// <param name="message">The original message.</param>
        /// <param name="signature">The response from the passport</param>
        /// <returns>True if the signature is correct for this message.</returns>
        public static bool CheckAA(RsaPublicKeyStructure publicKey, byte[] message, byte[] signature)
        {
            SHA1 sha1 = SHA1.Create();
            RsaEngine rsa = new RsaEngine();
            RsaKeyParameters p = new RsaKeyParameters(false, publicKey.Modulus, publicKey.PublicExponent);
            rsa.Init(false, p);

            byte[] digestedMessage = sha1.ComputeHash(message); // should always be 20 bytes
            byte[] m2 = new byte[8];
            Array.Copy(digestedMessage, 0, m2, 0, m2.Length);
            byte[] plainText = rsa.ProcessBlock(signature, 0, signature.Length);
            byte[] m1 = recoverMessage(digestedMessage.Length, plainText);

            Sha1Digest digest = new Sha1Digest();
            Iso9796d2Signer signer = new Iso9796d2Signer(rsa, digest);
            signer.Init(false, p);
            signer.BlockUpdate(m1, 0, m1.Length);
            signer.BlockUpdate(m2, 0, m2.Length);
            return signer.VerifySignature(signature);
        }
Exemple #10
0
        ///<summary>
        ///
        /// Metodo para criptografia assimétrica RSA utilizando BouncyCastle
        /// 
        ///</summary>
        public static string cifraAssimetrica(string caminhoChave, string conteudoClaro)
        {
            try
            {
                byte[] conteudoBytes = Encoding.UTF8.GetBytes(conteudoClaro);

                //lendo certificado
                AsymmetricKeyParameter certificadoParametros = retornaParametrosCertificado(caminhoChave);

                //cifrando texto
                IAsymmetricBlockCipher cifra = new RsaEngine();
                cifra.Init(true, certificadoParametros);
                byte[] conteudoCifrado = cifra.ProcessBlock(conteudoBytes, 0, conteudoBytes.Length);

                //Converte pra base64
                string conteudoBase64 = Convert.ToBase64String(conteudoCifrado);

                return conteudoBase64;
            }
            catch (excecao.excecao ex)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
        }
Exemple #11
0
        public virtual void DoTest5()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - Signing
            //
            Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true);

            eng.Init(true, privParameters);

            eng.Update(msg5[0]);
            eng.BlockUpdate(msg5, 1, msg5.Length - 1);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig5, 0, data))
            {
                Fail("failed ISO9796-2 generation Test 5");
            }

            eng.Update(msg5[0]);
            eng.BlockUpdate(msg5, 1, msg5.Length - 1);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 5");
            }

            if (eng.HasFullMessage())
            {
                Fail("fullMessage true - Test 5");
            }

            if (!StartsWith(msg5, eng.GetRecoveredMessage()))
            {
                Fail("failed ISO9796-2 partial recovered message Test 5");
            }

            int length = eng.GetRecoveredMessage().Length;

            if (length >= msg5.Length)
            {
                Fail("Test 5 recovered message too long");
            }

            eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true);

            eng.Init(false, pubParameters);

            eng.UpdateWithRecoveredMessage(sig5);

            if (!StartsWith(msg5, eng.GetRecoveredMessage()))
            {
                Fail("failed ISO9796-2 updateWithRecovered partial recovered message Test 5");
            }

            if (eng.HasFullMessage())
            {
                Fail("fullMessage updateWithRecovered true - Test 5");
            }

            for (int i = length ; i != msg5.Length; i++)
            {
                eng.Update(msg5[i]);
            }

            if (!eng.VerifySignature(sig5))
            {
                Fail("failed ISO9796-2 verify Test 5");
            }

            if (eng.HasFullMessage())
            {
                Fail("fullMessage updateWithRecovered true - Test 5");
            }

            // should fail
            eng.UpdateWithRecoveredMessage(sig5);

            eng.BlockUpdate(msg5, 0, msg5.Length);

            if (eng.VerifySignature(sig5))
            {
                Fail("failed ISO9796-2 updateWithRecovered verify fail Test 5");
            }
        }
Exemple #12
0
        public virtual void DoTest6()
        {
            byte[] salt = Hex.Decode("61DF870C4890FE85D6E3DD87C3DCE3723F91DB49");
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6);
            ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - PSS Signing
            //
            Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, true);

            eng.Init(true, sigParameters);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig6, 1, data))
            {
                Fail("failed ISO9796-2 generation Test 6");
            }

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 6");
            }
        }
Exemple #13
0
        public virtual void DoTest3()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod2, pub2);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod2, pri2);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-1 - public encrypt, private decrypt
            //
            ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa);

            eng.Init(true, privParameters);

            eng.SetPadBits(4);

            data = eng.ProcessBlock(msg3, 0, msg3.Length);

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig3, 1, data))
            {
                Fail("failed ISO9796-1 generation Test 3");
            }

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

            if (!IsSameAs(msg3, 0, data))
            {
                Fail("failed ISO9796-1 retrieve Test 3");
            }
        }
Exemple #14
0
        public virtual void DoTest4()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - Signing
            //
            Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD128Digest());

            eng.Init(true, privParameters);

            eng.Update(msg4[0]);
            eng.BlockUpdate(msg4, 1, msg4.Length - 1);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig4, 0, data))
            {
                Fail("failed ISO9796-2 generation Test 4");
            }

            eng.Update(msg4[0]);
            eng.BlockUpdate(msg4, 1, msg4.Length - 1);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 4");
            }

            if (eng.HasFullMessage())
            {
                eng = new Iso9796d2Signer(rsa, new RipeMD128Digest());

                eng.Init(false, pubParameters);

                if (!eng.VerifySignature(sig4))
                {
                    Fail("failed ISO9796-2 verify and recover Test 4");
                }

                if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4))
                {
                    Fail("failed ISO9796-2 recovered message Test 4");
                }

                // try update with recovered
                eng.UpdateWithRecoveredMessage(sig4);

                if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4))
                {
                    Fail("failed ISO9796-2 updateWithRecovered recovered message Test 4");
                }
                
                if (!eng.VerifySignature(sig4))
                {
                    Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4");
                }
                
                if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4))
                {
                    Fail("failed ISO9796-2 updateWithRecovered recovered verify message Test 4");
                }
                
                // should fail
                eng.UpdateWithRecoveredMessage(sig4);
                
                eng.BlockUpdate(msg4, 0, msg4.Length);
                
                if (eng.VerifySignature(sig4))
                {
                    Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4");
                }
            }
            else
            {
                Fail("full message flag false - Test 4");
            }
        }
        public override void PerformTest()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);
            byte[] data = Hex.Decode(edgeInput);

            //
            // RAW
            //
            IAsymmetricBlockCipher   eng = new RsaEngine();

            eng.Init(true, pubParameters);

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

            eng.Init(false, privParameters);

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

            if (!edgeInput.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW edge Test");
            }

            data = Hex.Decode(input);

            eng.Init(true, pubParameters);

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

            eng.Init(false, privParameters);

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

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW Test");
            }

            //
            // PKCS1 - public encrypt, private decrypt
            //
            eng = new Pkcs1Encoding(eng);

            eng.Init(true, pubParameters);

            if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
            {
                Fail("PKCS1 output block size incorrect");
            }

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

            eng.Init(false, privParameters);

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

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed PKCS1 public/private Test");
            }

            //
            // PKCS1 - private encrypt, public decrypt
            //
            eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());

            eng.Init(true, privParameters);

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

            eng.Init(false, pubParameters);

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

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed PKCS1 private/public Test");
            }

            testZeroBlock(pubParameters, privParameters);
            testZeroBlock(privParameters, pubParameters);

            //
            // key generation test
            //
            RsaKeyPairGenerator  pGen = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters  genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);

            pGen.Init(genParam);

            IAsymmetricCipherKeyPair  pair = pGen.GenerateKeyPair();

            eng = new RsaEngine();

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
            {
                Fail("failed key generation (768) length test");
            }

            eng.Init(true, pair.Public);

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

            eng.Init(false, pair.Private);

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

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (768) Test");
            }

            genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

            pGen.Init(genParam);
            pair = pGen.GenerateKeyPair();

            eng.Init(true, pair.Public);

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
            {
                Fail("failed key generation (1024) length test");
            }

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

            eng.Init(false, pair.Private);

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

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (1024) test");
            }

            genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 16, 25);
            pGen.Init(genParam);

            for (int i = 0; i < 100; ++i)
            {
                pair = pGen.GenerateKeyPair();
                RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters) pair.Private;
                IBigInteger pqDiff = privKey.P.Subtract(privKey.Q).Abs();

                if (pqDiff.BitLength < 5)
                {
                    Fail("P and Q too close in RSA key pair");
                }
            }

            doTestBadSig();
            doTestOaep(pubParameters, privParameters);
            doTestStrictPkcs1Length(pubParameters, privParameters);
            doTestDudPkcs1Block(pubParameters, privParameters);
            doTestMissingDataPkcs1Block(pubParameters, privParameters);
            doTestTruncatedPkcs1Block(pubParameters, privParameters);
            doTestWrongPaddingPkcs1Block(pubParameters, privParameters);

            try
            {
                new RsaEngine().ProcessBlock(new byte[]{ 1 }, 0, 1);
                Fail("failed initialisation check");
            }
            catch (InvalidOperationException)
            {
                // expected
            }
        }
Exemple #16
0
        public virtual void DoTest2()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod1, pub1);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod1, pri1);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-1 - public encrypt, private decrypt
            //
            ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa);

            eng.Init(true, privParameters);

            data = eng.ProcessBlock(msg2, 0, msg2.Length);

            eng.Init(false, pubParameters);

            if (!IsSameAs(data, 1, sig2))
            {
                Fail("failed ISO9796-1 generation Test 2");
            }

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

            if (!AreEqual(msg2, data))
            {
                Fail("failed ISO9796-1 retrieve Test 2");
            }
        }
Exemple #17
0
        public virtual void DoTest12()
        {
            BigInteger          mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16);
            BigInteger          pubExp = new BigInteger("65537", 10);
            BigInteger          priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16);
            RsaKeyParameters    pubParameters = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters    privParameters = new RsaKeyParameters(true, mod, priExp);
            RsaEngine           rsa = new RsaEngine();
            byte[]              data;
            byte[]              m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[]              m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            byte[]              m3 = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //
            // ISO 9796-2 - Regular Signing
            //
            IDigest           dig = new Sha1Digest();
            Iso9796d2Signer  eng = new Iso9796d2Signer(rsa, dig);

            //
            // check message bounds
            //
            eng.Init(true, privParameters);

            eng.BlockUpdate(m1, 0, m1.Length);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m2, 0, m2.Length);

            if (eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 m2 verify Test 12");
            }

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m3, 0, m3.Length);

            if (eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 m3 verify Test 12");
            }

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m1, 0, m1.Length);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 12");
            }
        }
        /// <summary>
        /// Enroll the authenticator with the server.
        /// </summary>
        public void Enroll()
        {
            // default to US
            string region = REGION_US;
            string country = REGION_US;

            // Battle.net does a GEO IP lookup anyway so there is no need to pass the region
            // however China has its own URL so we must still do our own GEO IP lookup to find the country
            HttpWebRequest georequest = (HttpWebRequest)WebRequest.Create(GEOIPURL);
            georequest.Method = "GET";
            georequest.ContentType = "application/json";
            // get response
            string responseString = null;
            using (HttpWebResponse georesponse = (HttpWebResponse)georequest.GetResponse())
            {
                // OK?
                if (georesponse.StatusCode == HttpStatusCode.OK)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream bs = georesponse.GetResponseStream())
                        {
                            byte[] temp = new byte[RESPONSE_BUFFER_SIZE];
                            int read;
                            while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
                            {
                                ms.Write(temp, 0, read);
                            }
                            responseString = Encoding.UTF8.GetString(ms.ToArray());
                        }
                    }
                }
            }
            if (string.IsNullOrEmpty(responseString) == false)
            {
                // not worth a full json parser, just regex it
                Match match = Regex.Match(responseString, ".*\"country\":\"([^\"]*)\".*", RegexOptions.IgnoreCase);
                if (match.Success == true)
                {
                    // match the correct region
                    country = match.Groups[1].Value.ToUpper();

                    if (EU_COUNTRIES.Contains(country) == true)
                    {
                        region = REGION_EU;
                    }
                    else if (KR_COUNTRIES.Contains(country) == true)
                    {
                        region = REGION_KR;
                    }
                    else if (country == REGION_CN)
                    {
                        region = REGION_CN;
                    }
                    else
                    {
                        region = REGION_US;
                    }
                }
            }

            // allow override of country for CN using US from app.config
            System.Configuration.AppSettingsReader config = new System.Configuration.AppSettingsReader();
            try
            {
                string configcountry = config.GetValue("BattleNetAuthenticator.Country", typeof(string)) as string;
                if (string.IsNullOrEmpty(configcountry) == false)
                {
                    country = configcountry;
                }
            }
            catch (InvalidOperationException ) { }
            try
            {
                string configregion = config.GetValue("BattleNetAuthenticator.Region", typeof(string)) as string;
                if (string.IsNullOrEmpty(configregion) == false)
                {
                    region = configregion;
                }
            }
            catch (InvalidOperationException ) {}

            // generate byte array of data:
            //  00 byte[20] one-time key used to decrypt data when returned;
            //  20 byte[2] country code, e.g. US, GB, FR, KR, etc
            //  22 byte[16] model string for this device;
            //	38 END
            byte[] data = new byte[38];
            byte[] oneTimePad = CreateOneTimePad(20);
            Array.Copy(oneTimePad, data, oneTimePad.Length);
            // add country
            byte[] countrydata = Encoding.UTF8.GetBytes(country);
            Array.Copy(countrydata, 0, data, 20, Math.Min(countrydata.Length, 2));
            // add model name
            byte[] model = Encoding.UTF8.GetBytes(GeneralRandomModel());
            Array.Copy(model, 0, data, 22, Math.Min(model.Length, 16));

            // encrypt the data with BMA public key
            RsaEngine rsa = new RsaEngine();
            rsa.Init(true, new RsaKeyParameters(false, new Org.BouncyCastle.Math.BigInteger(ENROLL_MODULUS, 16), new Org.BouncyCastle.Math.BigInteger(ENROLL_EXPONENT, 16)));
            byte[] encrypted = rsa.ProcessBlock(data, 0, data.Length);

            // call the enroll server
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetMobileUrl(region) + ENROLL_PATH);
            request.Method = "POST";
            request.ContentType = "application/octet-stream";
            request.ContentLength = encrypted.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(encrypted, 0, encrypted.Length);
            requestStream.Close();
            byte[] responseData = null;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                // OK?
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new InvalidEnrollResponseException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription));
                }

                // load back the buffer - should only be a byte[45]
                using (MemoryStream ms = new MemoryStream())
                {
                    //using (BufferedStream bs = new BufferedStream(response.GetResponseStream()))
                    using (Stream bs = response.GetResponseStream())
                    {
                        byte[] temp = new byte[RESPONSE_BUFFER_SIZE];
                        int read;
                        while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
                        {
                            ms.Write(temp, 0, read);
                        }
                        responseData = ms.ToArray();

                        // check it is correct size
                        if (responseData.Length != ENROLL_RESPONSE_SIZE)
                        {
                          throw new InvalidEnrollResponseException(string.Format("Invalid response data size (expected 45 got {0})", responseData.Length));
                        }
                    }
                }
            }

            // return data:
            // 00-07 server time (Big Endian)
            // 08-24 serial number (17)
            // 25-44 secret key encrpyted with our pad
            // 45 END

            // extract the server time
            byte[] serverTime = new byte[8];
            Array.Copy(responseData, serverTime, 8);
            if (BitConverter.IsLittleEndian == true)
            {
                Array.Reverse(serverTime);
            }
            // get the difference between the server time and our current time
            ServerTimeDiff = BitConverter.ToInt64(serverTime, 0) - CurrentTime;

            // get the secret key
            byte[] secretKey = new byte[20];
            Array.Copy(responseData, 25, secretKey, 0, 20);
            // decrypt the initdata with a simple xor with our key
            for (int i = oneTimePad.Length-1; i >= 0; i--)
            {
                secretKey[i] ^= oneTimePad[i];
            }
            SecretKey = secretKey;

            // get the serial number
            Serial = Encoding.Default.GetString(responseData, 8, 17);
        }
Exemple #19
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);
            }
        }
Exemple #20
0
        public virtual void DoTest9()
        {
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - PSS Signing
            //
            Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 0, true);

            eng.Init(true, privParameters);

            eng.Update(msg9[0]);
            eng.BlockUpdate(msg9, 1, msg9.Length - 1);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig9, 0, data))
            {
                Fail("failed ISO9796-2 generation Test 9");
            }

            eng.Update(msg9[0]);
            eng.BlockUpdate(msg9, 1, msg9.Length - 1);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 9");
            }
        }
        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);
                }
            }
        }
Exemple #22
0
		/// <summary>
		/// Restore an authenticator from the serial number and restore code.
		/// </summary>
		/// <param name="serial">serial code, e.g. US-1234-5678-1234</param>
		/// <param name="restoreCode">restore code given on enroll, 10 chars.</param>
		public async Task Restore(string serial, string restoreCode)
		{
			// get the serial data
			byte[] serialBytes = Encoding.UTF8.GetBytes(serial.ToUpper().Replace("-", string.Empty));

			// send the request to the server to get our challenge
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetMobileUrl(serial) + RESTORE_PATH);
			request.Method = "POST";
			request.ContentType = "application/octet-stream";
			//request.ContentLength = serialBytes.Length;
			Stream requestStream = await request.GetRequestStreamAsync();
			requestStream.Write(serialBytes, 0, serialBytes.Length);
			requestStream.Close();
			byte[] challenge = null;
			try
			{
				using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
				{
					// OK?
					if (response.StatusCode != HttpStatusCode.OK)
					{
						throw new InvalidRestoreResponseException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription));
					}

					// load back the buffer - should only be a byte[32]
					using (MemoryStream ms = new MemoryStream())
					{
						using (Stream bs = response.GetResponseStream())
						{
							byte[] temp = new byte[RESPONSE_BUFFER_SIZE];
							int read;
							while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
							{
								ms.Write(temp, 0, read);
							}
							challenge = ms.ToArray();

							// check it is correct size
							if (challenge.Length != RESTOREINIT_BUFFER_SIZE)
							{
								throw new InvalidRestoreResponseException(string.Format("Invalid response data size (expected 32 got {0})", challenge.Length));
							}
						}
					}
				}
			}
			catch (WebException we)
			{
				int code = (int)((HttpWebResponse)we.Response).StatusCode;
				if (code >= 500 && code < 600)
				{
					throw new InvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", code));
				}
				else
				{
					throw new InvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", code, ((HttpWebResponse)we.Response).StatusDescription));
				}
			}

			// only take the first 10 bytes of the restore code and encode to byte taking count of the missing chars
			byte[] restoreCodeBytes = new byte[10];
			char[] arrayOfChar = restoreCode.ToUpper().ToCharArray();
			for (int i = 0; i < 10; i++)
			{
				restoreCodeBytes[i] = ConvertRestoreCodeCharToByte(arrayOfChar[i]);
			}

			// build the response to the challenge
			HMac hmac = new HMac(new Sha1Digest());
			hmac.Init(new KeyParameter(restoreCodeBytes));
			byte[] hashdata = new byte[serialBytes.Length + challenge.Length];
			Array.Copy(serialBytes, 0, hashdata, 0, serialBytes.Length);
			Array.Copy(challenge, 0, hashdata, serialBytes.Length, challenge.Length);
			hmac.BlockUpdate(hashdata, 0, hashdata.Length);
			byte[] hash = new byte[hmac.GetMacSize()];
			hmac.DoFinal(hash, 0);

			// create a random key
			byte[] oneTimePad = CreateOneTimePad(20);

			// concatanate the hash and key
			byte[] hashkey = new byte[hash.Length + oneTimePad.Length];
			Array.Copy(hash, 0, hashkey, 0, hash.Length);
			Array.Copy(oneTimePad, 0, hashkey, hash.Length, oneTimePad.Length);

			// encrypt the data with BMA public key
			RsaEngine rsa = new RsaEngine();
			rsa.Init(true, new RsaKeyParameters(false, new Org.BouncyCastle.Math.BigInteger(ENROLL_MODULUS, 16), new Org.BouncyCastle.Math.BigInteger(ENROLL_EXPONENT, 16)));
			byte[] encrypted = rsa.ProcessBlock(hashkey, 0, hashkey.Length);

			// prepend the serial to the encrypted data
			byte[] postbytes = new byte[serialBytes.Length + encrypted.Length];
			Array.Copy(serialBytes, 0, postbytes, 0, serialBytes.Length);
			Array.Copy(encrypted, 0, postbytes, serialBytes.Length, encrypted.Length);

			// send the challenge response back to the server
			request = (HttpWebRequest)WebRequest.Create(GetMobileUrl(serial) + RESTOREVALIDATE_PATH);
			request.Method = "POST";
			request.ContentType = "application/octet-stream";
			//request.ContentLength = postbytes.Length;
			requestStream = await request.GetRequestStreamAsync();
			requestStream.Write(postbytes, 0, postbytes.Length);
			requestStream.Close();
			byte[] secretKey = null;
			try
			{
				using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
				{
					// OK?
					if (response.StatusCode != HttpStatusCode.OK)
					{
						throw new InvalidRestoreResponseException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription));
					}

					// load back the buffer - should only be a byte[32]
					using (MemoryStream ms = new MemoryStream())
					{
						using (Stream bs = response.GetResponseStream())
						{
							byte[] temp = new byte[RESPONSE_BUFFER_SIZE];
							int read;
							while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
							{
								ms.Write(temp, 0, read);
							}
							secretKey = ms.ToArray();

							// check it is correct size
							if (secretKey.Length != RESTOREVALIDATE_BUFFER_SIZE)
							{
								throw new InvalidRestoreResponseException(string.Format("Invalid response data size (expected " + RESTOREVALIDATE_BUFFER_SIZE + " got {0})", secretKey.Length));
							}
						}
					}
				}
			}
			catch (WebException we)
			{
				int code = (int)((HttpWebResponse)we.Response).StatusCode;
				if (code >= 500 && code < 600)
				{
					throw new InvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", code));
				}
				else if (code >= 600 && code < 700)
				{
					throw new InvalidRestoreCodeException("Invalid serial number or restore code.");
				}
				else
				{
					throw new InvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", code, ((HttpWebResponse)we.Response).StatusDescription));
				}
			}

			// xor the returned data key with our pad to get the actual secret key
			for (int i = oneTimePad.Length - 1; i >= 0; i--)
			{
				secretKey[i] ^= oneTimePad[i];
			}

			// set the authenticator data
			SecretKey = secretKey;
			if (serial.Length == 14)
			{
				Serial = serial.Substring(0, 2).ToUpper() + "-" + serial.Substring(2, 4) + "-" + serial.Substring(6, 4) + "-" + serial.Substring(10, 4);
			}
			else
			{
				Serial = serial.ToUpper();
			}
			// restore code is ok
			RestoreCodeVerified = true;
			// sync the time
			ServerTimeDiff = 0L;
			await Sync();
		}
Exemple #23
0
		/// <summary>
		/// Enroll the authenticator with the server. We can pass an optional country code from http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
		/// but the server uses GEOIP to determine the region anyway
		/// </summary>
		/// <param name="countryCode">optional 2 letter country code</param>
		public async Task Enroll(string countryCode)
		{
			// generate byte array of data:
			//  00 byte[20] one-time key used to decrypt data when returned;
			//  20 byte[2] country code, e.g. US, GB, FR, KR, etc
			//  22 byte[16] model string for this device;
			//	38 END
			byte[] data = new byte[38];
			byte[] oneTimePad = CreateOneTimePad(20);
			Array.Copy(oneTimePad, data, oneTimePad.Length);
			// add country if we have one
			if (string.IsNullOrEmpty(countryCode) == false)
			{
				byte[] countrydata = Encoding.UTF8.GetBytes(countryCode);
				Array.Copy(countrydata, 0, data, 20, Math.Min(countrydata.Length, 2));
			}
			// add model name
			byte[] model = Encoding.UTF8.GetBytes(GeneralRandomModel());
			Array.Copy(model, 0, data, 22, Math.Min(model.Length, 16));

			// encrypt the data with BMA public key
			RsaEngine rsa = new RsaEngine();
			rsa.Init(true, new RsaKeyParameters(false, new Org.BouncyCastle.Math.BigInteger(ENROLL_MODULUS, 16), new Org.BouncyCastle.Math.BigInteger(ENROLL_EXPONENT, 16)));
			byte[] encrypted = rsa.ProcessBlock(data, 0, data.Length);

			// call the enroll server
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetMobileUrl(countryCode) + ENROLL_PATH);
			request.AllowReadStreamBuffering = true;
			//request.AllowWriteStreamBuffering = true;
			request.AllowReadStreamBuffering = true;
			//request.AllowWriteStreamBuffering = true;
			request.Method = "POST";
			request.ContentType = "application/octet-stream";
			//request.ContentLength = encrypted.Length;
			Stream requestStream = await request.GetRequestStreamAsync();
			requestStream.Write(encrypted, 0, encrypted.Length);
			requestStream.Close();
			byte[] responseData = null;
			using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
			{
				// OK?
				if (response.StatusCode != HttpStatusCode.OK)
				{
					throw new InvalidEnrollResponseException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription));
				}

				// load back the buffer - should only be a byte[45]
				using (MemoryStream ms = new MemoryStream())
				{
					//using (BufferedStream bs = new BufferedStream(response.GetResponseStream()))
					using (Stream bs = response.GetResponseStream())
					{
						byte[] temp = new byte[RESPONSE_BUFFER_SIZE];
						int read;
						while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
						{
							ms.Write(temp, 0, read);
						}
						responseData = ms.ToArray();

						// check it is correct size
						if (responseData.Length != ENROLL_RESPONSE_SIZE)
						{
							throw new InvalidEnrollResponseException(string.Format("Invalid response data size (expected 45 got {0})", responseData.Length));
						}
					}
				}
			}

			// return data:
			// 00-07 server time (Big Endian)
			// 08-24 serial number (17)
			// 25-44 secret key encrpyted with our pad
			// 45 END

			// extract the server time
			byte[] serverTime = new byte[8];
			Array.Copy(responseData, serverTime, 8);
			if (BitConverter.IsLittleEndian == true)
			{
				Array.Reverse(serverTime);
			}
			// get the difference between the server time and our current time
			ServerTimeDiff = BitConverter.ToInt64(serverTime, 0) - CurrentTime;

			// get the secret key
			byte[] secretKey = new byte[20];
			Array.Copy(responseData, 25, secretKey, 0, 20);
			// decrypt the initdata with a simple xor with our key
			for (int i = oneTimePad.Length - 1; i >= 0; i--)
			{
				secretKey[i] ^= oneTimePad[i];
			}
			SecretKey = secretKey;

			// get the serial number
			Serial = Encoding.UTF8.GetString(responseData, 8, 17);
		}
Exemple #24
0
        public virtual void DoTest7()
        {
            byte[] salt = new byte[0];
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6);
            ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - PSS Signing
            //
            Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new Sha1Digest(), 0, false);

            eng.Init(true, sigParameters);

            eng.Update(msg7[0]);
            eng.BlockUpdate(msg7, 1, msg7.Length - 1);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig7, 0, data))
            {
                Fail("failed ISO9796-2 generation Test 7");
            }

            eng.Update(msg7[0]);
            eng.BlockUpdate(msg7, 1, msg7.Length - 1);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 7");
            }

            if (!IsSameAs(msg7, 0, eng.GetRecoveredMessage()))
            {
                Fail("failed ISO9796-2 recovery Test 7");
            }
        }
        public static byte[] RsaDecrypt(string b64_private_key, byte [] cipher_text)
        {
            // Extracting the private key from the pair
            RsaKeyParameters privateKey = decodeUserKeyPairPrivate(b64_private_key);

            // Creating the RSA algorithm object
            IAsymmetricBlockCipher cipher = new RsaEngine();
            cipher.Init(false, privateKey);
            byte[] plain_text = cipher.ProcessBlock(cipher_text, 0, cipher_text.Length);

            return plain_text;
        }
Exemple #26
0
        public virtual void DoTest8()
        {
            byte[] salt = Hex.Decode("78E293203CBA1B7F92F05F4D171FF8CA3E738FF8");
            RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6);
            RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6);
            ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt);
            RsaEngine rsa = new RsaEngine();
            byte[] data;

            //
            // ISO 9796-2 - PSS Signing
            //
            Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, false);

            eng.Init(true, sigParameters);

            eng.Update(msg8[0]);
            eng.BlockUpdate(msg8, 1, msg8.Length - 1);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            if (!IsSameAs(sig8, 0, data))
            {
                Fail("failed ISO9796-2 generation Test 8");
            }

            eng.Update(msg8[0]);
            eng.BlockUpdate(msg8, 1, msg8.Length - 1);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 8");
            }
        }
Exemple #27
0
        private static void RsaKeyGeneratorTest()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);
            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和私钥
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }
            savetheKey(publicKey, privateKey);

            //一个测试……………………
            //输入,十六进制的字符串,解码为byte[]
            //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
            //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
            string input = "popozh RSA test";
            byte[] testData = Encoding.UTF8.GetBytes(input);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();
            //公钥加密
            //从保存在本地的磁盘文件中读取公钥
            Asn1Object aobject = Asn1Object.FromStream(new FileStream(pubKeyFile, FileMode.Open, FileAccess.Read));  //a.puk??
            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.GetInstance(aobject);
            AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            FileStream fs;
            engine.Init(true, testpublicKey);
            try
            {
                //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
                testData = engine.ProcessBlock(testData, 0, testData.Length);
                Console.WriteLine("加密完成!" + Environment.NewLine);
                fs = new FileStream(ecyFile, FileMode.Create, FileAccess.Write);
                fs.Write(testData, 0, testData.Length);
                fs.Close();
                Console.WriteLine("保存密文成功" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
            }
            //私钥解密
            //获取加密的私钥,进行解密,获得私钥
            fs = new FileStream(ecyFile, FileMode.Open, FileAccess.Read);
            byte[] anothertestdata = new byte[1024];
            fs.Read(anothertestdata, 0, anothertestdata.Length);
            fs.Close();
            Asn1Object aobj = Asn1Object.FromStream(new FileStream(priKeyFile, FileMode.Open, FileAccess.Read));   //a.pvk??
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);
            char[] password = "******".ToCharArray();
            PrivateKeyInfo priKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri);    //解密
            AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);    //私钥
            engine.Init(false, anotherprivateKey);
            try
            {
                anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
                Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine("failed - exception " + e.ToString());
            }

            Console.Read();
        }
Exemple #28
0
        public virtual void DoTest10()
        {
            BigInteger          mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16);
            BigInteger          pubExp = new BigInteger("65537", 10);
            BigInteger          priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16);
            RsaKeyParameters    pubParameters = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters    privParameters = new RsaKeyParameters(true, mod, priExp);
            RsaEngine           rsa = new RsaEngine();
            byte[]              data;

            //
            // ISO 9796-2 - PSS Signing
            //
            IDigest              dig = new Sha1Digest();
            Iso9796d2PssSigner  eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize());

            //
            // as the padding is random this test needs to repeat a few times to
            // make sure
            //
            for (int i = 0; i != 500; i++)
            {
                eng.Init(true, privParameters);

                eng.Update(msg9[0]);
                eng.BlockUpdate(msg9, 1, msg9.Length - 1);

                data = eng.GenerateSignature();

                eng.Init(false, pubParameters);

                eng.Update(msg9[0]);
                eng.BlockUpdate(msg9, 1, msg9.Length - 1);

                if (!eng.VerifySignature(data))
                {
                    Fail("failed ISO9796-2 verify Test 10");
                }
            }
        }
Exemple #29
0
		private void testSig(
			int                 id,
			RsaKeyParameters    pub,
			RsaKeyParameters    prv,
			byte[]              slt,
			byte[]              msg,
			byte[]              sig)
		{
			RsaBlindingFactorGenerator blindFactorGen = new RsaBlindingFactorGenerator();
			RsaBlindingEngine blindingEngine = new RsaBlindingEngine();
			PssSigner blindSigner = new PssSigner(blindingEngine, new Sha1Digest(), 20);
			PssSigner signer = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);

			blindFactorGen.Init(pub);

			BigInteger blindFactor = blindFactorGen.GenerateBlindingFactor();
			RsaBlindingParameters parameters = new RsaBlindingParameters(pub, blindFactor);

			// generate a blind signature
			blindSigner.Init(true, new ParametersWithRandom(parameters, new FixedRandom(slt)));

			blindSigner.BlockUpdate(msg, 0, msg.Length);

			byte[] blindedData = blindSigner.GenerateSignature();

			RsaEngine signerEngine = new RsaEngine();

			signerEngine.Init(true, prv);

			byte[] blindedSig = signerEngine.ProcessBlock(blindedData, 0, blindedData.Length);

			// unblind the signature
			blindingEngine.Init(false, parameters);

			byte[] s = blindingEngine.ProcessBlock(blindedSig, 0, blindedSig.Length);

			//signature verification
			if (!AreEqual(s, sig))
			{
				Fail("test " + id + " failed generation");
			}
	        
			//verify signature with PssSigner
			signer.Init(false, pub);
			signer.BlockUpdate(msg, 0, msg.Length);

			if (!signer.VerifySignature(s))
			{
        		Fail("test " + id + " failed PssSigner verification");
			}
		}
Exemple #30
0
		private bool isProcessingOkay(
			RsaKeyParameters    pub,
			RsaKeyParameters    prv,
			byte[]              data,
			SecureRandom        random)
		{
			RsaBlindingFactorGenerator blindFactorGen = new RsaBlindingFactorGenerator();
			RsaBlindingEngine blindingEngine = new RsaBlindingEngine();
			PssSigner blindSigner = new PssSigner(blindingEngine, new Sha1Digest(), 20);
			PssSigner pssEng = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);

			random.NextBytes(data);

			blindFactorGen.Init(pub);

			BigInteger blindFactor = blindFactorGen.GenerateBlindingFactor();
			RsaBlindingParameters parameters = new RsaBlindingParameters(pub, blindFactor);

			// generate a blind signature
			blindSigner.Init(true, new ParametersWithRandom(parameters, random));

			blindSigner.BlockUpdate(data, 0, data.Length);

			byte[] blindedData = blindSigner.GenerateSignature();

			RsaEngine signerEngine = new RsaEngine();

			signerEngine.Init(true, prv);

			byte[] blindedSig = signerEngine.ProcessBlock(blindedData, 0, blindedData.Length);

			// unblind the signature
			blindingEngine.Init(false, parameters);

			byte[] s = blindingEngine.ProcessBlock(blindedSig, 0, blindedSig.Length);

			//verify signature with PssSigner
			pssEng.Init(false, pub);
			pssEng.BlockUpdate(data, 0, data.Length);

			return pssEng.VerifySignature(s);
		}
        public static byte[] RsaEncrypt(string b64_public_key, byte[] plain_text)
        {
            RsaKeyParameters publicKey = decodeUserKeyPairPublic (b64_public_key);

            // 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[] encryptedBytes = cipher.ProcessBlock(plain_text, 0, plain_text.Length);

            return encryptedBytes;
        }
Exemple #32
0
 private RSA(string privPem)
 {
     key = (new PemReader(new StringReader(privPem.Trim())).ReadObject() as AsymmetricCipherKeyPair).Private;
     engine = new RsaEngine();
     engine.Init(true, key);
 }
Exemple #33
0
        private static RsaEngine GetRsaEngine(byte[] key)
        {
            //Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey()
            var rsaPrivateKey = (Asn1Sequence)new Asn1InputStream(key).ReadObject();

            //http://tools.ietf.org/html/rfc3447#page-60
            //version = rsaPrivateKey[0]
            BigInteger n = ((DerInteger)rsaPrivateKey[1]).Value;
            BigInteger e = ((DerInteger)rsaPrivateKey[2]).Value;
            BigInteger d = ((DerInteger)rsaPrivateKey[3]).Value;
            BigInteger p = ((DerInteger)rsaPrivateKey[4]).Value;
            BigInteger q = ((DerInteger)rsaPrivateKey[5]).Value;
            BigInteger dP = ((DerInteger)rsaPrivateKey[6]).Value;
            BigInteger dQ = ((DerInteger)rsaPrivateKey[7]).Value;
            BigInteger qInv = ((DerInteger)rsaPrivateKey[8]).Value;
            var rsa = new RsaEngine();
            rsa.Init(false, new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
            return rsa;
        }