Inheritance: ICryptographyHelper
        internal static void SetCacheValue(IPropertySet containerValues, byte[] value)
        {
            byte[] encryptedValue = CryptographyHelper.Encrypt(value);
            containerValues[CacheValueLength] = encryptedValue.Length;
            if (encryptedValue.Length == 0)
            {
                containerValues[CacheValueSegmentCount] = 1;
                containerValues[CacheValue + 0]         = null;
            }
            else
            {
                int    segmentCount = (encryptedValue.Length / MaxCompositeValueLength) + ((encryptedValue.Length % MaxCompositeValueLength == 0) ? 0 : 1);
                byte[] subValue     = new byte[MaxCompositeValueLength];
                for (int i = 0; i < segmentCount - 1; i++)
                {
                    Array.Copy(encryptedValue, i * MaxCompositeValueLength, subValue, 0, MaxCompositeValueLength);
                    containerValues[CacheValue + i] = subValue;
                }

                int copiedLength = (segmentCount - 1) * MaxCompositeValueLength;
                Array.Copy(encryptedValue, copiedLength, subValue, 0, encryptedValue.Length - copiedLength);
                containerValues[CacheValue + (segmentCount - 1)] = subValue;
                containerValues[CacheValueSegmentCount]          = segmentCount;
            }
        }
Example #2
0
        public async Task <string> CreateDeviceAuthChallengeResponse(IDictionary <string, string> challengeData)
        {
            string authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";

            X509Certificate2      certificate = FindCertificate(challengeData);
            DeviceAuthJWTResponse response    = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                          challengeData["nonce"], Convert.ToBase64String(certificate.GetRawCertData()));
            CngKey key = CryptographyHelper.GetCngPrivateKey(certificate);

            byte[] sig = null;
            using (RSACng rsa = new RSACng(key))
            {
                rsa.SignatureHashAlgorithm = CngAlgorithm.Sha256;
                sig = rsa.SignData(response.GetResponseToSign().ToByteArray());
            }

            string signedJwt = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", response.GetResponseToSign(),
                                             Base64UrlEncoder.Encode(sig));
            string        authToken  = string.Format(CultureInfo.InvariantCulture, " AuthToken=\"{0}\"", signedJwt);
            Task <string> resultTask =
                Task.Factory.StartNew(
                    () =>
            {
                return(string.Format(CultureInfo.InvariantCulture, authHeaderTemplate, authToken, challengeData["Context"],
                                     challengeData["Version"]));
            });

            return(await resultTask.ConfigureAwait(false));
        }
        internal static byte[] GetCacheValue(IPropertySet containerValues)
        {
            if (!containerValues.ContainsKey(CacheValueLength))
            {
                return(null);
            }

            int encyptedValueLength = (int)containerValues[CacheValueLength];
            int segmentCount        = (int)containerValues[CacheValueSegmentCount];

            byte[] encryptedValue = new byte[encyptedValueLength];
            if (segmentCount == 1)
            {
                encryptedValue = (byte[])containerValues[CacheValue + 0];
            }
            else
            {
                for (int i = 0; i < segmentCount - 1; i++)
                {
                    Array.Copy((byte[])containerValues[CacheValue + i], 0, encryptedValue, i * MaxCompositeValueLength, MaxCompositeValueLength);
                }
            }

            Array.Copy((byte[])containerValues[CacheValue + (segmentCount - 1)], 0, encryptedValue, (segmentCount - 1) * MaxCompositeValueLength, encyptedValueLength - (segmentCount - 1) * MaxCompositeValueLength);
            return(CryptographyHelper.Decrypt(encryptedValue));
        }
 public static void CreateSha256HashTest()
 {
     ICryptographyHelper cryptoHelper = new CryptographyHelper();
     string hash = cryptoHelper.CreateSha256Hash("abc");
     string hash2 = cryptoHelper.CreateSha256Hash("abd");
     string hash3 = cryptoHelper.CreateSha256Hash("abc");
     Verify.AreEqual(hash, hash3);
     Verify.AreNotEqual(hash, hash2);
     Verify.AreEqual(hash, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=");
 }
Example #5
0
        private void LogReturnedToken(AuthenticationResult result)
        {
            if (result.AccessToken != null)
            {
                string accessTokenHash = CryptographyHelper.CreateSha256Hash(result.AccessToken);

                CallState.Logger.Information(this.CallState,
                                             string.Format(CultureInfo.CurrentCulture,
                                                           "=== Token Acquisition finished successfully. An access token was retuned:\n\tAccess Token Hash: {0}\n\tExpiration Time: {1}\n\tUser Hash: {2}\n\t",
                                                           accessTokenHash,
                                                           result.ExpiresOn,
                                                           result.UserInfo != null
                            ? CryptographyHelper.CreateSha256Hash(result.UserInfo.UniqueId)
                            : "null"));
            }
        }
Example #6
0
        private AuthenticationResultEx ResultFromBrokerResponse(IDictionary <string, string> responseDictionary)
        {
            TokenResponse response;

            if (responseDictionary.ContainsKey("error") || responseDictionary.ContainsKey("error_description"))
            {
                response = TokenResponse.CreateFromBrokerResponse(responseDictionary);
            }
            else
            {
                string expectedHash       = responseDictionary["hash"];
                string encryptedResponse  = responseDictionary["response"];
                string decryptedResponse  = BrokerKeyHelper.DecryptBrokerResponse(encryptedResponse);
                string responseActualHash = CryptographyHelper.CreateSha256Hash(decryptedResponse);
                byte[] rawHash            = Convert.FromBase64String(responseActualHash);
                string hash = BitConverter.ToString(rawHash);
                if (expectedHash.Equals(hash.Replace("-", "")))
                {
                    responseDictionary = EncodingHelper.ParseKeyValueList(decryptedResponse, '&', false, null);
                    response           = TokenResponse.CreateFromBrokerResponse(responseDictionary);
                }
                else
                {
                    response = new TokenResponse
                    {
                        Error            = AdalError.BrokerReponseHashMismatch,
                        ErrorDescription = AdalErrorMessage.BrokerReponseHashMismatch
                    };
                }
            }

            var dateTimeOffset = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));

            dateTimeOffset = dateTimeOffset.AddSeconds(response.ExpiresOn);
            return(response.GetResult(dateTimeOffset, dateTimeOffset));
        }
        public void SignWithCertificateTest()
        {
            const string Message = "This is a test message";
            string[] certs = { "valid_cert.pfx", "valid_cert2.pfx" };
            for (int i = 0; i < 2; i++)
            {
                X509Certificate2 x509Certificate = new X509Certificate2(certs[i], "password", X509KeyStorageFlags.Exportable);
                byte[] rawData = x509Certificate.Export(X509ContentType.Pkcs12, "password");

                ICryptographyHelper cryptoHelper = new CryptographyHelper();
                byte[] signature = cryptoHelper.SignWithCertificate(Message, rawData, "password");
                Verify.IsNotNull(signature);

                GC.Collect();
                GC.WaitForPendingFinalizers();

                signature = cryptoHelper.SignWithCertificate(Message, rawData, "password");
                Verify.IsNotNull(signature);
            }
        }
        /// <summary>
        /// Signs a message using the private key in the certificate
        /// </summary>
        /// <param name="message">Message that needs to be signed</param>
        /// <returns>Signed message as a byte array</returns>
        public byte[] Sign(string message)
        {
            CryptographyHelper helper = new CryptographyHelper();

            return(helper.SignWithCertificate(message, this.Certificate));
        }
        protected override async Task PreRunAsync()
        {
            await base.PreRunAsync().ConfigureAwait(false);

            if (this.userCredential != null)
            {
                if (string.IsNullOrWhiteSpace(this.userCredential.UserName))
                {
                    this.userCredential.UserName = await platformInformation.GetUserPrincipalNameAsync().ConfigureAwait(false);

                    if (string.IsNullOrWhiteSpace(userCredential.UserName))
                    {
                        CallState.Logger.Information(this.CallState, "Could not find UPN for logged in user");
                        throw new AdalException(AdalError.UnknownUser);
                    }

                    CallState.Logger.Verbose(this.CallState, string.Format(CultureInfo.CurrentCulture, " Logged in user with hash '{0}' detected", CryptographyHelper.CreateSha256Hash(userCredential.UserName)));
                }

                this.DisplayableId = userCredential.UserName;
            }
            else if (this.userAssertion != null)
            {
                this.DisplayableId = userAssertion.UserName;
            }
        }
        protected override async Task PreTokenRequest()
        {
            await base.PreTokenRequest().ConfigureAwait(false);

            if (this.PerformUserRealmDiscovery())
            {
                UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState).ConfigureAwait(false);

                CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " User with hash '{0}' detected as '{1}'", CryptographyHelper.CreateSha256Hash(this.userCredential.UserName), userRealmResponse.AccountType));

                if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl))
                    {
                        throw new AdalException(AdalError.MissingFederationMetadataUrl);
                    }

                    WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState).ConfigureAwait(false);

                    CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl));

                    WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState, userRealmResponse.CloudAudienceUrn).ConfigureAwait(false);

                    CallState.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType));

                    // We assume that if the response token type is not SAML 1.1, it is SAML 2
                    this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
                }
                else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // handle password grant flow for the managed user
                    if (this.userCredential.PasswordToCharArray() == null)
                    {
                        throw new AdalException(AdalError.PasswordRequiredForManagedUserError);
                    }
                }
                else
                {
                    throw new AdalException(AdalError.UnknownUserType);
                }
            }
        }
 internal byte[] Sign(string message)
 {
     return(CryptographyHelper.SignWithCertificate(message, this.Certificate));
 }