Esempio n. 1
0
        public static byte[] DecryptTitleKey(byte[] titleKeyblock, RSAParameters rsaParams)
        {
            RSA rsa = RSA.Create();

            rsa.ImportParameters(rsaParams);
            return(rsa.Decrypt(titleKeyblock, RSAEncryptionPadding.OaepSHA256));
        }
Esempio n. 2
0
        private static void TestRSAFromFile()
        {
            try
            {
                byte[] originalValue = new byte[256];
                new System.Random().NextBytes(originalValue);

                for (int i = 0; i < 4; i++)
                {
                    DataProtector.DataProtectionScope scope = (i < 2 ? DataProtector.DataProtectionScope.CurrentUser : DataProtector.DataProtectionScope.LocalMachine);
                    RSA    rsa       = DataProtector.RSAFromFile(scope);
                    byte[] encrypted = rsa.Encrypt(originalValue, RSAEncryptionPadding.Pkcs1);
                    byte[] decrypted = rsa.Decrypt(encrypted, RSAEncryptionPadding.Pkcs1);
                    if (!originalValue.SequenceEqual(decrypted))
                    {
                        throw new InvalidDataException("TestRSAFromFile failure, original value not equal to decrypted value, scope: " + scope);
                    }
                }

                Console.WriteLine("TestRSAFromFile OK");
            }
            catch (Exception ex)
            {
                Console.WriteLine("TestRSAFromFile failed: {0}", ex);
            }
        }
Esempio n. 3
0
        private void DecryptButton_Click(object sender, EventArgs e)
        {
            if (EncryptedText.TextLength < 1)
            {
                return;
            }

            switch (AlgorithmSelect.SelectedIndex)
            {
            case 0:
                var caesar = new Caesar((int)caesarShift.Value, string25Key.Text);
                NormalText.Text = caesar.Decrypt(EncryptedText.Text);
                break;

            case 1:
                var playfaire = new Playfair(string25Key.Text);
                NormalText.Text = playfaire.Decrypt(EncryptedText.Text);
                break;

            case 2:
                var rsa = new RSA(rsaPublicText.Text, rsaPrivateText.Text);
                NormalText.Text = rsa.Decrypt(EncryptedText.Text);
                break;


            default:
                break;
            }
        }
Esempio n. 4
0
        public void decript()
        {
            RSA client = new RSA();

            string pub = @"-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKLL1U7AQdefJTr+fAFzC8IRoTqTasPY
RdDPZfGncEGyNXYdEwnXXDlWRldxCRY9d/tfTCqxzWo2BrIdq2gxmSMCAwEAAQ==
-----END PUBLIC KEY-----";

            string priv = @"-----BEGIN RSA PRIVATE KEY-----
MIIBPQIBAAJBAPB5AN8Qlhi/WqVX08TR/k06C5eoBGo6SuDdG1UxhhIiyZ6g5a5G
PpXH5cB587ZDNiMh+AX++9iQ5TvCmHJwfzkCAwEAAQJBAKyt559G1NG+j0QOFmbO
eLNSDEMCBvGVHHHutJLvthvMdOwYUtZ1qEKf1en3wcEybQ1ONmsvWSGWVHVk4zAp
q/UCIQD2OcXLcsoot5iKq02KY8o9MWMDZlLIkbeWTXB971RqAwIhAPoExE4KrTU3
NLjOIdUmK5XRNvwwMRSsTvx0eVIr34sTAiEAnVpKVzwiiWbbKzNSOHCRXA3lstR/
bwIAiyMuEq0SCzUCIQDAII2h0z6LWGMhaPZCz9RKir2QSpBM7KS+B9t7M8/TFQIh
AK5WOa2Ejo/nKGY+DGcmfT78NmFdtGNZpR7lauiqT258
-----END RSA PRIVATE KEY-----";

            string textToDecript = @"7cdc07ed48b36b2ba7006672c82d1f8ad6c680b1c128f172cc17005aeb9b3d97972ead7e8020a0674052dadf239e47dbbd9cf0c5fd28023959c21981a306cefa";

            client.setPrivateKey(priv);
            client.setPublicKey(pub);
            //System.Security.Cryptography.RSACryptoServiceProvider privateKey = RSAPemParser.ImportPrivateKey(priv);

            var bytesPlainTextData = client.Decrypt(HexaToByteArray(textToDecript));
            var plainTextData      = System.Text.Encoding.UTF8.GetString(bytesPlainTextData);

            Console.WriteLine(plainTextData);
        }
Esempio n. 5
0
        public static void LargeKeyCryptRoundtrip()
        {
            byte[] output;

            using (RSA rsa = RSAFactory.Create())
            {
                try
                {
                    rsa.ImportParameters(TestData.RSA16384Params);
                }
                catch (CryptographicException)
                {
                    // The key is pretty big, perhaps it was refused.
                    return;
                }

                byte[] crypt = rsa.Encrypt(TestData.HelloBytes, RSAEncryptionPadding.OaepSHA1);

                Assert.Equal(rsa.KeySize, crypt.Length * 8);

                output = rsa.Decrypt(crypt, RSAEncryptionPadding.OaepSHA1);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
Esempio n. 6
0
        private static string Decryptv2(Func <string, X509Certificate2> certResolver, MemoryStream inputStream, BinaryReader reader)
        {
            int    version    = 2;
            string thumbprint = ToHexString(reader.ReadBytes(20), 0, 20);

            X509Certificate2 cert = certResolver(thumbprint);

            int encryptedKeyLength = reader.ReadInt32();
            int nonceLength        = reader.ReadInt32();
            int tagLength          = reader.ReadInt32();

            byte[] encryptedKey = reader.ReadBytes(encryptedKeyLength);
            byte[] nonce        = reader.ReadBytes(nonceLength);
            byte[] tag          = reader.ReadBytes(tagLength);

            RSA privateKey = cert.GetRSAPrivateKey();

            byte[] decryptedKey = privateKey.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA512);

            int remainingBytes = (int)(inputStream.Length - inputStream.Position);

            byte[] encryptedData  = reader.ReadBytes(remainingBytes);
            byte[] decryptedData  = new byte[remainingBytes];
            byte[] additionalData = new byte[] { Convert.ToByte(version) };

            using (AesGcm aes = new AesGcm(decryptedKey))
            {
                aes.Decrypt(nonce, encryptedData, tag, decryptedData, additionalData);
            }

            return(Encoding.UTF8.GetString(decryptedData));
        }
        public void RSATestNewDec4()
        {
            RSA algorithm = new RSA();
            int plain     = algorithm.Decrypt(257, 337, 12448, 17);

            Assert.AreEqual(plain, 18537);
        }
Esempio n. 8
0
        public string Decrypt(string cipherText)
        {
            var cipherBytes    = Convert.FromBase64String(cipherText);
            var plainTextBytes = _rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);

            return(Encoding.UTF8.GetString(plainTextBytes));
        }
        public void RSATestDec2()
        {
            RSA algorithm = new RSA();
            int plain     = algorithm.Decrypt(13, 19, 221, 5);

            Assert.AreEqual(plain, 65);
        }
        public void RSATestDec3()
        {
            RSA algorithm = new RSA();
            int plain     = algorithm.Decrypt(61, 53, 2338, 7);

            Assert.AreEqual(plain, 70);
        }
        public void RSATestDec1()
        {
            RSA algorithm = new RSA();
            int plain     = algorithm.Decrypt(11, 17, 11, 7);

            Assert.AreEqual(plain, 88);
        }
Esempio n. 12
0
        public static string Read(string name)
        {
            // load an existing key from a no-expired cert with the subject name passed in from the OS-provided X509Store
            using (X509Store store = new X509Store("IoTHub", StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);
                foreach (X509Certificate2 cert in store.Certificates)
                {
                    if ((cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) &&
                        (DateTime.Now < cert.NotAfter))
                    {
                        using (RSA rsa = cert.GetRSAPrivateKey())
                        {
                            if (rsa != null)
                            {
                                foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in cert.Extensions)
                                {
                                    // check for instruction code extension
                                    if ((extension.Oid.Value == "2.5.29.23") && (extension.RawData.Length >= 4))
                                    {
                                        byte[] bytes = new byte[extension.RawData.Length - 4];
                                        Array.Copy(extension.RawData, 4, bytes, 0, bytes.Length);
                                        byte[] token = rsa.Decrypt(bytes, RSAEncryptionPadding.OaepSHA1);
                                        return(Encoding.ASCII.GetString(token));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }
Esempio n. 13
0
 public static byte[] DecryptDataOaepSha(X509Certificate2 cert, byte[] data, RSAEncryptionPadding strengh)
 {
     using (RSA rsa = cert.GetRSAPrivateKey())
     {
         return(rsa.Decrypt(data, strengh));
     }
 }
Esempio n. 14
0
        public void RealEncValue()
        {
            X509Certificate2 auth = realP12["authentication"];
            string           key  = realP12.Where(e => e.Value.Issuer == auth.Subject).Select(e => e.Key).FirstOrDefault();
            X509Certificate2 cert = realP12[key];

            Assert.NotNull(cert);
            Assert.True(cert.HasPrivateKey);


            byte[] data = Encoding.UTF8.GetBytes("My Test");

            RSA publicKey = (RSA)cert.PublicKey.Key;

            byte[] enc = publicKey.Encrypt(data, RSAEncryptionPadding.Pkcs1);
            Assert.NotNull(enc);

            RSA privateKey = (RSA)cert.PrivateKey;

            byte[] data_copy = privateKey.Decrypt(enc, RSAEncryptionPadding.Pkcs1);
            Assert.Equal(data.Length, data_copy.Length);
            for (int i = 0; i < data.Length; i++)
            {
                Assert.Equal(data[i], data_copy[i]);
            }
        }
Esempio n. 15
0
        public void RsaDecryptPkcs1Deficient()
        {
            // This value is gibberish, but it happens to be true that if it is preceded
            // with 0x00 it happens to pass a PKCS1 encryption padding sanity test with the
            // RSA2048Params key.
            //
            // If instead of prepending a 0x00 one appended 0x4B, it would decrypt to "Hello".
            byte[] encrypted = (
                "7EF2A69BBCF5B29A19DF6698B8BAB5EC4D9DF1D8CAA27D7D1BF60D560DB7D79D" +
                "020C85620657F2A32C872EE44DB604FAFFF792A886BEF2E142A2DB0379C5C57D" +
                "D444D2065A7976A6163B4A0D51AEE421B099A8E8A823A917A6E55A4A8E660715" +
                "B9AC53CF37392228B2F7042CCBDA14CA88314FD353EA70AA9899E88771B01C8E" +
                "E0DE35BD342F43809670B056B35A0EB68D370E1489D51AA4780766739887DBC6" +
                "A716FE05773803C43B5040BF29AB33C4567E8986B3C442A7CEFCF46D61E13E54" +
                "85468C0FF3FDC804BDDE60E4310CC45F5196DC75F713581D934FB914661B6B69" +
                "EC3CE2CF469D7CD8727B959B5593F8D38124B0947E7948252BF9A53763877F").HexToByteArray();

            byte[] correctlyPadded = new byte[encrypted.Length + 1];
            Buffer.BlockCopy(encrypted, 0, correctlyPadded, 1, encrypted.Length);

            using (RSA rsa = RSAFactory.Create(TestData.RSA2048Params))
            {
                byte[] decrypted = Decrypt(rsa, correctlyPadded, RSAEncryptionPadding.Pkcs1);
                Assert.NotNull(decrypted);

                Assert.ThrowsAny <CryptographicException>(
                    () => rsa.Decrypt(encrypted, RSAEncryptionPadding.Pkcs1));
            }
        }
Esempio n. 16
0
        private void rsaStartDecrypt_Click(object sender, EventArgs e)
        {
            var ready = true;

            if (string.IsNullOrWhiteSpace(rsaDecryptCipherFile.Text))
            {
                MessageBox.Show("Choose a file for decryption", "Choose cipher text", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                ready = false;
            }
            if (string.IsNullOrWhiteSpace(rsaDecryptPrivateKeyFile.Text))
            {
                rsaDecryptPrivateKeyFile.Text = _initialDirectory + "RSA_private.txt";
            }
            if (string.IsNullOrWhiteSpace(rsaDecryptPlainFile.Text))
            {
                rsaDecryptPlainFile.Text = _initialDirectory + "RSA_decrypted.txt";
            }

            if (ready)
            {
                RSA.Decrypt(rsaDecryptCipherFile.Text, int.Parse(rsaKeysSize.Text), rsaDecryptPrivateKeyFile.Text,
                            rsaDecryptPlainFile.Text);
            }
        }
Esempio n. 17
0
        private static string Decryptv1(Func <string, X509Certificate2> certResolver, MemoryStream inputStream, BinaryReader reader)
        {
            string thumbprint = ToHexString(reader.ReadBytes(20), 0, 20);

            X509Certificate2 cert = certResolver(thumbprint);

            int encryptedKeyLength = reader.ReadInt32();
            int ivLength           = reader.ReadInt32();

            byte[] encryptedKey = reader.ReadBytes(encryptedKeyLength);
            byte[] iv           = reader.ReadBytes(ivLength);

            using (Aes aes = Aes.Create())
            {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.PKCS7;

                RSA    privateKey   = cert.GetRSAPrivateKey();
                byte[] decryptedKey = privateKey.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA512);

                using (ICryptoTransform transform = aes.CreateDecryptor(decryptedKey, iv))
                {
                    int remainingBytes = (int)(inputStream.Length - inputStream.Position);

                    var decryptedBytes = transform.TransformFinalBlock(reader.ReadBytes(remainingBytes), 0, remainingBytes);
                    return(Encoding.UTF8.GetString(decryptedBytes));
                }
            }
        }
Esempio n. 18
0
        public static void DecryptSavedAnswer()
        {
            byte[] cipherBytes =
            {
                0x35, 0x6F, 0x8F, 0x2C, 0x4D, 0x1A, 0xAC, 0x6D,
                0xE7, 0x52, 0xA5, 0xDF, 0x26, 0x54, 0xA6, 0x34,
                0xF5, 0xBB, 0x14, 0x26, 0x1C, 0xE4, 0xDC, 0xA2,
                0xD8, 0x4D, 0x8F, 0x1C, 0x55, 0xD4, 0xC7, 0xA7,
                0xF2, 0x3C, 0x99, 0x77, 0x9F, 0xE4, 0xB7, 0x34,
                0xA6, 0x28, 0xB2, 0xC4, 0xFB, 0x6F, 0x85, 0xCA,
                0x19, 0x21, 0xCA, 0xC1, 0xA7, 0x8D, 0xAE, 0x95,
                0xAB, 0x9B, 0xA9, 0x88, 0x5B, 0x44, 0xC6, 0x9B,
                0x44, 0x26, 0x71, 0x5D, 0x02, 0x3F, 0x43, 0x42,
                0xEF, 0x4E, 0xEE, 0x09, 0x87, 0xEF, 0xCD, 0xCF,
                0xF9, 0x88, 0x99, 0xE8, 0x49, 0xF7, 0x8F, 0x9B,
                0x59, 0x68, 0x20, 0xF3, 0xA7, 0xB2, 0x94, 0xA4,
                0x23, 0x70, 0x83, 0xD9, 0xAC, 0xE7, 0x5E, 0xEE,
                0xE9, 0x7B, 0xE4, 0x4F, 0x73, 0x2E, 0x9B, 0xD8,
                0x2A, 0x75, 0xFB, 0x6C, 0xB9, 0x39, 0x6D, 0x72,
                0x8A, 0x9C, 0xCD, 0x58, 0x1A, 0x27, 0x79, 0x97,
            };

            byte[] output;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                output = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.OaepSHA1);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
Esempio n. 19
0
        public static byte[] RsaPkcs15Sha_Decrypt(
            ArraySegment <byte> data,
            X509Certificate2 cert,
            RSA rsaPrivate,
            SecurityPolicy policy)
        {
            int cipherTextBlockSize = UASecurity.GetCipherTextBlockSize(cert);

            byte[] buffer1 = new byte[data.Count / cipherTextBlockSize * UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy))];
            int    length  = rsaPrivate.KeySize / 8;

            UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy));
            if ((uint)(data.Count % length) > 0U)
            {
                throw new Exception(string.Format("Input data is not a multiple of block size, {0}/{1}", data.Count, length));
            }

            MemoryStream memoryStream = new MemoryStream(buffer1);

            byte[] data1 = new byte[length];
            for (int offset = data.Offset; offset < data.Offset + data.Count; offset += length)
            {
                Array.Copy(data.Array, offset, data1, 0, data1.Length);
                byte[] buffer2 = rsaPrivate.Decrypt(data1, UASecurity.UseOaepForSecurityPolicy(policy));
                memoryStream.Write(buffer2, 0, buffer2.Length);
            }
            memoryStream.Close();
            return(buffer1);
        }
Esempio n. 20
0
        public static void DecryptSavedAnswerUnusualExponent()
        {
            byte[] cipherBytes =
            {
                0x55, 0x64, 0x05, 0xF7, 0xBF, 0x99, 0xD8, 0x07,
                0xD0, 0xAC, 0x1B, 0x1B, 0x60, 0x92, 0x57, 0x95,
                0x5D, 0xA4, 0x5B, 0x55, 0x0E, 0x12, 0x90, 0x24,
                0x86, 0x35, 0xEE, 0x6D, 0xB3, 0x46, 0x3A, 0xB0,
                0x3D, 0x67, 0xCF, 0xB3, 0xFA, 0x61, 0xBB, 0x90,
                0x6D, 0x6D, 0xF8, 0x90, 0x5D, 0x67, 0xD1, 0x8F,
                0x99, 0x6C, 0x31, 0xA2, 0x2C, 0x8E, 0x99, 0x7E,
                0x75, 0xC5, 0x26, 0x71, 0xD1, 0xB0, 0xA5, 0x41,
                0x67, 0x19, 0xF7, 0x40, 0x04, 0xBE, 0xB2, 0xC0,
                0x97, 0xFB, 0xF6, 0xD4, 0xEF, 0x48, 0x5B, 0x93,
                0x81, 0xF8, 0xE1, 0x6A, 0x0E, 0xA0, 0x74, 0x6B,
                0x99, 0xC6, 0x23, 0xF5, 0x02, 0xDE, 0x47, 0x49,
                0x1E, 0x9D, 0xAE, 0x55, 0x20, 0xB5, 0xDE, 0xA0,
                0x04, 0x32, 0x37, 0x4B, 0x24, 0xE4, 0x64, 0x1B,
                0x1B, 0x4B, 0xC0, 0xC7, 0x30, 0x08, 0xA6, 0xAE,
                0x50, 0x86, 0x08, 0x34, 0x70, 0xE5, 0xB0, 0x3B,
            };

            byte[] output;

            using (RSA rsa = RSAFactory.Create())
            {
                rsa.ImportParameters(TestData.UnusualExponentParameters);
                output = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.OaepSHA1);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
Esempio n. 21
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
            Cls_Metodos     metodos   = new Cls_Metodos();

            try
            {
                Cls_User clsUser = new Cls_User();

                string query        = actionContext.Request.RequestUri.Query;
                var    queryStrings = System.Web.HttpUtility.ParseQueryString(query);

                int    usuario_id = Convert.ToInt32(metodos.ObtieneValorDesdeToken("idUsuario", principal));
                string token      = metodos.ObtieneValorDesdeToken("token", principal);

                //RSA dec = new RSA("<RSAKeyValue><Modulus>t015WR/Q/hmDXmQp+Bf0vMLUsGWg6QOb/zt/RbVb4nvsbQA9bjHzMT1pw0UfFvJrxSnNUqsLRKUyy0UXpEgu1fB5nQUtSYzJk4dnEaOtwQHr7QLEW8+lhvefj35XXxurLUbzDZ79LodTmn2bNVPq4SZXKIDq+vm9iwWuaDWfqqaVRCw8O8dHg9nC4wXDaRTnZfon7GEzEUjpVPFH1xyYEUrqV7XbYkpxI05ruvqyYLEOkTZ7H5jGKjhEikl7CXrj6jYV3A3bsmunfz0eQRXef7xAR1gkkZ71KvnRYnukY4nUTTL8AWvrAl6+dugLduPz8HMX8mAcCSY2Rb5Ihkex9w==</Modulus><Exponent>AQAB</Exponent><P>395jT4DcwdSye1paCo38jvCIiBmuUKT0ziHlOE6/AzqBX5cN6YsIJ7yo0VuAJt/vwFDTJx6FmAXHGhV1MPEhwRfLPELtQNKRNXI/yIm7+2pqIutDFwOC8v/SuO1LTsUhQq0jRf+/O0sKcsrLOKt3i8yESm8IKIt4HxL5auKO98c=</P><Q>0ZyQ8fpevjy5n/8b6Qf4PFlB2c8b7+9unY9m1ioEcxffi67Kzd0mdnqW8WyfTDng+GoxxPhZKciMbMd9D2i/QZDwUotF2GOk25E8JN1SzcB0eNT1Jif+K9+PkN083TyFU0RB1NHQF7NSmlmdt6yqk9xKGKSHhFdNs82kpvBSVFE=</Q><DP>LRRuMRtE2O9IxZgrG4b9/ZaoF6f8NxcQiNXAf7cztaW5WZNkZMvvZ3kREZ94Tdu4PqTH8E+wHS3Eqxb5E1LrNiPhdBASEISWYwnPmEVMClOibcesKd02KFKlj0GRcZo2mWOd/8GBM6JnxzfY9l9o4kjbttVm8isrlC5Q9VoL6g8=</DP><DQ>RVc129anYOdVwMfzw7MPO2eLkTIiW80pGpZFvrNHpYtQODUqgc+W2brUFCmKyPycn5EBxdciJ+BgE9wqUt6j5ly8I5JPGLZd4wS4kLlmmwn/fbl1H5o7Sug55gJKECXlNRZvcKe33x9DRCxBMHG+PAuzt1M2QWFgIwr0XQVDNwE=</DQ><InverseQ>K6jXF/Q7vx3YhvO+6aDZ0ogICS6nkGEJpbf/dtEWlTxScFuSyj/ihai0cgg5yDWPyr54xRtu/FLytIrrt0GTx5YKfbMnQNxzcr3jNfxN7EKb8GNgbIjtly+4axvNIJGj1ANZJZJQi7MTx/ewZSvZiLaramtBwqGl6ZiUKVuyNZk=</InverseQ><D>QfUQuy8lpqlLigWEzI7iM6HvomGPWwk/csHX9B9kJsTst/QkJqi2l3s/uVH/8+PbP6DhDuQZM+Q1uMrtzOFkaPsU55lbSGHujrVkMwawmQi1+hzKxzaam0wzEBEoI0Lzf2FOSBJzi/CJ9sdHuBKwK7/+EMcCxrhiqcmrjjftchvPEzKfefVSGSy34lnrME8XjlTqbZQ9QQ/a+62STQ7Jg8bzT1xBe9fTN7m2tVyLElfayy4eB8fXlbFjRyJiLZmzYjpSqnuTC9rEgVds2qc918HBWBX0z9vgpmaqFdU39hEs+R/F7dD0qkxpoAO4oIKiff0YUCy0Mhzw5wyGYltwQQ==</D></RSAKeyValue>", "");
                //string d = dec.Decrypt("mrL+i/7qlZVgX23izK6xgZ7vZkt0WLxAO+g6XpWWIrkANzDNA7vLVHhUz65R/+9Q5M7UZNmDPHijIGwjsz7BaU9j+fiNJihlZGp5v9ah0Q/quK2ZTpiKhNovUzxZJ9GDOvHmT1j8HGzuu3EYJDc2XjFtMQ121suxzooELD0RFB4TsOvXA8c54L5d+jDhvOhyAAqg5WmioMC32rAXWHuM6ZjMgPRxjrSlBjh/69kjcwNbEY3+QtkAza6xA8oSzY8YLgAtp0M2BedzbEZnnw1Fd9qPBPY4a/7R9ytBAQ861jXwKXHZtB2tL4nxmORgNbu9iVMrbzOY8sJi2058QoyvcA==");

                int    numeroPeticion;
                string auth_token_test = ConfigurationManager.AppSettings["auth_token_test"].ToString();
                string auth_token      = actionContext.Request.Headers.GetValues("auth_token").FirstOrDefault();//"byaGultH3EmlfGhc8bA/Abtb6aFv+QeV9qvRnEGyunUsyRPqJe2EbUrgsYyzFBg16mYTu5B+WjqYoZEDHAktGKOeKpzRwlq7X3CXEE8DLQoXLiaY8avpF66BFcWzWIcqU11JMaROfDp2QM9k6smaymyn5Z25NV0bQMeQ3ltxGvoDVjXurZil99aaO8O81RPaUwWZUb0y9WM82hmRhDaVWuQLXEh5//8kJYvAm84cX3QK/oP1Okx7bG2wpXHuqYD8HmBVmJD1sCpd13rLwHpv2sOwpDLtY45OiqDFRbOOw9Y3lRZqCcoD636NwR6J2aPKFCk3DZNAuET+IjO6RGl48A==";//queryStrings["auth_token"];

                if (auth_token_test.Length > 0 && auth_token == auth_token_test)
                {
                    numeroPeticion = 0;
                }
                else
                {
                    RSA    dec     = new RSA(clsUser.ObtenerLlavePrimaria(usuario_id), "");
                    string decrypt = dec.Decrypt(auth_token);

                    bool result = Int32.TryParse(decrypt, out numeroPeticion);
                    if (!result)
                    {
                        throw new ArgumentException("Problema con RSA");
                    }
                }

                Cls_User user = new Cls_User();
                DataRow  row  = user.VerificarToken(usuario_id, token, numeroPeticion);
                if (Convert.ToInt32(row["valido"]) == 0)
                {
                    throw new ArgumentException(row["mensaje"].ToString());
                }

                return(base.IsAuthorized(actionContext));
            }
            catch (Exception exc)
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.Unauthorized,
                    Content    = new StringContent("{\"exito\":0, \"mensaje\":\"" + exc.Message + "\", \"logout\":1}", System.Text.Encoding.UTF8, "application/json")
                };
                int usuario_id = Convert.ToInt32(metodos.ObtieneValorDesdeToken("idUsuario", principal));
                Cls_User.Logout(usuario_id);
                return(false);
            }
        }
Esempio n. 22
0
 public string Decrypt(string cipherText)
 {
     if (_privateKeyRsaProvider == null)
     {
         throw new Exception("_privateKeyRsaProvider is null");
     }
     return(Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(System.Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1)));
 }
Esempio n. 23
0
        public static byte[] Decrypt(this RSA rsa, byte[] bytes)
        {
#if !NETSTANDARD2_0
            return(((RSACryptoServiceProvider)rsa).Decrypt(bytes, RsaUtils.DoOAEPPadding));
#else
            return(rsa.Decrypt(bytes, RSAEncryptionPadding.OaepSHA1));
#endif
        }
Esempio n. 24
0
 private static string Decrypt(X509Certificate2 certificate, string stringToDecrypt)
 {
     using (RSA rsa = certificate.GetRSAPrivateKey())
     {
         byte[] decryptedBytes = rsa.Decrypt(Encoding.UTF8.GetBytes(stringToDecrypt), RSAEncryptionPadding.OaepSHA256);
         return(Encoding.UTF8.GetString(decryptedBytes));
     }
 }
Esempio n. 25
0
 public void NullArray_Throws()
 {
     using (RSA rsa = RSAFactory.Create())
     {
         AssertExtensions.Throws <ArgumentNullException>("data", () => rsa.Encrypt(null, RSAEncryptionPadding.OaepSHA1));
         AssertExtensions.Throws <ArgumentNullException>("data", () => rsa.Decrypt(null, RSAEncryptionPadding.OaepSHA1));
     }
 }
Esempio n. 26
0
        public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType, bool keyFromFile)
        {
            try
            {
                RSA rsaCsp = null;
                if (keyFromFile)
                {
                    //文件读取
                    rsaCsp = LoadCertificateFile(privateKeyPem, signType);
                }
                else
                {
                    //字符串获取
                    rsaCsp = LoadCertificateString(privateKeyPem, signType);
                }
                if (string.IsNullOrEmpty(charset))
                {
                    charset = DEFAULT_CHARSET;
                }
                byte[] data         = Convert.FromBase64String(content);
                int    maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制
                if (data.Length <= maxBlockSize)
                {
                    byte[] cipherbytes = rsaCsp.Decrypt(data, RSAEncryptionPadding.Pkcs1);
                    return(Encoding.GetEncoding(charset).GetString(cipherbytes));
                }
                MemoryStream crypStream = new MemoryStream(data);
                MemoryStream plaiStream = new MemoryStream();
                Byte[]       buffer     = new Byte[maxBlockSize];
                int          blockSize  = crypStream.Read(buffer, 0, maxBlockSize);
                while (blockSize > 0)
                {
                    Byte[] toDecrypt = new Byte[blockSize];
                    Array.Copy(buffer, 0, toDecrypt, 0, blockSize);
                    Byte[] cryptograph = rsaCsp.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1);
                    plaiStream.Write(cryptograph, 0, cryptograph.Length);
                    blockSize = crypStream.Read(buffer, 0, maxBlockSize);
                }

                return(Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()));
            }
            catch (Exception ex)
            {
                throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex);
            }
        }
Esempio n. 27
0
        public void DecryptWithNullTest()
        {
            const string ciphertext = "aaabiebeg";

            var system = new RSA(new Alphabet("ab"));

            system.Decrypt(ciphertext, null);
        }
Esempio n. 28
0
        public void DecryptNullTest()
        {
            var key = new RSAKey((17, 11));

            var system = new RSA(new Alphabet("ab"));

            system.Decrypt(null, key);
        }
Esempio n. 29
0
        public string Decrypt(string cryptoText)
        {
            byte[] encryptedData = Convert.FromBase64String(cryptoText);
            byte[] data          = rsa.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);
            var    text          = byteConverter.GetString(data);

            return(text);
        }
        public void DecryptData()
        {
            RSA cipher = CreateCipher();

            //Decrypt the data
            byte[] original = cipher.Decrypt(Convert.FromBase64String(CipherText), RSAEncryptionPadding.Pkcs1);
            OriginalPlainText = Encoding.UTF8.GetString(original);
        }
Esempio n. 31
0
        private static void RSAEncrypt2()
        {
            // RSA examples
            RSA rsa = new RSA();

            RSACryptoServiceProvider serviceProvider =
                new RSACryptoServiceProvider();
            //Export the key information to an RSAParameters object.
            //Pass false to export the public key information or pass
            //true to export public and private key information.
            //RSAParameters RSAParams = RSA.ExportParameters(false);

            //Encrypt data
            UnicodeEncoding bytConvertor = new UnicodeEncoding();
            byte[] plainData = bytConvertor.GetBytes("Sample data");

            byte[] enData = rsa.Encrypt(plainData, serviceProvider.ExportParameters(false));
            Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData));

            byte[] deData = rsa.Decrypt(enData, serviceProvider.ExportParameters(true));
            Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData));
        }