Init() публичный Метод

public Init ( bool forEncryption, ICipherParameters parameters ) : void
forEncryption bool
parameters ICipherParameters
Результат void
Пример #1
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;
		}
Пример #2
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);
    }
Пример #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);
    }
Пример #4
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();
        }
Пример #5
0
        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);
        }
Пример #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);
            }
        }
Пример #7
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);
        }
Пример #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);
    }
Пример #9
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);
            }
        }
Пример #10
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);
		}
Пример #11
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");
			}
		}
Пример #12
0
 private RSA(string privPem)
 {
     key = (new PemReader(new StringReader(privPem.Trim())).ReadObject() as AsymmetricCipherKeyPair).Private;
     engine = new RsaEngine();
     engine.Init(true, key);
 }
Пример #13
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();
		}
Пример #14
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);
		}
Пример #15
0
        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
            }
        }
Пример #16
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;
        }
Пример #17
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);
            }
        }
Пример #18
0
        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;
        }
Пример #19
0
        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;
        }
        /// <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);
        }
Пример #21
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);
                }
            }
        }
Пример #22
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();
        }
Пример #23
0
        private static byte[] EncryptRSAPayload(byte[] payload)
        {
            //! NOTE: I am using BouncyCastle/RSAEngine due to the fact that RSACryptoServiceProvider will
            //        not let you encrypt without padding.

            RsaEngine rsaCryptoProvider = new RsaEngine();
            rsaCryptoProvider.Init(true, new RsaKeyParameters(false, new BouncyCastleBigInteger(ENROLL_RSA_MODULUS, 16), new BouncyCastleBigInteger(ENROLL_RSA_EXPONENT, 16)));
            return rsaCryptoProvider.ProcessBlock(payload, 0, payload.Length);
        }