public string Get() { var stopwatch = new Stopwatch(); stopwatch.Start(); var hashingKey = new byte[32]; var encryptionKey = new byte[32]; using (var provider = new RNGCryptoServiceProvider()) { provider.GetBytes(hashingKey); provider.GetBytes(encryptionKey); } var nonceGenerator = new NonceGenerator(); nonceGenerator.Execute(); var armorToken = new ArmorToken("*****@*****.**", "HMH", nonceGenerator.Nonce); var hash = new HashArmorTokenGenerationStep(new HMACSHA256HashingMechanismFactory(hashingKey), new EmptyArmorTokenGenerationStep()); var encrypt = new EncryptArmorTokenGenerationStep(new RijndaelEncryptionMechanismFactory(encryptionKey), hash); var serialise = new SerialiseArmorTokenGenerationStep(new ArmorTokenSerialisor(), encrypt); var armorTokenGenerator = new ArmorTokenGenerator(armorToken, serialise); armorTokenGenerator.Execute(); stopwatch.Stop(); Trace.WriteLine(string.Concat("Time: ", stopwatch.ElapsedMilliseconds)); return(armorTokenGenerator.ArmorToken); }
/// <summary> /// Initializes a new instance of the <see cref="SecurityHeadersMiddleware"/> class. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="service">An instance of <see cref="ICustomHeaderService"/>.</param> /// <param name="policies">A <see cref="HeaderPolicyCollection"/> containing the policies to be applied.</param> /// <param name="nonceGenerator">Used to generate nonce (number used once) values for headers</param> internal SecurityHeadersMiddleware(RequestDelegate next, ICustomHeaderService service, HeaderPolicyCollection policies, NonceGenerator nonceGenerator) { _next = next ?? throw new ArgumentNullException(nameof(next)); CustomHeaderService = service ?? throw new ArgumentNullException(nameof(service)); _policy = policies ?? throw new ArgumentNullException(nameof(policies)); _nonceGenerator = nonceGenerator ?? throw new ArgumentException(nameof(nonceGenerator)); }
/// <summary> /// Creates the HTTP Authorization header in hawk scheme. /// </summary> internal async Task CreateClientAuthorizationInternalAsync(IRequestMessage request, DateTime utcNow) { var credential = options.CredentialsCallback(); this.artifacts = new ArtifactsContainer() { Id = credential.Id, Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(), Nonce = NonceGenerator.Generate() }; if (options.NormalizationCallback != null) { this.artifacts.ApplicationSpecificData = options.NormalizationCallback(request); } var normalizedRequest = new NormalizedRequest(request, this.artifacts, options.HostNameSource); this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential); // Sign the request bool includePayloadHash = options.RequestPayloadHashabilityCallback != null && options.RequestPayloadHashabilityCallback(request); string payload = includePayloadHash ? await request.ReadBodyAsStringAsync() : null; crypto.Sign(payload, request.ContentType); request.Authorization = new AuthenticationHeaderValue(HawkConstants.Scheme, this.artifacts.ToAuthorizationHeaderParameter()); }
public void SignContext(OAuthContext context, TokenBase accessToken) { EnsureStateIsValid(); if (accessToken.ConsumerKey != ConsumerKey) { throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, accessToken.ConsumerKey); } var signer = new OAuthContextSigner(); var auth = new NonceGenerator(); context.UseAuthorizationHeader = UseHeaderForOAuthParameters; context.ConsumerKey = accessToken.ConsumerKey; context.Token = accessToken.Token; context.TokenSecret = accessToken.TokenSecret; context.SignatureMethod = SignatureMethod; context.Timestamp = DateTime.Now.EpocString(); context.Nonce = auth.GenerateNonce(); context.Version = "1.0"; string signatureBase = context.GenerateSignatureBase(); Console.WriteLine("signature_base: {0}", signatureBase); signer.SignContext(context, new SigningContext { Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret }); Console.WriteLine("oauth_singature: {0}", context.Signature); }
/// <summary> /// 生成授权token /// </summary> /// <returns>授权token</returns> string BuildAuthToken(string appKey) { string nonce = NonceGenerator.GenerateString(), appSecret = GetAppSecret(appKey); long timestamp = DateTime.Now.ToTimestamp(); // Sh1加密 List <string> list = new List <string>() { nonce, appSecret, timestamp.ToString() }; // 字典排序 list.Sort(); ICryptor cryptor = new Sha1Cryptor(); string signature = cryptor.Encrypt(string.Join(string.Empty, list)); AuthParameterModel auth = new AuthParameterModel { AppKey = appKey, Nonce = nonce, Timestamp = timestamp, Signature = signature }; string authJson = auth.SerializeObject(), token = authJson.ToBase64(); return(token); }
public async Task User_ClearingLfsTokenClearsHashedAsWell() { var database = new EditableInMemoryDatabaseFixture("UserClearApiToken"); var user = new User() { UserName = "******", Email = "*****@*****.**", LfsToken = NonceGenerator.GenerateNonce(32) }; await database.Database.Users.AddAsync(user); await database.Database.SaveChangesAsync(); Assert.NotNull(user.LfsToken); Assert.NotNull(user.HashedLfsToken); user.LfsToken = null; await database.Database.SaveChangesAsync(); Assert.Null(user.LfsToken); Assert.Null(user.HashedLfsToken); var searched = await database.Database.Users.FirstAsync(); Assert.Equal(user.Id, searched.Id); Assert.Null(searched.HashedLfsToken); }
public async Task <IActionResult> ConnectLauncher([Required] LauncherLinkCodeCheckForm request) { Response.ContentType = "application/json"; var user = await GetUserForNewLink(request.Code); // Update user to consume the code user.LauncherCodeExpires = DateTime.UtcNow - TimeSpan.FromSeconds(1); user.LauncherLinkCode = null; user.TotalLauncherLinks += 1; // Create a new code, which the user doesn't directly see to avoid it leaking as easily var code = NonceGenerator.GenerateNonce(42); var remoteAddress = HttpContext.Connection.RemoteIpAddress; await database.LauncherLinks.AddAsync(new LauncherLink() { User = user, LinkCode = code, LastIp = remoteAddress?.ToString(), LastConnection = DateTime.UtcNow }); await database.LogEntries.AddAsync(new LogEntry() { Message = $"New launcher link created from: {remoteAddress}", TargetUserId = user.Id }); await database.SaveChangesAsync(); logger.LogInformation("New launcher linked to user {Id} from {RemoteAddress}", user.Id, remoteAddress); return(Created(string.Empty, new LauncherLinkResult(true, code))); }
/// <summary> /// Creates the HTTP Authorization header in hawk scheme. /// </summary> internal async Task CreateClientAuthorizationInternalAsync(HttpRequestMessage request, DateTime utcNow) { var credential = credentialFunc(); this.artifacts = new ArtifactsContainer() { Id = credential.Id, Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(), Nonce = NonceGenerator.Generate() }; if (!String.IsNullOrWhiteSpace(this.ApplicationSpecificData)) { this.artifacts.ApplicationSpecificData = this.ApplicationSpecificData; } var normalizedRequest = new NormalizedRequest(request, this.artifacts); this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential); // Sign the request await crypto.SignAsync(request.Content); request.Headers.Authorization = new AuthenticationHeaderValue( HawkConstants.Scheme, this.artifacts.ToAuthorizationHeaderParameter()); }
public void Initial_Value_Should_Be_Correct() { var initial = 123UL; var nonce = new NonceGenerator(initial); Assert.Equal(initial, nonce.Next); }
public override TPMCommandResponse Process() { byte[] nonce = NonceGenerator.GenerateByteNonce(20); TPMBlob requestBlob = new TPMBlob(); requestBlob.WriteCmdHeader(TPMCmdTags.TPM_TAG_RQU_COMMAND, TPMOrdinals.TPM_ORD_ReadPubek); requestBlob.Write(nonce, 0, nonce.Length); requestBlob.WriteCmdSize(); TPMBlob responseBlob = TransmitMe(requestBlob); responseBlob.SkipHeader(); long posStart = responseBlob.Position; TPMPubkeyCore pubkey = TPMPubkeyCore.CreateFromTPMBlob(responseBlob); long posEnd = responseBlob.Position; Digest digest = new Digest(responseBlob, 20); if (digest.CompareTo( new HashStreamDataProvider(responseBlob, posStart, posEnd - posStart, false), new HashByteDataProvider(nonce)) == false) { throw new TPMResponseException("Local digest does not match remote digest"); } Parameters responseParams = new Parameters(); responseParams.AddValue(TPMPubkey.PARAM_TPM_PUBKEY, pubkey); return(new TPMCommandResponse(true, TPMCommandNames.TPM_CMD_ReadPubek, responseParams)); }
public bool TryFortify() { var identityReader = identityReaderFactory.Create(); IEnumerable<Claim> identity; var isAuthenticated = identityReader.TryRead(out identity); if (!isAuthenticated) return false; var claims = identity.ToList(); var userId = claims.Single(c => c.Type.Equals("UserId")).Value; var platform = claims.Single(c => c.Type.Equals("Platform")).Value; var encryptionKey = ArmorSettings.EncryptionKey; var hashingKey = ArmorSettings.HashingKey; var nonceGenerator = new NonceGenerator(); nonceGenerator.Execute(); var armorToken = new ArmorToken(userId, platform, nonceGenerator.Nonce); var armorTokenConstructor = new ArmorTokenConstructor(); var standardSecureArmorTokenBuilder = new StandardSecureArmorTokenBuilder(armorToken, encryptionKey, hashingKey); var generateSecureArmorToken = new GenerateSecureArmorToken(armorTokenConstructor, standardSecureArmorTokenBuilder); generateSecureArmorToken.Execute(); httpContext.Response.AppendHeader("ARMOR", generateSecureArmorToken.SecureArmorToken); return true; }
public void GenerateNonceTest() { var generator = new NonceGenerator(); var nonce = generator.Generate(); nonce.Should().NotBeNullOrEmpty(); nonce.Length.Should().Be(44); }
public void NextValues_Should_Be_Correct() { var nonceGenerator = new NonceGenerator(); Assert.Equal(0UL, nonceGenerator.Next); Assert.Equal(1UL, nonceGenerator.Next); Assert.Equal(2UL, nonceGenerator.Next); Assert.Equal(3UL, nonceGenerator.Next); }
public void GivenIHaveGeneratedRandomNumbers(int p0) { for (var i = 0; i < p0; i++) { var nonceGenerator = new NonceGenerator(); nonceGenerator.Execute(); nonces.Add(nonceGenerator.Nonce); } }
protected override bool IsAuthorized(HttpActionContext actionContext) { #region Read logged-in user claims var principal = (ClaimsIdentity)Thread.CurrentPrincipal.Identity; var userId = principal.Claims.Single(c => c.Type.Equals("UserId")).Value; var platform = principal.Claims.Single(c => c.Type.Equals("Platform")).Value; #endregion #region Ensure existence of ArmorToken in HTTP header var armorHeaderParser = new ArmorHeaderParser(actionContext.Request.Headers); armorHeaderParser.Execute(); if (!armorHeaderParser.ArmorTokenHeader.IsValid) { return(false); } #endregion #region Validate ArmorToken var encryptionKey = Convert.FromBase64String("0nA6gWIoNXeeFjJFo1qi1ZlL7NI/4a6YbL8RnqMTC1A="); var hashingKey = Convert.FromBase64String("0nA6gWIoNXeeFjJFo1qi1ZlL7NI/4a6YbL8RnqMTC1A="); var secureArmorTokenValidator = new SecureArmorTokenValidator(armorHeaderParser.ArmorTokenHeader.ArmorToken, encryptionKey, hashingKey, userId, 10000000000); secureArmorTokenValidator.Execute(); if (!secureArmorTokenValidator.ArmorTokenValidationStepResult.IsValid) { return(false); } #endregion #region Refresh ArmorToken and re-issue var nonceGenerator = new NonceGenerator(); nonceGenerator.Execute(); var armorToken = new ArmorToken(userId, platform, nonceGenerator.Nonce, new[] { new Claim("Another", "Claim") }); var armorTokenConstructor = new ArmorTokenConstructor(); var standardSecureArmorTokenBuilder = new StandardSecureArmorTokenBuilder(armorToken, encryptionKey, hashingKey); var generateSecureArmorToken = new GenerateSecureArmorToken(armorTokenConstructor, standardSecureArmorTokenBuilder); generateSecureArmorToken.Execute(); #endregion HttpContext.Current.Response.AppendHeader("ARMOR", generateSecureArmorToken.SecureArmorToken); return(true); }
protected void SetupSessionForSSO(string ssoSource, string?returnTo, Session session) { session.LastUsed = DateTime.UtcNow; var remoteAddress = Request.HttpContext.Connection.RemoteIpAddress; session.LastUsedFrom = remoteAddress; session.SsoNonce = NonceGenerator.GenerateNonce(AppInfo.SsoNonceLength); session.StartedSsoLogin = ssoSource; session.SsoStartTime = DateTime.UtcNow; session.SsoReturnUrl = returnTo; }
public OAuthContext BuildExchangeRequestTokenForAccessTokenContext(TokenBase requestToken, NameValueCollection additionalQueryParameters) { EnsureStateIsValid(); if (requestToken.ConsumerKey != ConsumerKey) { throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, requestToken.ConsumerKey); } var auth = new NonceGenerator(); var factory = new OAuthContextFactory(); var signer = new OAuthContextSigner(); OAuthContext context = factory.FromUri("GET", AccessTokenUri); if (additionalQueryParameters != null) { context.QueryParameters.Add(additionalQueryParameters); } context.ConsumerKey = ConsumerKey; context.Token = requestToken.Token; context.TokenSecret = requestToken.TokenSecret; context.RequestMethod = "GET"; context.SignatureMethod = SignatureMethod; context.Timestamp = DateTime.Now.EpocString(); context.Nonce = auth.GenerateNonce(); context.Version = "1.0"; string signatureBase = context.GenerateSignatureBase(); Console.WriteLine("signature_base: {0}", signatureBase); signer.SignContext(context, new SigningContext { Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret }); Console.WriteLine("oauth_singature: {0}", context.Signature); Uri uri = context.GenerateUri(); Console.WriteLine("Uri: {0}", uri); return(context); }
public void SignContext(IOAuthContext context) { EnsureStateIsValid(); context.UseAuthorizationHeader = UseHeaderForOAuthParameters; context.Nonce = _nonceGenerator.GenerateNonce(context); context.ConsumerKey = ConsumerKey; context.Realm = Realm; context.SignatureMethod = SignatureMethod; context.Timestamp = DateTime.Now.Epoch().ToString(); context.Version = "1.0"; context.Nonce = NonceGenerator.GenerateNonce(context); string signatureBase = context.GenerateSignatureBase(); _signer.SignContext(context, new SigningContext { Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret }); }
public bool TryFortify() { var identityReader = identityReaderFactory.Create(); IEnumerable <Claim> identity; var isAuthenticated = identityReader.TryRead(out identity); if (!isAuthenticated) { return(false); } var claims = identity.ToList(); var userId = claims.Single(c => c.Type.Equals("UserId")).Value; var platform = claims.SingleOrDefault(c => c.Type.Equals("Platform")); var encryptionKey = ArmorSettings.EncryptionKey; var hashingKey = ArmorSettings.HashingKey; var nonceGenerator = new NonceGenerator(); nonceGenerator.Execute(); var armorToken = new ArmorToken(userId, platform == null ? "ARMOR" : platform.Value, nonceGenerator.Nonce); var armorTokenConstructor = new ArmorTokenConstructor(); var standardSecureArmorTokenBuilder = new StandardSecureArmorTokenBuilder(armorToken, encryptionKey, hashingKey); var generateSecureArmorToken = new GenerateSecureArmorToken(armorTokenConstructor, standardSecureArmorTokenBuilder); generateSecureArmorToken.Execute(); httpContext.Response.AppendHeader("ARMOR", generateSecureArmorToken.SecureArmorToken); return(true); }
private static MTProtoClientBuilder CreateDefault() { var clientTransportFactory = new ClientTransportFactory(); var tlRig = new TLRig(); var messageIdGenerator = new MessageIdGenerator(); var hashServices = new HashServices(); var encryptionServices = new EncryptionServices(); var randomGenerator = new RandomGenerator(); var messageCodec = new MessageCodec(tlRig, hashServices, encryptionServices, randomGenerator); var keyChain = new KeyChain(tlRig, hashServices); var nonceGenerator = new NonceGenerator(); return new MTProtoClientBuilder(clientTransportFactory, tlRig, messageIdGenerator, messageCodec, hashServices, encryptionServices, nonceGenerator, keyChain); }
public override void Init(Parameters param, TPMProvider tpmProvider, TPMWrapper tpmWrapper) { base.Init(param, tpmProvider, tpmWrapper); _digest = null; _responseDigest = null; if (param.IsDefined <byte[]>("externalData")) { _nonce = param.GetValueOf <byte[]>("externalData"); } else { _nonce = NonceGenerator.GenerateByteNonce(20); } object myType = param.GetValueOf <object>("targetPCR"); _pcrSelection = param.GetValueOf <TPMPCRSelectionCore>("targetPCR"); }
public async Task <ActionResult <string> > CreateOwnAPIToken() { // We must re-fetch this data to get it from our db context for updating it var user = await database.Users.FindAsync(HttpContext.AuthenticatedUser() !.Id); if (user == null) { return(Problem("Could not find authenticated user in the database")); } logger.LogInformation("User ({Email}) created a new API token", user.Email); await database.LogEntries.AddAsync(new LogEntry() { Message = "API token created by user", TargetUserId = user.Id }); user.ApiToken = NonceGenerator.GenerateNonce(AppInfo.APITokenByteCount); await database.SaveChangesAsync(); return(user.ApiToken); }
private void TestCreation() { NonceGenerator testGenerator = new NonceGenerator(); Assert.NotNull(testGenerator); }
public OAuthContext BuildExchangeRequestTokenForAccessTokenContext(TokenBase requestToken, NameValueCollection additionalQueryParameters) { EnsureStateIsValid(); if (requestToken.ConsumerKey != ConsumerKey) throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, requestToken.ConsumerKey); var auth = new NonceGenerator(); var factory = new OAuthContextFactory(); var signer = new OAuthContextSigner(); OAuthContext context = factory.FromUri("GET", AccessTokenUri); if (additionalQueryParameters != null) context.QueryParameters.Add(additionalQueryParameters); context.ConsumerKey = ConsumerKey; context.Token = requestToken.Token; context.TokenSecret = requestToken.TokenSecret; context.RequestMethod = "GET"; context.SignatureMethod = SignatureMethod; context.Timestamp = DateTime.Now.EpocString(); context.Nonce = auth.GenerateNonce(); context.Version = "1.0"; string signatureBase = context.GenerateSignatureBase(); Console.WriteLine("signature_base: {0}", signatureBase); signer.SignContext(context, new SigningContext {Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret}); Console.WriteLine("oauth_singature: {0}", context.Signature); Uri uri = context.GenerateUri(); Console.WriteLine("Uri: {0}", uri); return context; }
public void SignContext(OAuthContext context, TokenBase accessToken) { EnsureStateIsValid(); if (accessToken.ConsumerKey != ConsumerKey) throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, accessToken.ConsumerKey); var signer = new OAuthContextSigner(); var auth = new NonceGenerator(); context.UseAuthorizationHeader = UseHeaderForOAuthParameters; context.ConsumerKey = accessToken.ConsumerKey; context.Token = accessToken.Token; context.TokenSecret = accessToken.TokenSecret; context.SignatureMethod = SignatureMethod; context.Timestamp = DateTime.Now.EpocString(); context.Nonce = auth.GenerateNonce(); context.Version = "1.0"; string signatureBase = context.GenerateSignatureBase(); Console.WriteLine("signature_base: {0}", signatureBase); signer.SignContext(context, new SigningContext {Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret}); Console.WriteLine("oauth_singature: {0}", context.Signature); }
/// <summary> /// Construct a new CspMiddleware. /// </summary> /// <param name="next">The next RequestDelegate</param> /// <param name="configure">An action to build options for configuring the header.</param> public CspMiddleware(RequestDelegate next, Action <CspOptionsBuilder> configure) { _next = next; _configure = configure; _nonceGenerator = new NonceGenerator(); }
public void SetNonceParameters(uint lot, uint tid, uint?nonce, int?seed) { this.NonceGenerator = new NonceGenerator(lot, tid, nonce, seed); }
/// <summary> /// 生成验证码 /// </summary> /// <param name="length">验证码长度</param> /// <returns></returns> public static string Generate(int length) { return(NonceGenerator.GenerateString(length)); }
public void CreateSecret() { Secret = NonceGenerator.GenerateNonce(32); this.BumpUpdatedAt(); }
/// <summary> /// Generates a new nonce odd /// </summary> public void NewNonceOdd() { NonceGenerator.GenerateByteNonce(_nonceOdd); }
public DigestHeaderFactory(NonceGenerator nonceGenerator, string realm) { this.nonceGenerator = nonceGenerator; this.realm = realm; }
/// <summary> /// Generates a new nonce odd /// </summary> public void NewNonceOddOSAP() { NonceGenerator.GenerateByteNonce(_nonceOddOSAP); }