ASP.NET MembershipProvider uses passwordSalt when encrypting - encryption

I've a question about the ASP.NET Membership (from .NET 2.0), and more specifically the way it encrypts passwords (when you choose to encrypt them, and not hash then), and the way it verifies them.
I was under the impression that a password salt would only make sense if you choose to hash your passwords, and not encrypt them. And, according to the MSDN documentation on those old-school membership providers
PasswordSalt nvarchar(128) Randomly generated 128-bit value used to salt password hashes; stored in base-64-encoded form
But, I've tried changing the salt for a password that's stored as encrypted, and validation of that password stopped working (the encrypted password was not changed, just the passwordsalt).
So, is the passwordSalt involved when encrypting/validating the password using those membership providers (since validation stopped working, I'd say it is, but I've no idea why)?
Thanks, and all the best.
EDIT:
I've tried inputting an invalid base64 salt, and got this stacktrace, which is already a bit weird in my opinion, for an encryption check. It looks more like a hash check. Weird thing is none of this is documented on MSDN.
[FormatException: Invalid length for a Base-64 char array or string.]
System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) +14390811
System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) +162
System.Convert.FromBase64String(String s) +56
System.Web.Security.SqlMembershipProvider.EncodePassword(String pass, Int32 passwordFormat, String salt) +148
System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +245
System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +195

I've managed to step-into the System.Web.dll and found the cause.
Apparently, the MSDN documentation is not up to the with the implementation.
In case encryption is selected, apparently it does use the salt.
private string EncodePassword(string pass, int passwordFormat, string salt)
{
byte[] bIn = Encoding.Unicode.GetBytes(pass);
byte[] bSalt = Convert.FromBase64String(salt);
byte[] bRet = null;
...
byte[] bAll = new byte[bSalt.Length + bIn.Length];
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
bRet = EncryptPassword(bAll, _LegacyPasswordCompatibilityMode);
}

Related

System.IO.FileNotFoundException Cannot find file

I am using google as an smtp client to send an email and am having troubles with sending the attachment, i am using an asp:fileupload to choose the file then using the fileupload.filename to select the attachment. Here is the Error message.
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf'. File name: 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName) at frmQuote.btnSubmit_Click(Object sender, EventArgs e) in c:\Users\jack\Documents\Visual Studio 2013\WebSites\firstarPrecision\frmQuote.aspx.cs:line 46
Then here is the C# Code to go along with it
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("EMAIL", "PASSWORD"),
EnableSsl = true
};
var msgQuote = new MailMessage
{
Subject = strQuoteSubject,
Body = strQuoteBody,
From = new MailAddress("EMAIL"),
};
//HINT HINT HERE IS WHERE THE ERROR OCCURS, I JUST DONT KNOW WHY :(
//HOW DO I TURN OFF CAPS LOCK
Attachment att = new Attachment(fupAttachment.FileName.ToString());
msgQuote.Attachments.Add(att);
msgQuote.To.Add(new MailAddress(strEmail));
client.Send(msgQuote);
}
catch (Exception ex)
{
Response.Write(ex);
}
there is the code, i obviously blocked out my credentials and such... at least i hope i got all of it.
An uploaded file needs to be saved to the server, or you could pass the file stream to the attachment (if the API supports it, not 100% sure). Either way, what you are giving it is insufficient. Save the file stream on the fupAttachment object, and then attach the file from that location. Also, depending on the version of IIS you are using determines which account accesses the file stream for permissions. The latest IIS uses an account for the apppool that needs the permissions.

Bad Data with Cryptography.RC2

There is a special working progress where we encrypt and decrypt an input.
Suddenly, yesterday, there was an encrypted string we weren't able to decrypt.
It seems my cryptographic knowledge aren't good enough to solve this problem.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crypto
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class Crypto
{
public static void Main()
{
//String NotWorking_dec = "鈦ꧪ㧘聯ꢮ玗硴廜᭮⸂濅�";
String enc ="mIAU::__*?";
//String dec = "砿첩뜞ꦽ嶾蝡泛ɝࠪ塤偏ꍨ";
Console.WriteLine(decrypt(dec));
//writeFile(encrypt(enc));
Console.ReadLine();
}
private static string key = "ZlKMpRwoPLmNXEpCLxEa6g==";
private static string iv = "U5ZB4W4bQqg=";
private static ICryptoTransform enc;
private static ICryptoTransform dec;
static Crypto()
{
RC2 rc = System.Security.Cryptography.RC2.Create();
enc = rc.CreateEncryptor(Convert.FromBase64String(key), Convert.FromBase64String(iv));
dec = rc.CreateDecryptor(Convert.FromBase64String(key), Convert.FromBase64String(iv));
}
public static String encrypt(String value)
{
byte[] input = toBytes(value);
return toString(enc.TransformFinalBlock(input, 0, input.Length));
}
public static String decrypt(String value)
{
byte[] input = toBytes(value);
Console.WriteLine(input.Length);
return toString(dec.TransformFinalBlock(input, 0, input.Length));
}
private static void writeFile(String value)
{
try
{
StreamWriter sw = new StreamWriter("output.tmp", true);
sw.WriteLine(value);
sw.Close();
}
catch (Exception ex) { }
}
private static byte[] toBytes(String value)
{
return Encoding.Unicode.GetBytes(value);
}
private static String toString(byte[] value)
{
return Encoding.Unicode.GetString(value);
}
}
}
This working progress works for months.
You are able to test it with the input
mIAU::__*?
you get
砿첩뜞ꦽ嶾蝡泛ɝࠪ塤偏ꍨ
decrypt it and you get again
mIAU::__*?
But the encrypted String "鈦ꧪ㧘聯ꢮ玗硴廜᭮⸂濅�" throws errors: (Of course we used the same key and iv)
BAD DATA
bei System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
bei System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone)
bei System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
bei Crypto.Crypto.decrypt(String value) in c:\Users\Td\Documents\Visual Studio 2013\Projects\Crypto\Crypto\Program.cs:Zeile 56.
bei Crypto.Crypto.Main() in c:\Users\Td\Documents\Visual Studio 2013\Projects\Crypto\Crypto\Program.cs:Zeile 23.
bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
bei System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
bei System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
bei System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
bei System.Activator.CreateInstance(ActivationContext activationContext)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
You cannot simply convert random bytes to strings and back. Not all bytes are valid character encodings. You need to apply for instance base 64 encoding to your binary ciphertext if you require text. Otherwise you will loose data, depending on the value of the ciphertext. And the ciphertext will contain random byte values. So it may fail now and then, as you are currently experiencing.
Java silently converts unknown bytes to characters by default, for instance it will create a � character if it cannot convert byte(s) to a character. This is why this particular string fails.
Besides that, Unicode contains a lot of characters that are not easily printable, and even characters that can be created using either two Unicode code points or a single one. So a Unicode string may have multiple possible encodings, so it is doubly unsuitable for conveying binary data.
All in all, text should not be directly used to convey binary data. The data needs to be encoded first.

while uploading a cloudfile in rackspace cloud using openstack.net i get net.openstack.Core.Exceptions.Response.BadServiceRequestException

While uploading a file to rackspace cloud using the CreateObjectFromFile method from my local machine, it goes though fine. but when i do it from a client machine i get net.openstack.Core.Exceptions.Response.BadServiceRequestException.
ContainerID: 1644
srcfileName: \\10.5.48.2\XMLGateway\BOOutBox\PJR340131023160359529217.xml
desfileName: 1644_PJR340131023160359529217.xml
cloudFilesProvider.CreateObjectFromFile(inStrContainerID, inStrSrcFilePath, strDesFileName);
I checked for documentation on this exception and i cannot find anything useful.
EDIT:
here is the error stack
net.openstack.Core.Exceptions.Response.BadServiceRequestException: Invalid request body: unable to parse Auth data. Please review XML or JSON formatting.
at net.openstack.Providers.Rackspace.Validators.HttpResponseCodeValidator.Validate(Response response)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.ExecuteRESTRequest[T](CloudIdentity identity, String urlPath, HttpMethod method, Object body, Dictionary`2 queryStringParameter, Boolean isRetry, Boolean isTokenRequest, String token, Int32 retryCount, Int32 retryDelay, Func`7 callback)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.ExecuteRESTRequest[T](CloudIdentity identity, String urlPath, HttpMethod method, Object body, Dictionary`2 queryStringParameter, Boolean isRetry, Boolean isTokenRequest, String token, Int32 retryCount, Int32 retryDelay)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.<>c__DisplayClassc.<GetUserAccess>b__b()
at net.openstack.Core.Caching.UserAccessCache.<>c__DisplayClassc.<Get>b__4(String k)
at System.Collections.Concurrent.ConcurrentDictionary`2.AddOrUpdate(TKey key, Func`2 addValueFactory, Func`3 updateValueFactory)
at net.openstack.Core.Caching.UserAccessCache.Get(String key, Func`1 refreshCallback, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.GetUserAccess(CloudIdentity identity, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.CloudIdentityProvider.GetUserAccess(CloudIdentity identity, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.ProviderBase`1.GetServiceEndpoint(CloudIdentity identity, String serviceName, String region)
at net.openstack.Providers.Rackspace.ProviderBase`1.GetPublicServiceEndpoint(CloudIdentity identity, String serviceName, String region)
at net.openstack.Providers.Rackspace.CloudFilesProvider.GetServiceEndpointCloudFiles(CloudIdentity identity, String region, Boolean useInternalUrl)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObject(String container, Stream stream, String objectName, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObjectFromFile(String container, String filePath, String objectName, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at ?.?.?(String ?, String ?, String ?, String ?, String ?, String& ?, Boolean& ?, String& ?)
Edit 2:
Ok after updating the dll to the new versions, this is the stacktrace:
Unable to connect to the remote server
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.203.3.30:443
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.<>c__DisplayClass6.<Stream>b__5(HttpWebRequest req)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.<>c__DisplayClass9.<ExecuteRequest>b__8()
at JSIStudios.SimpleRESTServices.Client.RequestRetryLogic.Execute(Func`1 callback, IEnumerable`1 non200SuccessCodes, Int32 retryCount, Nullable`1 retryDelay)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.ExecuteRequest(Uri url, HttpMethod method, Func`3 responseBuilderCallback, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Func`2 executeCallback)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.Stream(Uri url, HttpMethod method, Func`3 responseBuilderCallback, Stream content, Int32 bufferSize, Int64 maxReadLength, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Action`1 progressUpdated)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.Stream(Uri url, HttpMethod method, Stream content, Int32 bufferSize, Int64 maxReadLength, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Action`1 progressUpdated)
at net.openstack.Providers.Rackspace.ProviderBase`1.StreamRESTRequest(CloudIdentity identity, Uri absoluteUri, HttpMethod method, Stream stream, Int32 chunkSize, Int64 maxReadLength, Dictionary`2 queryStringParameter, Dictionary`2 headers, Boolean isRetry, RequestSettings requestSettings, Action`1 progressUpdated)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObject(String container, Stream stream, String objectName, String contentType, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObjectFromFile(String container, String filePath, String objectName, String contentType, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at ?.?.?(String ?, String ?, String ?, String ?, String ?, String& ?, Boolean& ?, String& ?
So does have to do with with firewall settings on the client machine?
A newer release of the SDK is available through NuGet. Two of the many changes included in that release are the following:
Removed GeographicalCloudIdentityProvider (a class only used inside the SDK itself, nevertheless this is the part of your stack trace that indicated you were using an old version of the SDK)
Added the ability for ResponseException (the base class of BadServiceRequestException and several others) to include detailed information about the cause of the problem as part of the exception.
(Applies to openstack.net 1.2.x only): Due to a limitation in the SDK dependencies that we are working to resolve ASAP, you'll need to explicitly install one of the SDK dependencies before installing the SDK. The instructions for this are included in the comment marked UPDATE on the following page: openstacknetsdk/openstack.net#203

ASP.NET RSACryptoServiceProvider throws Invalid flags specified exception

I got problem when try to generate keys using ASP.NET (.NET 4) for RSA, the RSACryptoServiceProvider throws invalid flags specified exception.
[CryptographicException: Invalid flags specified.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +33
System.Security.Cryptography.Utils._GenerateKey(SafeProvHandle hProv, Int32 algid, CspProviderFlags flags, Int32 keySize, SafeKeyHandle& hKey) +0
System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +9719339
System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +89
System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters) +38
System.Security.Cryptography.RSA.ToXmlString(Boolean includePrivateParameters) +45
I initialize the RSA using this code:
var _cpsParameter = new CspParameters();
_cpsParameter.Flags = CspProviderFlags.UseMachineKeyStore;
var rsaProvider = new RSACryptoServiceProvider(bitStrength, _cpsParameter);
string publicAndPrivateKeys = rsaProvider.ToXmlString(true);
string justPublicKey = rsaProvider.ToXmlString(false);
Any idea how to solve this ?
One possible explanation might be that you already have a non-exportable key in the key-container with the name "" (in that case .NET will just use the existing key instead of overwriting it with a new key).
Try this code instead and see if that makes a difference:
var cspParameters = new CspParameters();
cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
cspParameters.KeyContainerName = Guid.NewGuid().ToString();
var rsaProvider = new RSACryptoServiceProvider(bitStrength, cspParameters);
string publicAndPrivateKeys = rsaProvider.ToXmlString(true);
string justPublicKey = rsaProvider.ToXmlString(false);

ASP.NET insert from bll to mysql

I am trying to make an insert to an MySql database using a three layer solution (or what it might be called).
I have done this may times with an MS-sql database and it has worked very well.
But now when I am trying to make an insert I get the the ID can't be null.
I thought the database took care of that.
If I write an insert directly in the code and use the MySqlCommand and executeNonQuery it works great.
Is it not possible to use BLL and DAL with MySql?
Error message:
System.Data.NoNullAllowedException: Column 'GiftID' does not allow nulls. at System.Data.DataColumn.CheckNullable(DataRow row) at System.Data.DataColumn.CheckColumnConstraint(DataRow row, DataRowAction action) at System.Data.DataTable.RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, Boolean fireEvent) at System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Int32 position, Boolean fireEvent, Exception& deferredException) at System.Data.DataTable.InsertRow(DataRow row, Int32 proposedID, Int32 pos, Boolean fireEvent) at System.Data.DataRowCollection.Add(DataRow row) at PayEx.payexusersDataTable.AddpayexusersRow(payexusersRow row) in c:\Users\IT\AppData\Local\Temp\Temporary ASP.NET Files\payex\45bd406a\10c84208\App_Code.cyqhjqo7.1.cs:line 444 at PayExBLL.AddPayExUser(String Firstname, String Lastname, String Company, String Address, String Zip, String City, String Phone, String Email, Byte ContactMe, UInt32 Amount, UInt32 TransactionNumber, Byte Anonymous, String Currency) in c:\Users\IT\Documents\Visual Studio 2008\WebSites\payex\App_Code\BLL\PayExBLL.cs:line 66 at _Default.btn_next3_Click(Object sender, EventArgs e) in c:\Users\IT\Documents\Visual Studio 2008\WebSites\payex\Default.aspx.cs:line 191
My code:
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
public bool AddPayExUser(string Firstname, string Lastname, string Company, string Address, string Zip, string City, string Phone, string Email, byte ContactMe, uint Amount, uint TransactionNumber, byte Anonymous, string Currency)
{
PayEx.payexusersDataTable puTable = new PayEx.payexusersDataTable();
PayEx.payexusersRow puRow = puTable.NewpayexusersRow();
puRow.Firstname = Firstname;
puRow.Lastname = Lastname;
puRow.Company = Company;
puRow.Address = Address;
puRow.Zip = Zip;
puRow.City = City;
puRow.Phone = Phone;
puRow.Email = Email;
puRow.ContactMe = ContactMe;
puRow.Amount = Amount;
puRow.TransactionNumber = TransactionNumber;
puRow.Anonymous = Anonymous;
puRow.Currency = Currency;
puTable.AddpayexusersRow(puRow);
int rowsAffected = Adapter.Update(puTable);
return rowsAffected == 1;
}
System.Data.NoNullAllowedException: Column 'GiftID' does not allow nulls. at
From the looks of your code, you're forgetting to pass in a GiftID parameter to your function but it's expected (and can't be null) in your table row.
Hence the exception. Either set it in your code above, or define a default value on it in your MySQL database.
EDIT: This comment assumes you're inserting into a table for which GiftId is the primary key, which seems unlikely. If so, Eoin Campbell's answer makes more sense!
Check if GiftId is an AUTO_INCREMENT column; that's MySQL's equivalent of identity.
You can recreate the column as identity like:
ALTER TABLE Gifts
DROP COLUMN GiftId;
ALTER TABLE items
ADD COLUMN GiftId INT NOT NULL AUTO_INCREMENT FIRST;

Resources