how to Decrypt password in c# - c#

I want to decrypt password in C# I am using the below code.
public class NetFourMembershipProvider : SqlMembershipProvider
{
public string GetClearTextPassword(string encryptedPwd)
{
try
{
byte[] encodedPassword = Convert.FromBase64String(encryptedPwd);
byte[] bytes = this.DecryptPassword(encodedPassword);
if (bytes == null)
{
return null;
}
return Encoding.Unicode.GetString(bytes, 0x10, bytes.Length - 0x10);
}
catch (Exception)
{
throw;
}
}
}
And my web config file is
<configuration>
<system.web>
<machineKey validationKey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" decryptionKey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" decryption="3DES" validation="SHA1" />
<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SiteSqlServer" enablePasswordRetrieval="true"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0"
requiresUniqueEmail="false"
passwordFormat="Encrypted"
applicationName="DotNetNuke"
description="Stores and retrieves ......." />
</providers>
</membership>
<compilation debug="true" targetFramework="4.0" />
</system.web>
At this line byte[] bytes=this.DecryptPassword(encodedPassword); I am getting the below error message.
You must specify a non-autogenerated machine key to store passwords in the encrypted format. Either specify a different passwordFormat, or change the machineKey configuration to use a non-autogenerated decryption key.
How can I convert passwords.
Please help me.
Note:- The validationkey is 40 characters and decryptionKey is a 48 charectors long data.
Thanks in Advance

Rather trying to decrypt the password. Store the encrypted password in database...and when you want to validate password use encrypted password entered by user and compare it to encrypted password stored in DB.
Generally alogorithms like SHA or MD5 is used to perform hashing on entered password..Actually, Hashing and Encryption is two different thing.In this case, Hashing is used.

Related

MembershipProvider validation fails after password change

I am using an SQLMemberShipProvider.
When I enter my username and password the following code is executed membershipProvider.ValidateUser(myUserName, myPassword) and returns true indicating that the user is valid.
I reset the password with the following code:
var username = membershipProvider.GetUser(myUserName, false);
username.ChangePassword(username.ResetPassword(), newPassword);
Now when I enter my username and the new changed password, the following executes again membershipProvider.ValidateUser(myUserName, newPassword), but this time the validation fails.
I don't understand this, as I am using the same provider for both calls of ValidateUser. The password seemed to have changed as the original password is no longer valid as well.
The password format is hashed, IsLocked is false and IsApproved is true.
Code looks good. This is occuring most porbably because resetPassword is not set to true in your web.config:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="MyApplication" />
</providers>
</membership>
Ensure that enablePasswordReset="true" is set.

Retrieve the password from developer point of the user, which is encrypted by ASP.NET membership provider

I am using the ASP.NET membership in my application.
When customers register I need to get the password of the user, is there any algorithm so that I can get the decrypted password.
eg:
1) we will be having set of tables that will be created on asp.net_membership where in that we store userName, password, password key, strength and security question.
<membership>`enter code here`
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, `enter code here `Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MMMS35.API"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="Moose"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="1"
passwordStrengthRegularExpression="" />
</providers>
</membership>
When customers register I need to get the password of the user, is there any algorithm so that I can get the decrypted password.
If you want to get the password entered by the user when he is registering, you can probably do so. For example, if you use the ASP.NET CreateUserWizard control, you can access the CreateUserWizard.Password property. Nevertheless, it's not very clear what you'd want to do with it.
If you want to get the user's password after he's registered, which is probably not a good idea from a security perspective as noted in the comments to your question, you need to configure your MembershipProvider with:
enablePasswordRetrieval="true"
passwordFormat="Clear" or "Encrypted"

IIS7 Session loses its values

I've implemented a challenge-response scheme as an Ajax handler.
For some reason it stopped working after working fine for a couple months.
Investigating the issue showed that Context.Session[KEY] had lost its value between the challenge and the response calls.
I put Session_Start and Session_End (and a few other) methods in Global.asax.cs with some logging there and I see a new Session_Start event being fired with the same session ID and there was no Session_End event
Question is: why does IIS lose the session values?
Update: I tried switching to SQLServer sessions but there was no change in behavior. On rare occasions sessions work as intended, not sure why. I tried all "session losing variables" troubleshooting guides I could find to no effect
UPDATE 2: I narrowed down the issue to a missing session cookie, but modifying my.browsers config didn't resolve the issue after several attempts. When I call the ajax handler from a browser the session cookie "ASP.NetSessionId" shows up as expected. I changed the cookie name in IIS settings for both the site and the server to "SessionId" but I kept seeing ASP.NET, even after restarting the server. I would still like to give the bounty to someone who has an idea what's going on. In the meanwhile I worked around this problem by setting a session cookie in code.
Pseudo code for Login.ashx:
string login = GetParameter("login", context);
string passhash = GetParameter("pass", context);
string challenge = "" + Context.Session["CHALLENGE"];
if (!string.IsNullOrEmpty(challenge))
{
// this is the 'response' part
string challengeResponse = Crypto.GetChallengeResponse(Challenge, UserFromDB.PassHash);
if (challengeResponse == passhash)
{
// Great success, challenge matches the response
Log.I("Success");
return "SUCCESS";
}
else
{
Log.W("Failed to respond");
return "FAILED TO RESPOND";
}
}
else
{
// if passed login or session-stored challenge are empty - issue a new challenge
challenge = "Challenge: "+ Crypto.GetRandomToken();
Context.Session["CHALLENGE"] = challenge;
Log.I("Sent Challenge"); // this is what's in the log below
return challenge;
}
Here's the log, Session started appears with each call, Session.Keys.Count stays 0 even though Session["CHALLENGE"] should have been set:
// This is the challenge request:
[] **Session started**: sr4m4o11tckwc21kjryxp22i Keys: 0 AppDomain: /LM/W3SVC/1/ROOT-4-130081332618313933 #44
[] Processing: <sv> **MYWEBSITE/ajax/Login.ashx** SID=sr4m4o11tckwc21kjryxp22i
[] Sent Challenge #Login.ashx.cs-80
// this is the response, note that there's another Session started with the same id
// and the session didn't keep the value ["CHALLENGE"], there are no session-end events either
[] **Session started**: sr4m4o11tckwc21kjryxp22i Keys: 0 AppDomain: /LM/W3SVC/1/ROOT-4-130081332625333945 #93
[] Processing: <sv> **MYWEBSITE/ajax/Login.ashx?login=MYLOGIN&pass=RuhQr1vjKg_CDFw3JoSYTsiW0V0L9K6k6==**
[] Sent Challenge #Login.ashx.cs-80 >Session: sr4m4o11tckwc21kjryxp22i
web config, sanitized
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="IncludeStackTraceInErrors" value="false" />
</appSettings>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="MYConnection" connectionString="metadata=res://*…. and a bunch of other stuff that works" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
What is the default value for Idle Time-out ? If the app pool times out your session goes bye bye
See Application Pool (Advanced Settings) -> Idle Time-out
I think it defaults to five minutes.
See this link for advice on setting the idle timeout
You could also experience your issue if your running as a webgarden when it's not needed; look at Maximum Worker Processes, try setting it to 1 and retest
I can see you are using handler for that purpose which would always return null.
You need to implement IReadOnlySessionState.
Check out http://www.hanselman.com/blog/GettingSessionStateInHttpHandlersASHXFiles.aspx
Add IRequiresSessionState to your handler implimentation
ex
public class handler_name:IHttpHandler, IRequiresSessionState

Microsoft Media Platform + Forms Authentification

Forms Authentication does not work. Auth cookies are not sent to server when SMF attempts to get access to *.ism/Manifest files on a server that requires specific user roles.
What i do:
1. Create new Silverlight Smooth Streaming template with supporting RIA WCF.
2. Configure web.config :
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=[SERVER];Initial Catalog=[CATALOG];User ID=[USER];Pwd=[PASSWORD];" providerName="System.Data.SqlClient" />
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="Gender" />
<add name="Birthday" />
<add name="AvatarPath" />
</properties>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Add Authentification Service and correct User class (add 3 props).
On client side add this to app.xaml.cs:
public App()
{
//Default things...
InitializeWebContext();
}
private void InitializeWebContext()
{
WebContext webContext = new WebContext();
var fa = new FormsAuthentication();
var ac = new AuthenticationDomainService1();
fa.DomainContext = ac;
fa.Login(new LoginParameters("user", "password"), (y) =>
{
if (!y.HasError)
{
this.RootVisual = new MainPage();
}
}, null);
webContext.Authentication = fa;
ApplicationLifetimeObjects.Add(webContext);
Resources.Add("WebContext", WebContext.Current);
}
Access is restricted by web.config file in target directory:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="Role_name" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
User exists in this role.
When I use the default video that's specified in Xaml (Big Bunny) - everything is fine. But when I change mediasource to a path to s restricted zone on my server I get an access error.
On the client side, I get user credentials succesfully.
Fiddler shows next thing:
When I try access to another resctricted methods ([RequiresAuthentication]) on RIA WCF, client send Auth cookies, but when SMFPlayer try access to media source, that cookie wasn`t sent.
What have I missed?
I found some workaround:
If you transfer the stream files into a subdirectory, and restrict access to it (instead of a directory with "ism" files). Manifest will be issued to anonymous users, but the data streams is only for registered (when player try touch data stream it sucessfully attach auth cookies).

question about forms authentication

Ok, I have my web application with this web.config for the manage of users and roles
<connectionStrings>
<add name="MySqlConnection" connectionString="" />
</connectionStrings>
<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".ASPXFORMSAUTH"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlConnection"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
For security reason i can't set the connection string in my web.config. Now i want to know if i can pass in the application the instance of the connection to the forms authentication in some way.
Note's that i don't want to set the connection string in runtime I want pass the instance of the connection
Make a class library and a class in it. This class could contain a function as follows:
public static SqlConnectionStringBuilder GetConnection()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = #"some string";
sqlBuilder.Password = #"mypassword";
sqlBuilder.UserID = #"myuserid";
//set other properties here.
return sqlBuilder;
}
Now you can reference the above class library in your project.
You could also encrypt your connection string. Refer to these articles:
How to Encrypt connection string in web.config
Encryption of Connection Strings Inside the Web.config in ASP.NET 2.0
something like this?
Setting Membership-Profile-Role provider's connection string at runtime
If it needs to be a unique connection string per user, the link Davide Piras provided is the way to go.
If having an open connection string with SQL Auth details in it is the issue, you might consider simply encrypting it:
https://web.archive.org/web/20211020203213/https://www.4guysfromrolla.com/articles/021506-1.aspx

Categories

Resources