public override void Configure(Container container)
        {
            RequestConverters.Add((req, requestDto) => {
                var encRequest = requestDto as BasicEncryptedMessage;
                if (encRequest == null)
                {
                    return(null);
                }

                var requestType   = Metadata.GetOperationType(encRequest.OperationName);
                var decryptedJson = RsaUtils.Decrypt(encRequest.EncryptedBody, SecureConfig.PrivateKeyXml);
                var request       = JsonSerializer.DeserializeFromString(decryptedJson, requestType);

                req.Items["_encrypt"] = encRequest;

                return(request);
            });

            ResponseConverters.Add((req, response) => {
                if (!req.Items.ContainsKey("_encrypt"))
                {
                    return(null);
                }

                var encResponse = RsaUtils.Encrypt(response.ToJson(), SecureConfig.PublicKeyXml);
                return(new BasicEncryptedMessageResponse
                {
                    OperationName = response.GetType().Name,
                    EncryptedBody = encResponse
                });
            });
        }
        private static string ValidateAndDecrypt(byte[] authRsaEncCryptKey, byte[] authEncryptedBytes)
        {
            byte[]    iv        = new byte[AesUtils.BlockSizeBytes];
            const int tagLength = HmacUtils.KeySizeBytes;

            byte[] rsaEncCryptAuthKeys = new byte[authRsaEncCryptKey.Length - iv.Length - tagLength];

            Buffer.BlockCopy(authRsaEncCryptKey, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(authRsaEncCryptKey, iv.Length, rsaEncCryptAuthKeys, 0, rsaEncCryptAuthKeys.Length);

            var cryptAuthKeys = RsaUtils.Decrypt(rsaEncCryptAuthKeys, SecureConfig.PrivateKeyXml);

            byte[] cryptKey = new byte[AesUtils.KeySizeBytes];
            byte[] authKey  = new byte[AesUtils.KeySizeBytes];

            Buffer.BlockCopy(cryptAuthKeys, 0, cryptKey, 0, cryptKey.Length);
            Buffer.BlockCopy(cryptAuthKeys, cryptKey.Length, authKey, 0, authKey.Length);

            if (!HmacUtils.Verify(authRsaEncCryptKey, authKey))
            {
                throw new Exception("authRsaEncCryptKey is Invalid");
            }

            if (!HmacUtils.Verify(authEncryptedBytes, authKey))
            {
                throw new Exception("authEncryptedBytes is Invalid");
            }

            var msgBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey);

            return(msgBytes.FromUtf8Bytes());
        }
        private static string ValidateAndDecryptWithMasterKey(byte[] rsaEncAesKeyNonceBytes, byte[] authEncryptedBytes)
        {
            var aesKeyNonceBytes = RsaUtils.Decrypt(rsaEncAesKeyNonceBytes, SecureConfig.PrivateKeyXml);

            var aesKey = new byte[AesUtils.KeySizeBytes];
            var iv     = new byte[AesUtils.BlockSizeBytes];

            Buffer.BlockCopy(aesKeyNonceBytes, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(aesKeyNonceBytes, iv.Length, aesKey, 0, aesKey.Length);

            var sha512HashBytes = aesKey.ToSha512HashBytes();
            var cryptKey        = new byte[sha512HashBytes.Length / 2];
            var authKey         = new byte[sha512HashBytes.Length / 2];

            Buffer.BlockCopy(sha512HashBytes, 0, cryptKey, 0, cryptKey.Length);
            Buffer.BlockCopy(sha512HashBytes, cryptKey.Length, authKey, 0, authKey.Length);

            if (!HmacUtils.Verify(authEncryptedBytes, authKey))
            {
                throw new Exception("Verification Failed");
            }

            var msgBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey);

            var json = msgBytes.FromUtf8Bytes();

            return(json);
        }
Exemplo n.º 4
0
 public Reminder Decrypt(Reminder reminder)
 {
     reminder.UserName  = RsaUtils.Decrypt <string>(reminder.UserName);
     reminder.Email     = RsaUtils.Decrypt <string>(reminder.Email);
     reminder.CellPhone = RsaUtils.Decrypt <string>(reminder.CellPhone);
     return(reminder);
 }
Exemplo n.º 5
0
 private Contact Decrypt(Contact contact)
 {
     contact.Name      = RsaUtils.Decrypt <string>(contact.Name);
     contact.Email     = RsaUtils.Decrypt <string>(contact.Email);
     contact.CellPhone = RsaUtils.Decrypt <string>(contact.CellPhone);;
     return(contact);
 }
Exemplo n.º 6
0
        public void RsaTestFunction()
        {
            RsaKeys keys = RsaUtils.GenerateRsaKeys();

            RsaTestObj obj = new RsaTestObj()
            {
                MyProperty     = 9527,
                MyPropertyList = new List <string> {
                    "9527", "HelloWorld"
                }
            };

            var text   = RsaUtils.Encrypt(keys.PublicKey, obj);
            var newObj = RsaUtils.Decrypt <RsaTestObj>(keys.PrivateKey, text);

            bool result = newObj != null &&
                          newObj.MyProperty == obj.MyProperty &&
                          newObj.MyPropertyList != null &&
                          newObj.MyPropertyList.Count == obj.MyPropertyList.Count;

            if (result)
            {
                for (int i = 0; i < obj.MyPropertyList.Count; ++i)
                {
                    var left  = obj.MyPropertyList[i];
                    var right = newObj.MyPropertyList[i];
                    if (left != right)
                    {
                        result = false;
                    }
                }
            }

            Assert.IsTrue(result);
        }
        public void Can_Encryt_and_Decrypt_String()
        {
            var request = new HelloSecure {
                Name = "World"
            };
            var requestJson = request.ToJson();
            var encRequest  = RsaUtils.Encrypt(requestJson, SecureConfig.PublicKeyXml);

            var decJson = RsaUtils.Decrypt(encRequest, SecureConfig.PrivateKeyXml);

            Assert.That(decJson, Is.EqualTo(requestJson));
        }
Exemplo n.º 8
0
 private Account Decrypt(Account account)
 {
     account.Name = RsaUtils.Decrypt <string>(account.Name);
     if (account.IssuerBank != null && account.IssuerBank != "")
     {
         account.IssuerBank = RsaUtils.Decrypt <string>(account.IssuerBank);
     }
     if (account.BankAccount != null && account.BankAccount != "")
     {
         account.BankAccount = RsaUtils.Decrypt <string>(account.BankAccount);
     }
     return(account);
 }
        public void Can_Send_Encrypted_Message()
        {
            var client = new JsonServiceClient(Config.AbsoluteBaseUri);

            var request = new HelloSecure {
                Name = "World"
            };
            var encRequest = RsaUtils.Encrypt(request.ToJson(), SecureConfig.PublicKeyXml);

            var encResponse = client.Post(new BasicEncryptedMessage
            {
                OperationName = typeof(HelloSecure).Name,
                EncryptedBody = encRequest
            });

            var responseJson = RsaUtils.Decrypt(encResponse.EncryptedBody, SecureConfig.PrivateKeyXml);
            var response     = responseJson.FromJson <HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
Exemplo n.º 10
0
 /// <summary>Check if the decryption was correct</summary>
 /// <param name="file">The file to decrypt</param>
 /// <param name="key">The key file</param>
 /// <param name="error">A error to return</param>
 /// <param name="path">The path for the new file</param>
 /// <returns>True if is correct, otherwise false</returns>
 private bool DidDecryption(HttpPostedFileBase file, HttpPostedFileBase key, ref string error, ref string path)
 {
     if (fileUtils.IsFileTypeCorrect(file, ".rsacif", ref error) && fileUtils.IsFileTypeCorrect(key, ".key", ref error))
     {
         string   uploadedFile = fileUtils.SaveFile(file, "~/App_Data/Uploads");
         string   uploadedKey  = fileUtils.SaveFile(key, "~/App_Data/Uploads");
         RsaUtils rsa          = new RsaUtils();
         if (rsa.Decrypt(uploadedFile, uploadedKey, ref path))
         {
             return(true);
         }
         else
         {
             error = "Bad Encryption";
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 11
0
        public void TestSign()
        {
            //2048 ¹«Ô¿
            string publicKey =
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoQh0wEqx/R2H1v00IU12Oc30fosRC/frhH89L6G+fzeaqI19MYQhEPMU13wpeqRONCUta+2iC1sgCNQ9qGGf19yGdZUfueaB1Nu9rdueQKXgVurGHJ+5N71UFm+OP1XcnFUCK4wT5d7ZIifXxuqLehP9Ts6sNjhVfa+yU+VjF5HoIe69OJEPo7OxRZcRTe17khc93Ic+PfyqswQJJlY/bgpcLJQnM+QuHmxNtF7/FpAx9YEQsShsGpVo7JaKgLo+s6AFoJ4QldQKir2vbN9vcKRbG3piElPilWDpjXQkOJZhUloh/jd7QrKFimZFldJ1r6Q59QYUyGKZARUe0KZpMQIDAQAB";
            //2048 ˽Կ
            string privateKey =
                "MIIEpAIBAAKCAQEAoQh0wEqx/R2H1v00IU12Oc30fosRC/frhH89L6G+fzeaqI19MYQhEPMU13wpeqRONCUta+2iC1sgCNQ9qGGf19yGdZUfueaB1Nu9rdueQKXgVurGHJ+5N71UFm+OP1XcnFUCK4wT5d7ZIifXxuqLehP9Ts6sNjhVfa+yU+VjF5HoIe69OJEPo7OxRZcRTe17khc93Ic+PfyqswQJJlY/bgpcLJQnM+QuHmxNtF7/FpAx9YEQsShsGpVo7JaKgLo+s6AFoJ4QldQKir2vbN9vcKRbG3piElPilWDpjXQkOJZhUloh/jd7QrKFimZFldJ1r6Q59QYUyGKZARUe0KZpMQIDAQABAoIBAQCRZLUlOUvjIVqYvhznRK1OG6p45s8JY1r+UnPIId2Bt46oSLeUkZvZVeCnfq9k0Bzb8AVGwVPhtPEDh73z3dEYcT/lwjLXAkyPB6gG5ZfI/vvC/k7JYV01+neFmktw2/FIJWjEMMF2dvLNZ/Pm4bX1Dz9SfD/45Hwr8wqrvRzvFZsj5qqOxv9RPAudOYwCwZskKp/GF+L+3Ycod1Wu98imzMZUH+L5dQuDGg3kvf3ljIAegTPoqYBg0imNPYY/EGoFKnbxlK5S5/5uAFb16dGJqAz3XQCz9Is/IWrOTu0etteqV2Ncs8uqPdjed+b0j8CMsr4U1xjwPQ8WwdaJtTkRAoGBANAndgiGZkCVcc9975/AYdgFp35W6D+hGQAZlL6DmnucUFdXbWa/x2rTSEXlkvgk9X/PxOptUYsLJkzysTgfDywZwuIXLm9B3oNmv3bVgPXsgDsvDfaHYCgz0nHK6NSrX2AeX3yO/dFuoZsuk+J+UyRigMqYj0wjmxUlqj183hinAoGBAMYMOBgF77OXRII7GAuEut/nBeh2sBrgyzR7FmJMs5kvRh6Ck8wp3ysgMvX4lxh1ep8iCw1R2cguqNATr1klOdsCTOE9RrhuvOp3JrYzuIAK6MpH/uBICy4w1rW2+gQySsHcH40r+tNaTFQ7dQ1tef//iy/IW8v8i0t+csztE1JnAoGABdtWYt8FOYP688+jUmdjWWSvVcq0NjYeMfaGTOX/DsNTL2HyXhW/Uq4nNnBDNmAz2CjMbZwt0y+5ICkj+2REVQVUinAEinTcAe5+LKXNPx4sbX3hcrJUbk0m+rSu4G0B/f5cyXBsi9wFCAzDdHgBduCepxSr04Sc9Hde1uQQi7kCgYB0U20HP0Vh+TG2RLuE2HtjVDD2L/CUeQEiXEHzjxXWnhvTg+MIAnggvpLwQwmMxkQ2ACr5sd/3YuCpB0bxV5o594nsqq9FWVYBaecFEjAGlWHSnqMoXWijwu/6X/VOTbP3VjH6G6ECT4GR4DKKpokIQrMgZ9DzaezvdOA9WesFdQKBgQCWfeOQTitRJ0NZACFUn3Fs3Rvgc9eN9YSWj4RtqkmGPMPvguWo+SKhlk3IbYjrRBc5WVOdoX8JXb2/+nAGhPCuUZckWVmZe5pMSr4EkNQdYeY8kOXGSjoTOUH34ZdKeS+e399BkBWIiXUejX/Srln0H4KoHnTWgxwNpTsBCgXu8Q==";

            var rsa = new RsaUtils(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey);

            string str = "²©¿ÍÔ° http://www.cnblogs.com/";

            Console.WriteLine("ԭʼ×Ö·û´®£º" + str);

            //¼ÓÃÜ
            string enStr = rsa.Encrypt(str);

            Console.WriteLine("¼ÓÃÜ×Ö·û´®£º" + enStr);

            //½âÃÜ
            string deStr = rsa.Decrypt(enStr);

            Console.WriteLine("½âÃÜ×Ö·û´®£º" + deStr);

            //˽ԿǩÃû
            string signStr = rsa.Sign(str);

            Console.WriteLine("×Ö·û´®Ç©Ãû£º" + signStr);

            //¹«Ô¿Ñé֤ǩÃû
            bool signVerify = rsa.Verify(str, signStr);

            Console.WriteLine("Ñé֤ǩÃû£º" + signVerify);

            Console.ReadKey();

            Console.ReadKey(true);
        }
Exemplo n.º 12
0
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName))
            {
                return;
            }

            var bearerToken = req.GetBearerToken()
                              ?? req.GetCookieValue(Keywords.TokenCookie);

            if (bearerToken != null)
            {
                var parts = bearerToken.Split('.');
                if (parts.Length == 3)
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    var header         = parts[0];
                    var payload        = parts[1];
                    var signatureBytes = parts[2].FromBase64UrlSafe();

                    var headerJson   = header.FromBase64UrlSafe().FromUtf8Bytes();
                    var payloadBytes = payload.FromBase64UrlSafe();

                    var headerData = headerJson.FromJson <Dictionary <string, string> >();

                    var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes();

                    var algorithm = headerData["alg"];

                    //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
                    if (RequireHashAlgorithm && algorithm != HashAlgorithm)
                    {
                        throw new NotSupportedException("Invalid algoritm '{0}', expected '{1}'".Fmt(algorithm, HashAlgorithm));
                    }

                    if (!VerifyPayload(algorithm, bytesToSign, signatureBytes))
                    {
                        return;
                    }

                    var payloadJson = payloadBytes.FromUtf8Bytes();
                    var jwtPayload  = JsonObject.Parse(payloadJson);

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
                else if (parts.Length == 5) //Encrypted JWE Token
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    if (PrivateKey == null || PublicKey == null)
                    {
                        throw new NotSupportedException("PrivateKey is required to DecryptPayload");
                    }

                    var jweHeaderBase64Url  = parts[0];
                    var jweEncKeyBase64Url  = parts[1];
                    var ivBase64Url         = parts[2];
                    var cipherTextBase64Url = parts[3];
                    var tagBase64Url        = parts[4];

                    var sentTag    = tagBase64Url.FromBase64UrlSafe();
                    var aadBytes   = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                    var iv         = ivBase64Url.FromBase64UrlSafe();
                    var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                    var jweEncKey        = jweEncKeyBase64Url.FromBase64UrlSafe();
                    var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                    var authKey  = new byte[128 / 8];
                    var cryptKey = new byte[128 / 8];
                    Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                    Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                    using (var hmac = new HMACSHA256(authKey))
                        using (var encryptedStream = new MemoryStream())
                        {
                            using (var writer = new BinaryWriter(encryptedStream))
                            {
                                writer.Write(aadBytes);
                                writer.Write(iv);
                                writer.Write(cipherText);
                                writer.Flush();

                                var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                                if (!calcTag.EquivalentTo(sentTag))
                                {
                                    return;
                                }
                            }
                        }

                    JsonObject jwtPayload;
                    var        aes = Aes.Create();
                    aes.KeySize   = 128;
                    aes.BlockSize = 128;
                    aes.Mode      = CipherMode.CBC;
                    aes.Padding   = PaddingMode.PKCS7;
                    using (aes)
                        using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                            using (var ms = MemoryStreamFactory.GetStream(cipherText))
                                using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    var jwtPayloadBytes = cryptStream.ReadFully();
                                    jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes());
                                }

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
            }
        }
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName))
            {
                return;
            }

            var bearerToken = req.GetJwtToken();

            if (bearerToken != null)
            {
                var parts = bearerToken.Split('.');
                if (parts.Length == 3)
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    var jwtPayload = GetVerifiedJwtPayload(parts);
                    if (jwtPayload == null) //not verified
                    {
                        return;
                    }

                    if (ValidateToken != null)
                    {
                        if (!ValidateToken(jwtPayload, req))
                        {
                            throw HttpError.Forbidden(ErrorMessages.TokenInvalid);
                        }
                    }

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
                else if (parts.Length == 5) //Encrypted JWE Token
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    if (PrivateKey == null || PublicKey == null)
                    {
                        throw new NotSupportedException("PrivateKey is required to DecryptPayload");
                    }

                    var jweHeaderBase64Url  = parts[0];
                    var jweEncKeyBase64Url  = parts[1];
                    var ivBase64Url         = parts[2];
                    var cipherTextBase64Url = parts[3];
                    var tagBase64Url        = parts[4];

                    var sentTag    = tagBase64Url.FromBase64UrlSafe();
                    var aadBytes   = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                    var iv         = ivBase64Url.FromBase64UrlSafe();
                    var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                    var jweEncKey        = jweEncKeyBase64Url.FromBase64UrlSafe();
                    var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                    var authKey  = new byte[128 / 8];
                    var cryptKey = new byte[128 / 8];
                    Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                    Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                    using (var hmac = new HMACSHA256(authKey))
                        using (var encryptedStream = new MemoryStream())
                        {
                            using (var writer = new BinaryWriter(encryptedStream))
                            {
                                writer.Write(aadBytes);
                                writer.Write(iv);
                                writer.Write(cipherText);
                                writer.Flush();

                                var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                                if (!calcTag.EquivalentTo(sentTag))
                                {
                                    return;
                                }
                            }
                        }

                    JsonObject jwtPayload;
                    var        aes = Aes.Create();
                    aes.KeySize   = 128;
                    aes.BlockSize = 128;
                    aes.Mode      = CipherMode.CBC;
                    aes.Padding   = PaddingMode.PKCS7;
                    using (aes)
                        using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                            using (var ms = MemoryStreamFactory.GetStream(cipherText))
                                using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    var jwtPayloadBytes = cryptStream.ReadFully();
                                    jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes());
                                }

                    if (ValidateToken != null)
                    {
                        if (!ValidateToken(jwtPayload, req))
                        {
                            throw HttpError.Forbidden(ErrorMessages.TokenInvalid);
                        }
                    }

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
            }
        }
Exemplo n.º 14
0
        public JsonObject GetVerifiedJwtPayload(string[] parts)
        {
            if (parts.Length == 3)
            {
                var header         = parts[0];
                var payload        = parts[1];
                var signatureBytes = parts[2].FromBase64UrlSafe();

                var headerJson   = header.FromBase64UrlSafe().FromUtf8Bytes();
                var payloadBytes = payload.FromBase64UrlSafe();

                var headerData = headerJson.FromJson <Dictionary <string, string> >();

                var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes();

                var algorithm = headerData["alg"];

                //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
                if (RequireHashAlgorithm && algorithm != HashAlgorithm)
                {
                    throw new NotSupportedException($"Invalid algoritm '{algorithm}', expected '{HashAlgorithm}'");
                }

                if (!VerifyPayload(algorithm, bytesToSign, signatureBytes))
                {
                    return(null);
                }

                var payloadJson = payloadBytes.FromUtf8Bytes();
                var jwtPayload  = JsonObject.Parse(payloadJson);
                return(jwtPayload);
            }
            if (parts.Length == 5) //Encrypted JWE Token
            {
                var jweHeaderBase64Url  = parts[0];
                var jweEncKeyBase64Url  = parts[1];
                var ivBase64Url         = parts[2];
                var cipherTextBase64Url = parts[3];
                var tagBase64Url        = parts[4];

                var sentTag    = tagBase64Url.FromBase64UrlSafe();
                var aadBytes   = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                var iv         = ivBase64Url.FromBase64UrlSafe();
                var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                var jweEncKey        = jweEncKeyBase64Url.FromBase64UrlSafe();
                var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                var authKey  = new byte[128 / 8];
                var cryptKey = new byte[128 / 8];
                Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                using (var hmac = new HMACSHA256(authKey))
                    using (var encryptedStream = new MemoryStream())
                    {
                        using (var writer = new BinaryWriter(encryptedStream))
                        {
                            writer.Write(aadBytes);
                            writer.Write(iv);
                            writer.Write(cipherText);
                            writer.Flush();

                            var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                            if (!calcTag.EquivalentTo(sentTag))
                            {
                                return(null);
                            }
                        }
                    }

                var aes = Aes.Create();
                aes.KeySize   = 128;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.PKCS7;
                using (aes)
                    using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                        using (var ms = MemoryStreamFactory.GetStream(cipherText))
                            using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                            {
                                var jwtPayloadBytes = cryptStream.ReadFully();
                                return(JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes()));
                            }
            }

            throw new ArgumentException(ErrorMessages.TokenInvalid);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Decrypt an encrypted text.
        /// </summary>
        /// <param name="encryptedText">The encrypted text.</param>
        /// <param name="options">The decryption options.</param>
        /// <returns>Returns a decrypted text.</returns>
        public static string Decrypt(string encryptedText, IDictionary <string, object> options)
        {
            var toDecrypt     = encryptedText;
            var decryptedText = string.Empty;

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

            var decodeFromBase64 = options.ContainsKey("DecodeFromBase64") &&
                                   Convert.ToBoolean(options["DecodeFromBase64"], CultureInfo.InvariantCulture);
            var encodeToBase64 = options.ContainsKey("EncodeToBase64") && Convert.ToBoolean(options["EncodeToBase64"], CultureInfo.InvariantCulture);

            var method = options.ContainsKey("Method") ? options["Method"].ToString() : string.Empty;

            switch (method)
            {
            // RSA
            case "RSA":
                var privateKeyPath = options["PrivateKeyPath"].ToString();

                if (privateKeyPath.StartsWith("\"", StringComparison.InvariantCulture))
                {
                    privateKeyPath = privateKeyPath.Substring(1, privateKeyPath.Length - 1);
                }

                if (privateKeyPath.EndsWith("\"", StringComparison.InvariantCulture))
                {
                    privateKeyPath = privateKeyPath.Substring(0, privateKeyPath.Length - 1);
                }

                decryptedText = decodeFromBase64 ? RsaUtils.Base64DecodeAndDecrypt(toDecrypt, privateKeyPath) : RsaUtils.Decrypt(toDecrypt, privateKeyPath);
                break;

            // AES
            case "AES":
                var key = options["key"].ToString();
                var initializationValue = options["iniValue"].ToString();

                decryptedText = decodeFromBase64 ? AesUtils.Base64DecodeAndDecrypt(toDecrypt, key, initializationValue) : AesUtils.Decrypt(toDecrypt, key, initializationValue);
                break;

            // Base64
            case "Base64":
                decryptedText = GeneralUtils.Base64Decode(toDecrypt);
                break;
            }

            return(encodeToBase64 ? GeneralUtils.Base64Encode(decryptedText) : decryptedText);
        }