/// <summary>
        /// Tries to sign and verify a bit of test data using the given certificate.
        /// This will cause the security subsystem to grant the calling app access
        /// to the certificate's private key for the current session.
        ///
        /// </summary>
        /// <param name="selectedCertificate">The X.509 Certificate for which access is required</param>
        /// <returns>True on successful signing and verification, false otherwise.</returns>
        private static bool VerifyCertificateKeyAccess(Certificate selectedCertificate)
        {
            bool VerifyResult = false;              // default to access failure
            var  keyPairTask  = PersistedKeyProvider.OpenKeyPairFromCertificateAsync(
                selectedCertificate, HashAlgorithmNames.Sha1,
                CryptographicPadding.RsaPkcs1V15).AsTask();

            keyPairTask.Wait();
            CryptographicKey keyPair = keyPairTask.Result;
            String           buffer  = "Data to sign";
            IBuffer          Data    = CryptographicBuffer.ConvertStringToBinary(buffer, BinaryStringEncoding.Utf16BE);

            try
            {
                // sign the data by using the key
                var signedDataTask = CryptographicEngine.SignAsync(keyPair, Data).AsTask();
                signedDataTask.Wait();
                IBuffer Signed = signedDataTask.Result;
                VerifyResult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);
            }
            catch (Exception exp)
            {
                Debug.WriteLine("Verification Failed. Exception Occurred : {0}", exp.Message);
                // default result is false so drop through to exit.
            }

            return(VerifyResult);
        }
        public static async Task <string> CreateDeviceAuthChallengeResponseAsync(IDictionary <string, string> challengeData)
        {
            string      authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";
            Certificate certificate        = null;

            try
            {
                certificate = await FindCertificate(challengeData).ConfigureAwait(false);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.DeviceCertificateNotFound)
                {
                    return(await Task.FromResult(string.Format(CultureInfo.InvariantCulture, @"PKeyAuth Context=""{0}"",Version=""{1}""", challengeData["Context"], challengeData["Version"])).ConfigureAwait(false));
                }
            }
            DeviceAuthJWTResponse response = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                       challengeData["nonce"], Convert.ToBase64String(certificate.GetCertificateBlob().ToArray()));
            IBuffer input = CryptographicBuffer.ConvertStringToBinary(response.GetResponseToSign(),
                                                                      BinaryStringEncoding.Utf8);
            CryptographicKey keyPair = await
                                       PersistedKeyProvider.OpenKeyPairFromCertificateAsync(certificate, HashAlgorithmNames.Sha256,
                                                                                            CryptographicPadding.RsaPkcs1V15).AsTask().ConfigureAwait(false);

            IBuffer signed = await CryptographicEngine.SignAsync(keyPair, input).AsTask().ConfigureAwait(false);

            string signedJwt = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", response.GetResponseToSign(),
                                             Base64UrlEncoder.Encode(signed.ToArray()));
            string authToken = string.Format(CultureInfo.InvariantCulture, " AuthToken=\"{0}\"", signedJwt);

            return(string.Format(CultureInfo.InvariantCulture, authHeaderTemplate, authToken, challengeData["Context"], challengeData["Version"]));
        }
示例#3
0
        public static async Task <bool> VerifyCertificateKeyAccess(Certificate selectedCertificate)
        {
            bool             VerifyResult = false; // default to access failure
            CryptographicKey keyPair      = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(
                selectedCertificate, HashAlgorithmNames.Sha1,
                CryptographicPadding.RsaPkcs1V15);

            String  buffer = "Data to sign";
            IBuffer Data   = CryptographicBuffer.ConvertStringToBinary(buffer, BinaryStringEncoding.Utf16BE);

            try
            {
                //sign the data by using the key
                IBuffer Signed = await CryptographicEngine.SignAsync(keyPair, Data);

                VerifyResult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("Verification Failed. Exception Occurred : {0}", exp.Message);
                // default result is false so drop through to exit.
            }

            return(VerifyResult);
        }
        public bool TryCreateDeviceAuthChallengeResponseAsync(HttpResponseHeaders headers, Uri endpointUri, out string responseHeader)
        {
            responseHeader = string.Empty;
            Certificate certificate        = null;
            string      authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";

            if (!DeviceAuthHelper.IsDeviceAuthChallenge(headers))
            {
                return(false);
            }
            if (!DeviceAuthHelper.CanOSPerformPKeyAuth())
            {
                responseHeader = DeviceAuthHelper.GetBypassChallengeResponse(headers);
                return(false);
            }

            IDictionary <string, string> challengeData = DeviceAuthHelper.ParseChallengeData(headers);

            if (!challengeData.ContainsKey("SubmitUrl"))
            {
                challengeData["SubmitUrl"] = endpointUri.AbsoluteUri;
            }

            try
            {
                certificate = Task.FromResult(FindCertificateAsync(challengeData)).Result.Result;
            }
            catch (MsalException ex)
            {
                if (ex.ErrorCode == MsalError.DeviceCertificateNotFound)
                {
                    responseHeader = DeviceAuthHelper.GetBypassChallengeResponse(headers);
                    return(true);
                }
            }

            DeviceAuthJWTResponse responseJWT = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                          challengeData["nonce"], Convert.ToBase64String(certificate.GetCertificateBlob().ToArray()));
            IBuffer input = CryptographicBuffer.ConvertStringToBinary(responseJWT.GetResponseToSign(),
                                                                      BinaryStringEncoding.Utf8);
            CryptographicKey keyPair =
                Task.FromResult(PersistedKeyProvider.OpenKeyPairFromCertificateAsync(certificate, HashAlgorithmNames.Sha256, CryptographicPadding.RsaPkcs1V15)).Result.GetResults();

            IBuffer signed = Task.FromResult(CryptographicEngine.SignAsync(keyPair, input)).Result.GetResults();

            string signedJwt = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", responseJWT.GetResponseToSign(),
                                             Base64UrlHelpers.Encode(signed.ToArray()));
            string authToken = string.Format(CultureInfo.InvariantCulture, " AuthToken=\"{0}\"", signedJwt);

            responseHeader = string.Format(CultureInfo.InvariantCulture, authHeaderTemplate, authToken, challengeData["Context"], challengeData["Version"]);
            return(true);
        }
示例#5
0
        public async Task <string> CreateDeviceAuthChallengeResponse(IDictionary <string, string> challengeData)
        {
            string authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";

            Certificate certificate = await FindCertificate(challengeData);

            DeviceAuthJWTResponse response = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                       challengeData["nonce"], Convert.ToBase64String(certificate.GetCertificateBlob().ToArray()));
            IBuffer input = CryptographicBuffer.ConvertStringToBinary(response.GetResponseToSign(),
                                                                      BinaryStringEncoding.Utf8);
            CryptographicKey keyPair = await
                                       PersistedKeyProvider.OpenKeyPairFromCertificateAsync(certificate, HashAlgorithmNames.Sha256,
                                                                                            CryptographicPadding.RsaPkcs1V15);

            IBuffer signed = await CryptographicEngine.SignAsync(keyPair, input);

            string signedJwt = string.Format(CultureInfo.CurrentCulture, "{0}.{1}", response.GetResponseToSign(),
                                             Base64UrlEncoder.Encode(signed.ToArray()));
            string authToken = string.Format(CultureInfo.CurrentCulture, " AuthToken=\"{0}\"", signedJwt);

            return(string.Format(authHeaderTemplate, authToken, challengeData["Context"], challengeData["Version"]));
        }