예제 #1
0
        public void TestSignAndCheckWithPublicKey()
        {
            var message = DateTime.Now.ToString();
            //"string to be encrypted";

            var _rsau       = new RsaUtils();
            var signMessage = _rsau.SignData(message);

            Assert.IsNotNull(signMessage);
            Assert.IsTrue(signMessage.Length > 0);

            var _rsau2 = new RsaUtils();

            _rsau2.SetKeys(_rsau.GetKeyInformation(false));
            var verifyData = _rsau2.CheckSign(message, signMessage);

            Assert.IsTrue(verifyData);
        }
        public void GetField()
        {
            _parent.doc.fat_inte = Int32.Parse(m_cli_cod.Text);
            _parent.doc.fat_dest = Int32.Parse(m_dst_cod.Text);

            try
            {
                int num = m_n_doc.Value == null ? 0 : Convert.ToInt32(m_n_doc.Value);
                _parent.doc.fat_n_doc = RsaUtils.GetStoredNumDoc(num, fat_registro.Text);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            _parent.doc.fat_registro = fat_registro.Text;
            _parent.doc.fat_d_doc    = m_d_doc.Date;
        }
예제 #3
0
        /// <summary>
        /// Calculates the size of the footer with an asymmetric signature.
        /// </summary>
        protected int GetAsymmetricSignatureSize(X509Certificate2 senderCertificate)
        {
            switch (SecurityPolicyUri)
            {
            case SecurityPolicies.Basic128Rsa15:
            case SecurityPolicies.Basic256:
            case SecurityPolicies.Basic256Sha256:
            {
                return(RsaUtils.GetSignatureLength(senderCertificate));
            }

            default:
            case SecurityPolicies.None:
            {
                return(0);
            }
            }
        }
    /// <summary>
    /// Get public key parameters from a X509Certificate2
    /// </summary>
    private static RsaKeyParameters GetPublicKeyParameter(X509Certificate2 certificate)
    {
        RSA rsa = null;

        try
        {
            rsa = certificate.GetRSAPublicKey();
            RSAParameters rsaParams = rsa.ExportParameters(false);
            return(new RsaKeyParameters(
                       false,
                       new BigInteger(1, rsaParams.Modulus),
                       new BigInteger(1, rsaParams.Exponent)));
        }
        finally
        {
            RsaUtils.RSADispose(rsa);
        }
    }
        public void Can_Send_Encrypted_Message()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            byte[] cryptKey, authKey, iv;
            AesUtils.CreateCryptAuthKeysAndIv(out cryptKey, out authKey, out iv);

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedBytes     = AesUtils.Encrypt(requestBody.ToUtf8Bytes(), cryptKey, iv);
            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(authRsaEncCryptAuthKeys),
                EncryptedBody         = Convert.ToBase64String(authEncryptedBytes),
            };

            var encResponse = client.Post(encryptedMessage);

            authEncryptedBytes = Convert.FromBase64String(encResponse.EncryptedBody);

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

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

            var responseJson = decryptedBytes.FromUtf8Bytes();
            var response     = responseJson.FromJson <HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
예제 #6
0
        public void TestSetPublicKey()
        {
            var _rsau    = new RsaUtils();
            var origKeys = _rsau.GetKeyInformation(false);

            var _rsau2    = new RsaUtils();
            var origKeys2 = _rsau2.GetKeyInformation(false);

            Assert.IsNotNull(origKeys);
            Assert.IsNotNull(origKeys2);
            Assert.IsFalse(origKeys.Equals(origKeys2));

            _rsau2.SetKeys(origKeys);
            var origKeys2_2 = _rsau2.GetKeyInformation(false);

            Assert.IsNotNull(origKeys2_2);
            Assert.IsFalse(origKeys2.Equals(origKeys2_2));
            Assert.IsTrue(origKeys.Equals(origKeys2_2));
        }
    /// <summary>
    /// Verify RSA key pair of two certificates.
    /// </summary>
    private static bool VerifyRSAKeyPair(
        X509Certificate2 certWithPublicKey,
        X509Certificate2 certWithPrivateKey,
        bool throwOnError = false)
    {
        bool result = false;

        try
        {
            // verify the public and private key match
            using (RSA rsaPrivateKey = certWithPrivateKey.GetRSAPrivateKey())
            {
                using (RSA rsaPublicKey = certWithPublicKey.GetRSAPublicKey())
                {
                    Opc.Ua.Test.RandomSource randomSource = new Opc.Ua.Test.RandomSource();
                    int    blockSize = RsaUtils.GetPlainTextBlockSize(rsaPrivateKey, true);
                    byte[] testBlock = new byte[blockSize];
                    randomSource.NextBytes(testBlock, 0, blockSize);
                    byte[] encryptedBlock = rsaPublicKey.Encrypt(testBlock, RSAEncryptionPadding.OaepSHA1);
                    byte[] decryptedBlock = rsaPrivateKey.Decrypt(encryptedBlock, RSAEncryptionPadding.OaepSHA1);
                    if (decryptedBlock != null)
                    {
                        result = Utils.IsEqual(testBlock, decryptedBlock);
                    }
                }
            }
        }
        catch (Exception e)
        {
            if (throwOnError)
            {
                throw e;
            }
        }
        finally
        {
            if (!result && throwOnError)
            {
                throw new CryptographicException("The public/private key pair in the certficates do not match.");
            }
        }
        return(result);
    }
예제 #8
0
        public void xxx()
        {
            var privKeyStr =
                @"MIICXQIBAAKBgQDEuMdX757iaBkrxN51IQMILf+o7nJhfddEQ8gurVNYgoGxg19N
ZtrJaegAiv6lbFO4jhkKzLX9mHXZrvxL+UD5lr458BA8vwm+ws7lxu+10exq0Xns
H26ekvBveDcbndhX+fbc34HhZlJCib6MKMzUGebwckGbZK3oz4WCZc3QoQIDAQAB
AoGBALBWWgpPNwMIARgk3qvrrYYVhYhuRYVyghYlFDoTEBTU12DBvBnrys6k6lwi
O+UY12slpPjzS2dI1MsOegW4Ji5/6w/rZC8BoyvOADSVWKc71eaQ8d9IqjjWKp0+
cL9hgI8s/DDYUtqmrqsxqPGkxOx8NSD7VcSID7xbbqK/v5uJAkEA+hurMyJUPRCD
Uyfie1m+cfQKjc4j4zN32KrbceG25QJq8Y/lpQSq0POSsmvaIxGkRJtTIoB6T/co
TYvox/kUiwJBAMlbJvyjm2KY12CTFjN7apmnMIRoYmI9z8n4hLl2h8852s+Ljdjn
MrCOcsL0T0kvxLlAKDwAeVWtjil3A9/DGQMCQAJPERSGw5pQtbWlz5xt5qkspJBM
j95AEmIoqZ/ygnq4u/4A4xDT6zPEm90Ty865EfgkKu9NmlN0p6WXng2CiiMCQEND
nQmGihDs5/4OBLub/edob4+74ynYZkKdL5FZJFM4i30LrI4J5egPHg08WgQj3f7Y
jNhGfEH/4V6+sF+eqAsCQQCTl/A2JqF6CThIdk6zLF40cJGRFOkAcRqsrV3Q64XD
C2rpXXqnjJlqysIFEmnUmxm64ckMyg96b1CxeW0F4Tr7";
            var privKey = Convert.FromBase64String(privKeyStr);
            var prvRsa  = RsaUtils.LoadPrivateKey(privKey);
        }
        public void Does_Hybrid_RSA_Crypt_and_Auth_AES_with_HMAC_SHA256()
        {
            var request = new HelloSecure {
                Name = "World"
            };
            var timestamp = DateTime.UtcNow.ToUnixTime();
            var msg       = timestamp + " POST " + request.GetType().Name + " " + request.ToJson();
            var msgBytes  = msg.ToUtf8Bytes();

            byte[] cryptKey, authKey, iv;
            AesUtils.CreateCryptAuthKeysAndIv(out cryptKey, out authKey, out iv);

            var encryptedBytes = AesUtils.Encrypt(msgBytes, cryptKey, iv);

            var decryptedBytes = AesUtils.Decrypt(encryptedBytes, cryptKey, iv);

            Assert.That(decryptedBytes, Is.EquivalentTo(msgBytes));

            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var decryptedMsg = ValidateAndDecrypt(authRsaEncCryptAuthKeys, authEncryptedBytes);

            var parts = decryptedMsg.SplitOnFirst(' ');

            Assert.That(long.Parse(parts[0]), Is.EqualTo(timestamp));

            parts = parts[1].SplitOnFirst(' ');
            Assert.That(parts[0], Is.EqualTo("POST"));

            parts = parts[1].SplitOnFirst(' ');
            Assert.That(parts[0], Is.EqualTo(request.GetType().Name));

            var decryptedJson    = parts[1];
            var decryptedRequest = decryptedJson.FromJson <HelloSecure>();

            Assert.That(decryptedRequest.Name, Is.EqualTo(request.Name));
        }
        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!"));
        }
        /// <summary>
        /// Verifies an RSA PKCS#1 v1.5 or PSS signature of a hash algorithm for the stream.
        /// </summary>
        private static bool Rsa_Verify(
            ArraySegment <byte> dataToVerify,
            byte[] signature,
            X509Certificate2 signingCertificate,
            HashAlgorithmName algorithm,
            RSASignaturePadding padding)
        {
            RSA rsa = null;

            try
            {
                // extract the public key.
                rsa = signingCertificate.GetRSAPublicKey();
                if (rsa == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No public key for certificate.");
                }

                // verify signature.
                if (!rsa.VerifyData(dataToVerify.Array, dataToVerify.Offset, dataToVerify.Count, signature, algorithm, padding))
                {
                    string messageType     = new UTF8Encoding().GetString(dataToVerify.Array, dataToVerify.Offset, 4);
                    int    messageLength   = BitConverter.ToInt32(dataToVerify.Array, dataToVerify.Offset + 4);
                    string actualSignature = Utils.ToHexString(signature);

                    Utils.Trace(
                        "Could not validate signature.\r\nCertificate={0}, MessageType={1}, Length={2}\r\nActualSignature={3}",
                        signingCertificate.Subject,
                        messageType,
                        messageLength,
                        actualSignature);

                    return(false);
                }
                return(true);
            }
            finally
            {
                RsaUtils.RSADispose(rsa);
            }
        }
        public void Does_throw_on_replayed_messages()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            var aes = new AesManaged {
                KeySize = AesUtils.KeySize
            };

            var aesKeyBytes       = aes.Key.Combine(aes.IV);
            var rsaEncAesKeyBytes = RsaUtils.Encrypt(aesKeyBytes, SecureConfig.PublicKeyXml);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(rsaEncAesKeyBytes),
                EncryptedBody         = AesUtils.Encrypt(requestBody, aes.Key, aes.IV)
            };
            var encResponse = client.Post(encryptedMessage);

            try
            {
                client.Post(encryptedMessage);

                Assert.Fail("Should throw");
            }
            catch (WebServiceException ex)
            {
                ex.StatusDescription.Print();

                var errorResponse = (EncryptedMessageResponse)ex.ResponseDto;
                var responseJson  = AesUtils.Decrypt(errorResponse.EncryptedBody, aes.Key, aes.IV);
                var response      = responseJson.FromJson <ErrorResponse>();
                Assert.That(response.ResponseStatus.Message, Is.EqualTo("Nonce already seen"));
            }
        }
예제 #13
0
        public void CreateTestLicenseFile()
        {
            var rsau = new RsaUtils();

            rsau.SetKeys(@"<RSAKeyValue><Modulus>2OO32RsAa73GjFw171YUkwOTyguKeT3N1zjAZY04/f4TdpRABfNBs1aHICepzhQ1gy1TBnYX3K95b+qD7u6CczU65JzormbqlgY1rweG+HNwGcn36g0M66k7qwfFSjZhbmlGTvedD7xo4L/pSf91p7KwjzLt6ac8+UAdqVfKsu0=</Modulus><Exponent>AQAB</Exponent><P>5P3vNrTqC9JeXmyJSQrfmQN3tYdr5Kc7OoRb0HqK11tc1grGZ1rDmSTQ6OFtqpzCiJyz2oH1BHA16WC2UbVftw==</P><Q>8nherC7UVWiuG8suixZtYL5CTK/CJVpf4GVrRZOb2slbL0sojgq7QQG5sZfQ4PIFHhfzgVM4uTkHNaFJUTv6ew==</Q><DP>zTNg8b0dHordVfAc9f9wb0XUOC+qV7QkN0P0otWtJV8RyhzNvkBvlwSO0KFyDLl8+b6yzNQ4JEoJhaDMwFuv8Q==</DP><DQ>rhlR2Q4y9jSYt2o3vDTZSpqyHkAhBhMTPptz39xyDzF/YMD1mLAJ7k5f2C2rFKmSlR4bgSORWiWhkJeDfmmzmw==</DQ><InverseQ>NLinNiXw75D8kOGhz2Z9hJR6tU0t1fuh9xVwAQSZomMFqTYEaGwekFIWA/7olAqR5b/oigGndS8F5L1tVDWqrg==</InverseQ><D>AmH+ExSI3KYpGEGrFgYME9FmPkICM3LKYCLvei4jAidYb2URjv8tKZs5wNCuvOTb8aT91IRXnsUOwHwDFwznwfcVwdIpW7m0Q/6Vu7GE3G1pzQOUynv+E9R8cdSl/m3lfNt8OJHNqnnR4MBoirerQargCZwDWY0nYlm6xBKIkME=</D></RSAKeyValue>");

            var dt1 = (new DateTime(2022, 01, 01)).ToString("yyyyMMdd");
            var dt2 = (new DateTime(2021, 02, 10)).ToString("yyyyMMdd");

            var dt1Sign = rsau.SignData(dt1);
            var dt2Sigh = rsau.SignData(dt2);

            Console.WriteLine($"1: {dt1}:{dt1Sign}");
            Console.WriteLine($"2: {dt2}:{dt2Sigh}");

            var rsau2 = new RsaUtils();

            rsau2.SetKeys(@"<RSAKeyValue><Modulus>2OO32RsAa73GjFw171YUkwOTyguKeT3N1zjAZY04/f4TdpRABfNBs1aHICepzhQ1gy1TBnYX3K95b+qD7u6CczU65JzormbqlgY1rweG+HNwGcn36g0M66k7qwfFSjZhbmlGTvedD7xo4L/pSf91p7KwjzLt6ac8+UAdqVfKsu0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");

            Assert.IsTrue(rsau2.CheckSign(dt1, dt1Sign));
            Assert.IsTrue(rsau2.CheckSign(dt2, dt2Sigh));
        }
예제 #14
0
 /// <summary>Check if the encryption 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 DidEncryption(HttpPostedFileBase file, HttpPostedFileBase key, ref string error, ref string path)
 {
     if (fileUtils.IsFileTypeCorrect(file, ".txt", 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.Encrypt(uploadedFile, uploadedKey, ref path))
         {
             return(true);
         }
         else
         {
             error = "Bad Encryption";
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
예제 #15
0
        /// <summary>
        /// Returns the cipher text block size for key in the specified certificate.
        /// </summary>
        protected int GetCipherTextBlockSize(X509Certificate2 receiverCertificate)
        {
            switch (SecurityPolicyUri)
            {
            case SecurityPolicies.Basic256:
            case SecurityPolicies.Basic256Sha256:
            {
                return(RsaUtils.GetCipherTextBlockSize(receiverCertificate, true));
            }

            case SecurityPolicies.Basic128Rsa15:
            {
                return(RsaUtils.GetCipherTextBlockSize(receiverCertificate, false));
            }

            default:
            case SecurityPolicies.None:
            {
                return(1);
            }
            }
        }
예제 #16
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);
        }
예제 #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext <AuthDbContext>(builder =>
            {
                builder.UseSqlite("Filename=./jwt.db");
            });
            string keyDir = PlatformServices.Default.Application.ApplicationBasePath;

            if (RsaUtils.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
            {
                keyParams = RsaUtils.GenerateAndSaveKey(keyDir);
            }
            _tokenOptions.Key         = new RsaSecurityKey(keyParams);
            _tokenOptions.Issuer      = "TestIssuer";
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);
            services.AddSingleton(_tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            });

            services.AddAuthentication().AddJwtBearer(jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = _tokenOptions.Key,
                    ValidAudience    = _tokenOptions.Audience,
                    ValidIssuer      = _tokenOptions.Issuer,
                    ValidateLifetime = true
                };
            });
            services.AddMvc();
        }
        public void SetField()
        {
            m_cli_cod.Text = "0";
            m_dst_cod.Text = "0";
            if (_cli != null)
            {
                m_cli_cod.Text     = _cli.cli_codice.ToString();
                cli_desc.Text      = _cli.cli_desc;
                cli_indirizzo.Text = _cli.cli_indirizzo;
                cli_citta.Text     = _cli.cli_citta;
            }
            else
            {
                m_cli_cod.Text     = "0";
                cli_desc.Text      = "";
                cli_indirizzo.Text = "";
                cli_citta.Text     = "";
            }
            if (_dst != null)
            {
                m_dst_cod.Text     = _dst.dst_codice.ToString();
                dst_desc.Text      = _dst.dst_desc;
                dst_indirizzo.Text = _dst.dst_indirizzo;
                dst_citta.Text     = _dst.dst_citta;
            }
            else
            {
                m_dst_cod.Text     = "0";
                dst_desc.Text      = "";
                dst_indirizzo.Text = "";
                dst_citta.Text     = "";
            }

            m_n_doc.Value     = RsaUtils.GetShowedNumDoc(_parent.doc.fat_n_doc);
            m_d_doc.Date      = _parent.doc.fat_d_doc;
            fat_registro.Text = _parent.doc.fat_registro;
        }
 /// <summary>
 /// Validates the cert and extracts the token from the cert.
 /// </summary>
 private static string CheckForToken(X509Certificate2 cert, string name)
 {
     if ((cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) &&
         (DateTime.Now < cert.NotAfter))
     {
         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));
                 }
             }
             RsaUtils.RSADispose(rsa);
         }
     }
     return(null);
 }
예제 #20
0
        /// <summary>
        /// Creates an RSA PKCS#1 v1.5 signature of a hash algorithm for the stream.
        /// </summary>
        private static byte[] RsaPkcs15_Sign(
            ArraySegment <byte> dataToSign,
            X509Certificate2 signingCertificate,
            HashAlgorithmName algorithm)
        {
            RSA rsa = null;

            try
            {
                // extract the private key.
                rsa = signingCertificate.GetRSAPrivateKey();
                if (rsa == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate.");
                }

                // create the signature.
                return(rsa.SignData(dataToSign.Array, dataToSign.Offset, dataToSign.Count, algorithm, RSASignaturePadding.Pkcs1));
            }
            finally
            {
                RsaUtils.RSADispose(rsa);
            }
        }
예제 #21
0
        public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey)
        {
            //From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample
            var jweHeader = new JsonObject
            {
                { "alg", "RSA-OAEP" },
                { "enc", "A128CBC-HS256" },
                { "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0, 3) },
            };

            var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe();

            var authKey          = new byte[128 / 8];
            var cryptKey         = new byte[128 / 8];
            var cryptAuthKeys256 = AesUtils.CreateKey();

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

            var aes = Aes.Create();

            aes.KeySize   = 128;
            aes.BlockSize = 128;
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            using (aes)
            {
                aes.GenerateIV();
                var iv = aes.IV;
                aes.Key = cryptKey;

                var jweEncKey          = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength);
                var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe();
                var ivBase64Url        = iv.ToBase64UrlSafe();

                var aad          = jweHeaderBase64Url + "." + jweEncKeyBase64Url;
                var aadBytes     = aad.ToUtf8Bytes();
                var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes();

                using (var cipherStream = MemoryStreamFactory.GetStream())
                    using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var writer = new BinaryWriter(cryptoStream))
                            {
                                writer.Write(payloadBytes);
                                cryptoStream.FlushFinalBlock();

                                using (var hmac = new HMACSHA256(authKey))
                                    using (var encryptedStream = MemoryStreamFactory.GetStream())
                                        using (var bw = new BinaryWriter(encryptedStream))
                                        {
                                            bw.Write(aadBytes);
                                            bw.Write(iv);
                                            bw.Write(cipherStream.GetBuffer(), 0, (int)cipherStream.Length);
                                            bw.Flush();

                                            var tag = hmac.ComputeHash(encryptedStream.GetBuffer(), 0, (int)encryptedStream.Length);

                                            var cipherTextBase64Url = cipherStream.ToBase64UrlSafe();
                                            var tagBase64Url        = tag.ToBase64UrlSafe();

                                            var jweToken = jweHeaderBase64Url + "."
                                                           + jweEncKeyBase64Url + "."
                                                           + ivBase64Url + "."
                                                           + cipherTextBase64Url + "."
                                                           + tagBase64Url;

                                            return(jweToken);
                                        }
                            }
            }
        }
예제 #22
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;
                }
            }
        }
예제 #23
0
        internal static async Task <string> DoRequest(string path,
                                                      string method,
                                                      Dictionary <string, object> param = null)
        {
            if (string.IsNullOrEmpty(ApiKey))
            {
                throw new PingppException("No API key provided.  (HINT: set your API key using "
                                          + "\"Pingpp::setApiKey(<API-KEY>)\".  You can generate API keys from "
                                          + "the Pingpp web interface.  See https://pingxx.com/document/api for "
                                          + "details.");
            }
            try {
                HttpContent httpContent = null;
                string      sign        = string.Empty;
                if (method.ToUpper() == "POST" || method.ToUpper() == "PUT")
                {
                    if (param == null)
                    {
                        throw new PingppException("Request params is empty");
                    }
                    string jsonBody = JsonConvert.SerializeObject(param, Formatting.Indented);

                    try {
                        sign = RsaUtils.RsaSign(jsonBody, PrivateKey);
                    } catch (System.Exception e) {
                        throw new PingppException("Sign request error." + e.Message);
                    }

                    httpContent = new StringContent(jsonBody);
                    httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
                }

                HttpClient          req;
                HttpResponseMessage res;
                method = method.ToUpper();
                switch (method)
                {
                case "GET":
                    req = GetRequest("");
                    using (res = await req.GetAsync(path)) {
                        return(await res.Content.ReadAsStringAsync());
                    }

                case "DELETE":
                    req = GetRequest("");
                    using (res = await req.DeleteAsync(path)) {
                        return(await res.Content.ReadAsStringAsync());
                    }

                case "POST":
                    req = GetRequest(sign);
                    using (res = await req.PostAsync(path, httpContent)) {
                        return(await res.Content.ReadAsStringAsync());
                    }

                case "PUT":
                    req = GetRequest(sign);
                    using (res = await req.PutAsync(path, httpContent)) {
                        return(await res.Content.ReadAsStringAsync());
                    }

                default: return(null);
                }
            } catch (WebException e) {
                if (e.Response == null)
                {
                    throw new WebException(e.Message);
                }
                var statusCode = ((HttpWebResponse)e.Response).StatusCode;
                var errors     = Mapper <Error> .MapFromJson(ReadStream(e.Response.GetResponseStream()), "error");

                throw new PingppException(errors, statusCode, errors.ErrorType, errors.Message);
            }
        }
        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;
                }
            }
        }
예제 #25
0
 public void Generate_new_Key()
 {
     RsaUtils.CreatePrivateKeyParams().ToPrivateKeyXml().Replace("\"", "\\\"").Print();
 }
예제 #26
0
        /// <summary>
        /// Decrypts the message using RSA PKCS#1 v1.5 encryption.
        /// </summary>
        private ArraySegment <byte> Rsa_Decrypt(
            ArraySegment <byte> dataToDecrypt,
            ArraySegment <byte> headerToCopy,
            X509Certificate2 encryptingCertificate,
            bool useOaep)
        {
            RSA rsa = null;

            try
            {
                // get the encrypting key.
                rsa = encryptingCertificate.GetRSAPrivateKey();
                if (rsa == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate.");
                }

                int inputBlockSize  = RsaUtils.GetCipherTextBlockSize(rsa, useOaep);
                int outputBlockSize = RsaUtils.GetPlainTextBlockSize(rsa, useOaep);

                // verify the input data is the correct block size.
                if (dataToDecrypt.Count % inputBlockSize != 0)
                {
                    Utils.Trace("Message is not an integral multiple of the block size. Length = {0}, BlockSize = {1}.", dataToDecrypt.Count, inputBlockSize);
                }

                byte[] decryptedBuffer = BufferManager.TakeBuffer(SendBufferSize, "Rsa_Decrypt");
                Array.Copy(headerToCopy.Array, headerToCopy.Offset, decryptedBuffer, 0, headerToCopy.Count);

                using (MemoryStream ostrm = new MemoryStream(
                           decryptedBuffer,
                           headerToCopy.Count,
                           decryptedBuffer.Length - headerToCopy.Count))
                {
                    // decrypt body.
                    byte[] input = new byte[inputBlockSize];

                    for (int ii = dataToDecrypt.Offset; ii < dataToDecrypt.Offset + dataToDecrypt.Count; ii += inputBlockSize)
                    {
                        Array.Copy(dataToDecrypt.Array, ii, input, 0, input.Length);
                        if (useOaep == true)
                        {
                            byte[] plainText = rsa.Decrypt(input, RSAEncryptionPadding.OaepSHA1);
                            ostrm.Write(plainText, 0, plainText.Length);
                        }
                        else
                        {
                            byte[] plainText = rsa.Decrypt(input, RSAEncryptionPadding.Pkcs1);
                            ostrm.Write(plainText, 0, plainText.Length);
                        }
                    }
                }

                // return buffers.
                return(new ArraySegment <byte>(decryptedBuffer, 0, (dataToDecrypt.Count / inputBlockSize) * outputBlockSize + headerToCopy.Count));
            }
            finally
            {
                RsaUtils.RSADispose(rsa);
            }
        }
예제 #27
0
        /// <summary>
        /// 个性化配置
        /// 用户初始化服务器需要的IOC资源
        /// </summary>
        public override void Configure(Container container)
        {
            //注册模板页面
            SetConfig(new HostConfig
            {
                //调试模式
                DebugMode = AppSettings.Get("DebugMode", false),
                ////隐藏metadata page页面
                //EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //没有登录可以使用?authsecret=xxx方式,和登录效果一致
                AdminAuthSecret = AppSettings.Get("AdminAuthSecret", "secretz"),
                //注册网页根目录
                //WebHostPhysicalPath = MapProjectPath("~/my-project/dist"),
                //WebHostPhysicalPath = MapProjectPath("~/wwwroot"),
                AddRedirectParamsToQueryString = true,
                //UseCamelCase = true,
                //注册接口服务地址
                HandlerFactoryPath = "api",
                DefaultContentType = MimeTypes.Json,
            });
            //注册测试页
            Plugins.Add(new TemplatePagesFeature());

            Plugins.Add(new AdminFeature());

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

            //Plugins.Add(new BasicAuthFeature());

            //添加一个request filter 确认用户的登录session
            //this.GlobalRequestFilters.Add((req, res, requestDto) =>
            //{
            //    if (!req.GetSession().IsAuthenticated)
            //    {
            //        res.ReturnAuthRequired();
            //    }
            //});

            //container.Register<IAuthProvider>(r => new myAuthProvider());


            //获取连接字符串
            var connectionString = ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString;

            //注册数据库连接工厂
            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
            //注册数据库连接
            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = true
            });
            //获取用户表的数据库连接,如果没有生成表则自动生成
            container.Resolve <IAuthRepository>().InitSchema();


            //Also store User Sessions in SQL Server
            container.RegisterAs <OrmLiteCacheClient, ICacheClient>();
            container.Resolve <ICacheClient>().InitSchema();


            //获取数据库的配置连接
            //container.Register<IAppSettings>(c => new OrmLiteAppSettings(c.Resolve<IDbConnectionFactory>()));

            //container.Register<IAppSettings>(c => new AppSettings());
            //获取配置
            //var appsetting = (AppSettings)container.Resolve<IAppSettings>();
            //初始化数据表
            //appsetting.InitSchema();

            //appsetting.Get("test", "test");

            var privateKey   = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048);
            var publicKeyXml = privateKey.ToPublicKeyXml();


            //所有需要用账号访问的方法,都会调用认证界面CustomUserSession,myAuthProvider为自定义的方法
            //Add Support for
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                    AllowInQueryString      = true,
                    SessionExpiry           = TimeSpan.FromDays(1),
                    //RedirectUrl = "www.baidu.com",
                    ExpireRefreshTokensIn = TimeSpan.FromDays(1),
                    ExpireTokensIn        = TimeSpan.FromDays(100),
                    CreatePayloadFilter   = (payload, session) =>
                    {
                        if (session.IsAuthenticated)
                        {
                            payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString();
                            payload["exp"]       = DateTime.UtcNow.AddYears(1).ToUnixTime().ToString();
                        }
                    },

                    //AuthKeyBase64 = "Base64AuthKey",//AppSettings.GetString("AuthKeyBase64") //"Base64AuthKey",
                    //HashAlgorithm = "RS256",
                    //PrivateKeyXml ="PrivateKey2016Xml", //AppSettings.GetString("PrivateKeyXml")
                },
                new ApiKeyAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    ExpireKeysAfter         = TimeSpan.FromDays(100),
                    SessionCacheDuration    = TimeSpan.FromMinutes(10),
                    InitSchema        = true,
                    AllowInHttpParams = true,
                    //KeyTypes = new[] { "secret", "publishable" },
                },                             //Sign-in with API Key
                new CredentialsAuthProvider(), //Sign-in with UserName/Password credentials
                new BasicAuthProvider(),       //Sign-in with HTTP Basic Auth
            })
            {
                IncludeRegistrationService   = true,
                IncludeAssignRoleServices    = true,
                IncludeAuthMetadataProvider  = true,
                ValidateUniqueEmails         = true,
                ValidateUniqueUserNames      = true,
                DeleteSessionCookiesOnLogout = true,
                SaveUserNamesInLowerCase     = true,
                GenerateNewSessionCookiesOnAuthentication = true,
            });

            //Default route: /register
            //Plugins.Add(new RegistrationFeature() { AllowUpdates = true });
            ////The IAuthRepository is used to store the user credentials etc.
            ////Implement this interface to adjust it to your app's data storage



            //CreateUser(10, "jinchaoqian1", "*****@*****.**", "j4012693", new List<string> { "TheRole" }, new List<string> { "ThePermission" });

            //记录日志
            LogManager.LogFactory = new MyLoggerFactory();
            //启用日志
            Plugins.Add(new RequestLogsFeature()
            {
                EnableRequestBodyTracking = true,
                EnableResponseTracking    = true,
                EnableSessionTracking     = true,
                EnableErrorTracking       = true,
            });
            //启用跨域访问
            this.Plugins.Add(new CorsFeature(allowedMethods: "GET, POST"));
            //注册Swagger插件进行API的Web调试
            Plugins.Add(new SwaggerFeature());
            //启用验证插件
            Plugins.Add(new ValidationFeature());
            //注册验证插件
            container.RegisterValidators(typeof(LoginValidator).Assembly);
            ////自动扫描验证插件
            //Plugins.Add(new ValidationFeature
            //{
            //    ScanAppHostAssemblies = true
            //});


            //JsConfig.EmitLowercaseUnderscoreNames = true;
            //JsConfig.ExcludeDefaultValues = true;
            //序列化时的日期格式
            JsConfig <DateTime> .SerializeFn = dateTime => dateTime.ToString("yyyy-MM-dd");
            JsConfig <TimeSpan> .SerializeFn = time =>
                                               (time.Ticks < 0 ? "-" : "") + time.ToString("hh':'mm':'ss'.'fffffff");

            //container.Register<ICacheClient>(c => new OrmLiteCacheClient(){DbFactory = c.Resolve<IDbConnectionFactory>()});

            //var cache = container.Resolve<OrmLiteCacheClient>();
            //cache.DbFactory = container.Resolve<IDbConnectionFactory>();

            //container.RegisterAs<OrmLiteCacheClient, ICacheClient>();

            ////Create 'CacheEntry' RDBMS table if it doesn't exist already
            //container.Resolve<ICacheClient>().InitSchema();

            container.Register <ICacheClient>(new MemoryCacheClient());



            //虚拟目录,使用插件方式或者是重载GetVirtualFileSources
            //Plugins.Add(new Disk1Plugin());

            //捕捉到被处理过的错误
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                //记录错误信息
                //TODO:
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return(null); //返回默认错误

                //或者自定义错误
                //return DtoUtils.CreateErrorResponse(request, exception);
            });

            //处理未被系统处理的错误
            //E.g. Exceptions during Request binding or in filters:
            this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
            {
                res.WriteAsync($"Error: {ex.GetType().Name}: {ex.Message}");
                res.EndRequest(skipHeaders: true);
            });

            AfterInitCallbacks.Add(host =>
            {
                var authProvider = (ApiKeyAuthProvider)
                                   AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                using (var db = host.TryResolve <IDbConnectionFactory>().Open())
                {
                    var userWithKeysIds = db.Column <string>(db.From <ApiKey>()
                                                             .SelectDistinct(x => x.UserAuthId)).Map(int.Parse);

                    var userIdsMissingKeys = db.Column <string>(db.From <UserAuth>()
                                                                .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id))
                                                                .Select(x => x.Id));

                    var authRepo = (IManageApiKeys)host.TryResolve <IAuthRepository>();
                    foreach (var userId in userIdsMissingKeys)
                    {
                        var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString());
                        authRepo.StoreAll(apiKeys);
                    }
                }
            });
        }
예제 #28
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);
        }
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom            random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();

            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();

            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA              rsa       = RSA.Create();
            RSAParameters    rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    RsaUtils.RSADispose(rsa);
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }
            RsaUtils.RSADispose(rsa);

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store            pkcsStore = builder.Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                case CertificateStoreType.Directory:
                {
                    // Add to DirectoryStore
                    using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        X509CertificateCollection certificates = await store.Enumerate();

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                await store.Delete(cert.Thumbprint);
                            }
                        }

                        // add new one
                        await store.Add(certificate);
                    }
                    break;
                }

                case CertificateStoreType.X509Store:
                {
                    // Add to X509Store
                    using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                    {
                        store.Open(OpenFlags.ReadWrite);

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                store.Remove(cert);
                            }
                        }

                        // add new cert to store
                        try
                        {
                            store.Add(certificate);
                        }
                        catch (Exception e)
                        {
                            throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                        }
                    }
                    break;
                }

                default:
                {
                    throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                }
                }
                return;
            }
        }
예제 #30
0
        internal static string DoRequest(string path, string method, Dictionary <string, object> param = null, bool isValidateUri = true)
        {
            if (string.IsNullOrEmpty(ApiKey))
            {
                throw new PingppException("No API key provided.  (HINT: set your API key using " +
                                          "\"Pingpp::setApiKey(<API-KEY>)\".  You can generate API keys from " +
                                          "the Pingpp web interface.  See https://pingxx.com/document/api for " +
                                          "details.");
            }
            try
            {
                HttpWebRequest  req;
                HttpWebResponse res;
                method = method.ToUpper();
                string body = "", sign = "";
                string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                if ((method.Equals("POST") || method.Equals("PUT")) && param != null)
                {
                    body = JsonConvert.SerializeObject(param, Formatting.Indented);
                }

                // Sign the request
                try
                {
                    if (PrivateKey != null)
                    {
                        var uri = isValidateUri ? path : "";
                        sign = RsaUtils.RsaSign(body + uri + timestamp, PrivateKey);
                    }
                }
                catch (System.Exception e)
                {
                    throw new PingppException("Sign request error." + e.Message);
                }

                req = GetRequest(path, method, timestamp, sign);
                if (method.Equals("POST") || method.Equals("PUT"))
                {
                    using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                    {
                        streamWriter.Write(body);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }
                using (res = req.GetResponse() as HttpWebResponse)
                {
                    return(res == null ? null : ReadStream(res.GetResponseStream()));
                }
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw new WebException(e.Message);
                }
                var statusCode = ((HttpWebResponse)e.Response).StatusCode;
                if ((int)statusCode == 502 && BadGateWayMatch && MaxRetry < MaxNetworkRetries)
                {
                    MaxRetry++;
                    DoRequest(path, method, param, isValidateUri);
                }
                var errors = Mapper <Error> .MapFromJson(ReadStream(e.Response.GetResponseStream()), "error");

                throw new PingppException(errors, statusCode, errors.ErrorType, errors.Message);
            }
        }