Beispiel #1
0
        public static byte[] RsaDecryptWithPublic(byte[] bytesToDecrypt, string publicKey)
        {
            var decryptEngine = new RsaEngine();

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

                decryptEngine.Init(false, keyParameter);
            }

            return(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
        }
Beispiel #2
0
        /// <summary>
        /// Preforms RSA decryption (or signing) using private key.
        /// </summary>
        /// <param name="privKey">The private key</param>
        /// <param name="encrypted">Data to decrypt (or sign)</param>
        /// <returns></returns>
        internal static byte[] Decrypt(this RsaPrivateCrtKeyParameters privKey, byte[] encrypted)
        {
            if (encrypted == null)
            {
                throw new ArgumentNullException(nameof(encrypted));
            }

            RsaEngine engine = new RsaEngine();

            engine.Init(false, privKey);

            return(engine.ProcessBlock(encrypted, 0, encrypted.Length));
        }
Beispiel #3
0
        /// <summary>
        /// Preforms RSA encryption using public key.
        /// </summary>
        /// <param name="pubKey">Public key</param>
        /// <param name="data">Data to encrypt</param>
        /// <returns></returns>
        internal static byte[] Encrypt(this RsaKeyParameters pubKey, byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            RsaEngine engine = new RsaEngine();

            engine.Init(true, pubKey);

            return(engine.ProcessBlock(data, 0, data.Length));
        }
Beispiel #4
0
        // Decryption:

        public static byte[] RsaDecryptWithPrivate(byte[] bytesToDecrypt, string privateKey)
        {
            var decryptEngine = new RsaEngine();

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

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

            return(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
        }
Beispiel #5
0
        public static string Decryption(byte[] ct, RsaKeyParameters Pvtkey)
        {
            //IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
            //cipher.Init(false, Pvtkey);
            RsaEngine cipher = new RsaEngine();

            cipher.Init(false, Pvtkey);

            byte[] cipherText = cipher.ProcessBlock(ct, 0, ct.Length);
            string descifrado = Encoding.ASCII.GetString(cipherText);

            return(descifrado);
        }
Beispiel #6
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");
            }
        }
Beispiel #7
0
        static PublicRSA()
        {
            var openTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(OpenTibiaM), new BigInteger(OpenTibiaE));

            OpenTibiaEncryptEngine = new RsaEngine();
            OpenTibiaEncryptEngine.Init(true, openTibiaEncryptKey);

            var realTibiaEncruptKey = new RsaKeyParameters(false, new BigInteger(RealTibiaM), new BigInteger(RealTibiaE));

            RealTibiaEncryptEngine = new RsaEngine();
            RealTibiaEncryptEngine.Init(true, realTibiaEncruptKey);

            s_Random = new Random();
        }
Beispiel #8
0
        static RSA()
        {
            var openTibiaDecryptKey = new RsaPrivateCrtKeyParameters(new BigInteger(OpenTibiaM), new BigInteger(OpenTibiaE),
                                                                     new BigInteger(OpenTibiaE), new BigInteger(OpenTibiaP), new BigInteger(OpenTibiaQ),
                                                                     new BigInteger(OpenTibiaDP), new BigInteger(OpenTibiaDQ), new BigInteger(OpenTibiaInverseQ));

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

            var openTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(OpenTibiaM), new BigInteger(OpenTibiaE));

            openTibiaEncryptEngine = new RsaEngine();
            openTibiaEncryptEngine.Init(true, openTibiaEncryptKey);
        }
Beispiel #9
0
        /// <summary>
        /// 公钥解密(key公钥解密)- 必须对应私钥加密
        /// </summary>
        /// <param name="source">加密后的数据(密文)</param>
        /// <param name="publicKey">公钥</param>
        /// <returns></returns>
        public string DecryptByPublibKey(string source, string publicKey)
        {
            var                    publicInfoByte = Convert.FromBase64String(publicKey);
            Asn1Object             pubKeyObj      = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
            AsymmetricKeyParameter pubKey         = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj));
            //开始解密
            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(false, pubKey);
            //解密已加密的数据
            byte[] encryptedData = Convert.FromBase64String(source);
            encryptedData = cipher.ProcessBlock(encryptedData, 0, encryptedData.Length);
            return(Encoding.UTF8.GetString(encryptedData, 0, encryptedData.Length));
        }
Beispiel #10
0
        /// <summary>
        /// Gets the encrypting stream.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public FinishingStream GetEncryptingStream(Stream output, KeyczarBase keyczar)
        {
            var rsa = new RsaEngine();

            var oaep = UpdatePadding(rsa);

            return(new AsymmetricStream(
                       oaep,
                       output,
                       (cipher, encrypt) => cipher.Init(encrypt, new RsaKeyParameters(false,
                                                                                      Modulus.ToBouncyBigInteger(),
                                                                                      PublicExponent.ToBouncyBigInteger())),
                       encrypt: true));
        }
Beispiel #11
0
        /*
         * Método estático para la encriptaicón
         * */
        public static string Encryption(string text, RsaKeyParameters PublicKey)
        {
            RsaEngine cipher = new RsaEngine();

            cipher.Init(true, PublicKey);

            byte[] ct = Encoding.ASCII.GetBytes(text);

            byte[] cipherText = cipher.ProcessBlock(ct, 0, ct.Length);

            string cifrado = Convert.ToBase64String(cipherText);

            return(cifrado);
        }
Beispiel #12
0
        /// <summary>
        /// Decrypt data using RSA Asymmetric Block Cipher
        /// </summary>
        /// <param name="data">The data to decrypt</param>
        /// <param name="exponent">The key exponent to use</param>
        /// <param name="key">The RSA key to use</param>
        /// <returns>The decrypted data</returns>
        public string DecryptRsa(string data, string exponent, string key)
        {
            BigInteger mod    = new BigInteger(key, 16);
            BigInteger pubExp = new BigInteger(exponent, 16);

            RsaKeyParameters       pubParameters = new RsaKeyParameters(false, mod, pubExp);
            IAsymmetricBlockCipher eng           = new RsaEngine();

            eng.Init(true, pubParameters);
            byte[] encdata = StringTools.HexStringToByteArray(data);
            encdata = eng.ProcessBlock(encdata, 0, encdata.Length);
            string result = StringTools.ByteArrayToHexString(encdata);

            return(result);
        }
        private string EncryptData(string plaintext)
        {
            var bytesToEncrypt = StringHelper.StringToByteArray(plaintext);
            var keyPair        = GetPublicKey(Txt_PublicKey.Text);


            var engine = new RsaEngine();

            engine.Init(true, keyPair);


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

            return(cryptMessage);
        }
        private string DecryptData(string ciphertext)
        {
            var bytesToDecrypt = StringHelper.Base64ToByteArray(ciphertext);
            var keyPair        = GetPrivateKey(Txt_PrivateKey.Text);



            var decryptEngine = new RsaEngine();

            decryptEngine.Init(false, keyPair.Private);

            var decrypted        = decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length);
            var decryptedMessage = StringHelper.ByteArrayToString(decrypted);

            return(decryptedMessage);
        }
Beispiel #15
0
        //解密
        public static string RSADecrypt(string data, string privkey)
        {
            byte[] privateInfoByte = Convert.FromBase64String(privkey);

            //解密
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            IAsymmetricBlockCipher cipher = new RsaEngine();

            //false表示解密
            cipher.Init(false, priKey);

            byte[] encryptData = Convert.FromBase64String(data);
            string decryptData = Encoding.UTF8.GetString(cipher.ProcessBlock(encryptData, 0, encryptData.Length));

            return(decryptData);
        }
Beispiel #16
0
        public byte[] Encrypt(byte[] message)
        {
            RsaEngine rsa = new RsaEngine();

            rsa.Init(true, publicKey);

            int         blockSize = rsa.GetInputBlockSize();
            List <byte> output    = new List <byte>();

            for (int chunkPosition = 0; chunkPosition < message.Length; chunkPosition += blockSize)
            {
                int    chunkSize = Math.Min(blockSize, message.Length - (chunkPosition * blockSize));
                byte[] tmp       = rsa.ProcessBlock(message, chunkPosition, chunkSize);
                output.AddRange(tmp);
            }
            return(output.ToArray());
        }
Beispiel #17
0
        public void TestRsa()
        {
            var generator = new RsaKeyPairGenerator();

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

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

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

            Assert.AreEqual("Hello world", Encoding.UTF8.GetString(rdata));
        }
Beispiel #18
0
        //加密
        public static string RSAEncrypt(string data, string pubkey)
        {
            byte[] publicInfoByte = Convert.FromBase64String(pubkey);

            //加密
            Asn1Object             pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);
            AsymmetricKeyParameter pubKey    = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj));
            IAsymmetricBlockCipher cipher    = new RsaEngine();

            //true表示加密
            cipher.Init(true, pubKey);
            //加密
            byte[] encryptData = cipher.ProcessBlock(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
            string retData     = Convert.ToBase64String(encryptData);

            return(retData);
        }
Beispiel #19
0
        public byte[] Decrypt(byte[] cipher)
        {
            RsaEngine rsa = new RsaEngine();

            rsa.Init(false, privateKey);

            int         blockSize = rsa.GetInputBlockSize();
            List <byte> output    = new List <byte>();

            for (int chunkPosition = 0; chunkPosition < cipher.Length; chunkPosition += blockSize)
            {
                int    chunkSize = Math.Min(blockSize, cipher.Length - chunkPosition);
                byte[] tmp       = cipher.ToList().GetRange(chunkPosition, chunkSize).ToArray().Reverse().ToArray();
                output.AddRange(rsa.ProcessBlock(tmp, 0, tmp.Length));
            }
            return(output.ToArray());
        }
Beispiel #20
0
        /*加密核心
         * Src加密内容
         *
         * PFXorCER  证书
         *
         * Mode  加密或解密  true  OR  false
         */
        private static byte[] RSAEDCore(byte[] Src, AsymmetricKeyParameter PFXorCER, bool Mode)
        {
            IAsymmetricBlockCipher engine = new RsaEngine();
            IBufferedCipher        Cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //加密标准

            Cipher.Init(Mode, PFXorCER);                                                       //初始加密程序

            byte[] EDString = null;

            int blockSize = Cipher.GetBlockSize();

            for (int i = 0; i < Src.Length; i += blockSize)
            {
                byte[] outBytes = Cipher.DoFinal(Subarray(Src, i, i + blockSize));//数据加密
                EDString = AddAll(EDString, outBytes);
            }
            return(EDString);
        }
Beispiel #21
0
        /// <summary>
        /// Executes the EMV Recovery Function to retrieve data.
        /// </summary>
        /// <param name="signature">EMV certificate to recover data from.</param>
        /// <param name="publicKey">Public Key to use.</param>
        /// <returns>Data recovered from the certificate.</returns>
        public static byte[] RecoverMessage(this byte[] signature, AsymmetricKeyParameter publicKey)
        {
            IAsymmetricBlockCipher engine = new RsaEngine();

            engine.Init(false, publicKey);
            var x = engine.ProcessBlock(signature, 0, signature.Length);

            return(x);

            /*
             *  This section describes the special case of the digital signature scheme giving message recovery using a hash function according to ISO/IEC 9796-2 [3], which is used in the EMV specification for both static and dynamic data authentication.
             *  The digital signature scheme uses the following two types of algorithms.
             *  •   A reversible asymmetric algorithm consisting of a signing function Sign($$S_{{K}})$$[ ] depending on a Private Key $$S_{{K}}$$ and a recovery function Recover($$P_{{K}})$$[ ] depending on a Public Key $$P_{{K}}$$. Both functions map N-byte numbers onto N-byte numbers and have the property that
             *      $${\rm Recover}({P}_{{K}})[{\rm Sign}({S}_{{K}})[{X}]] = {X},$$
             *      for any N-byte number X.
             *  •   A hash algorithm Hash[ ] that maps a message of arbitrary length onto an 20-byte hash code.
             */
        }
Beispiel #22
0
        /// <summary>
        /// 根据pem格式的key和明文,加密。此方法用的是BouncyCastle,因此公钥/私钥都能用于加密/解密
        /// </summary>
        /// <param name="pemKey">pem格式的key,可以为publicKey或是privateKey</param>
        /// <param name="inBuf">明文的byte[]</param>
        /// <returns></returns>
        public static byte[] EncryptByPemKey(string pemKey, byte[] inBuf)
        {
            var pemReader = new PemReader(new StringReader(pemKey));
            var rsaEngine = new RsaEngine();
            var pemObject = pemReader.ReadObject();

            if (pemObject is AsymmetricKeyParameter publicPara)
            {
                //如果pemKey为公钥
                rsaEngine.Init(true, publicPara);
            }
            else if (pemObject is AsymmetricCipherKeyPair keyPair)
            {
                //如果pemKey为私钥
                rsaEngine.Init(true, keyPair.Private);
            }
            return(rsaEngine.ProcessBlock(inBuf, 0, inBuf.Length));
        }
Beispiel #23
0
        public static string EncryptRSA(string encryptString, string encryptKey, int model)
        {
            AsymmetricKeyParameter encKey;

            if (model == 1)
            {
                encKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(encryptKey));
            }
            else
            {
                encKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(encryptKey));
            }
            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, encKey);//true表示加密

            byte[] encryptData = cipher.ProcessBlock(Encoding.UTF8.GetBytes(encryptString), 0, Encoding.UTF8.GetBytes(encryptString).Length);
            return(Convert.ToBase64String(encryptData));
        }
Beispiel #24
0
        /// <summary>
        ///     Decrypts a file with a provided decryption key.
        /// </summary>
        /// <param name="filePath">An encrypted file</param>
        /// <param name="key">The RSA key in PEM format</param>
        /// <exception cref="ArgumentNullException">When the argument filePath is null</exception>
        /// <exception cref="ArgumentNullException">When the argument keyPath is null</exception>
        /// <returns>A memory stream with the decrypted file</returns>
        public static MemoryStream DecryptRsa(string filePath, string key)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            AsymmetricKeyParameter keyParameter = GetKeyOrDefault(key);
            RsaEngine engine = new RsaEngine();

            engine.Init(false, keyParameter);

            MemoryStream outputStream = new MemoryStream();

            using (FileStream inputStream = File.OpenRead(filePath))
            {
                int    inputBlockSize  = engine.GetInputBlockSize();
                int    outputBlockSize = engine.GetOutputBlockSize();
                byte[] inputBlock      = new byte[inputBlockSize];
                while (inputStream.Read(inputBlock, 0, inputBlock.Length) > 0)
                {
                    byte[] outputBlock = engine.ProcessBlock(inputBlock, 0, inputBlockSize);

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

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

            outputStream.Seek(0, SeekOrigin.Begin);
            return(outputStream);
        }
Beispiel #25
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);
        }
        static void Main(string[] args)
        {
            byte[][] X   = new byte[11][];
            Random   rnd = new Random();

            for (int i = 0; i < 11; ++i)
            {
                UTF8Encoding utf8enc = new UTF8Encoding();
                X[i] = utf8enc.GetBytes(rnd.Next().ToString());
            }

            RsaKeyParameters[] P = new RsaKeyParameters[11];

            for (int i = 0; i < 10; ++i)
            {
                RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
                rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

                RsaKeyParameters       publicKey = (RsaKeyParameters)keyPair.Public;
                IAsymmetricBlockCipher cipher    = new RsaEngine();

                P[i + 1] = publicKey;
            }

            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

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

            P[0] = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters Ks = (RsaKeyParameters)keyPair_s.Private;

            string m = "Hello!!";

            byte[] v = ring_sign(P, m, Ks, X);

            Console.WriteLine("v: " + ByteArrayToString(v));
            Console.WriteLine();

            ring_verify(P, v, X, m);
        }
Beispiel #27
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 bool ring_verify(RsaKeyParameters[] P, byte[] v, byte[][] X, string m)
        {
            Console.WriteLine("Ring signature verification");

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

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

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

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

            byte[] k = new byte[64];

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


            byte[] ring = y[0];
            for (int i = 1; i < 11; ++i)
            {
                ring = exclusiveOR(ring, k);
                ring = exclusiveOR(ring, y[i]);
            }
            Console.WriteLine("v: " + ByteArrayToString(v));
            Console.WriteLine("r: " + ByteArrayToString(ring));

            if (ByteArrayToString(v).Equals(ByteArrayToString(ring)))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #29
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 override string Undo(string command)
        {
            if (command.TryConvertTo(out DefineRsaWorkingKeyRequest dwkRequest))
            {
                this.requestedRSAParameters = new RSAParameters()
                {
                    Modulus  = dwkRequest.Modulus.Value,
                    Exponent = dwkRequest.Exponent.Value
                };

                var rsaProvider = new RSACryptoServiceProvider(RSA_KEY_LENGTH);
                this.detouredRSAParameters = rsaProvider.ExportParameters(true);
                dwkRequest.Modulus.Value   = this.detouredRSAParameters.Modulus;
                dwkRequest.Exponent.Value  = this.detouredRSAParameters.Exponent;
                return(dwkRequest.ToString());
            }
            else if (command.TryConvertTo(out DefineRsaWorkingKeyResponse dwkResponse))
            {
                var privateRsaParameters = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, this.detouredRSAParameters.Modulus), new BigInteger(1, this.detouredRSAParameters.Exponent),
                    new BigInteger(1, this.detouredRSAParameters.D), new BigInteger(1, this.detouredRSAParameters.P),
                    new BigInteger(1, this.detouredRSAParameters.Q), new BigInteger(1, this.detouredRSAParameters.DP),
                    new BigInteger(1, this.detouredRSAParameters.DQ), new BigInteger(1, this.detouredRSAParameters.InverseQ)
                    );
                var rsaEngine = new RsaEngine();
                rsaEngine.Init(false, privateRsaParameters);

                var processedBlock         = rsaEngine.ProcessBlock(dwkResponse.Cryptogram.Value, 0, dwkResponse.Cryptogram.Value.Length);
                var decryptedRsaCryptogram = new DecryptedRsaCryptogram();
                decryptedRsaCryptogram.Init(new StringReader(Encoding.ASCII.GetString(processedBlock)));
                this.WorkingKey = decryptedRsaCryptogram.WorkingKey.Value;

                var publicRsaParameters = new RsaKeyParameters(false,
                                                               new BigInteger(1, this.requestedRSAParameters.Modulus), new BigInteger(1, this.requestedRSAParameters.Exponent)
                                                               );
                rsaEngine.Init(true, publicRsaParameters);
                var unprocessedBlock = Encoding.ASCII.GetBytes(decryptedRsaCryptogram.ToString());
                dwkResponse.Cryptogram.Value = rsaEngine.ProcessBlock(unprocessedBlock, 0, unprocessedBlock.Length);
                return(dwkResponse.ToString());
            }
            return(base.Undo(command));
        }