encryption using protectedData.protect in windows phone 7.1 - encryption

I am developing Windows Phone 7 application in which I send encrypted data to a webservice that decrypts it. I'm using the protectedData.protect which is only working properly as long as I am encrypting and decrypting from my application (for testing only); once I use the webservice the behaviour changes.
This is the code from the webservice:
If Flag = False Then ' Decrypt
Dim ProtectedPinByte As Byte() = Encoding.UTF8.GetBytes(password)
Dim PinByte2 As Byte() = ProtectedData.Unprotect(ProtectedPinByte, Nothing, DataProtectionScope.CurrentUser)
password = Encoding.UTF8.GetString(PinByte2, 0, PinByte2.Length)
Return Bll.Utilites.EncryptDecryptStr(True, password) 'Encrypts using another algorithm
Else ' Encrypt
EncPassword = Bll.Utilites.EncryptDecryptStr(False, password) 'decrypts from another algorithm
Dim PinByte As Byte() = Encoding.UTF8.GetBytes(EncPassword)
Dim ProtectedPinByte As Byte() = ProtectedData.Protect(PinByte, Nothing, DataProtectionScope.CurrentUser)
Return Encoding.UTF8.GetString(ProtectedPinByte, 0, ProtectedPinByte.Length)
End If

This isn't possible as the ProtectedData class on Windows Phone uses device credentials to encrypt the data, it can only be decrypted on that device.
In Silverlight for Windows Phone, both the user and machine
credentials are used to encrypt or decrypt data.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata(v=vs.96).aspx

Related

DICOM C-ECHO verification with ClearCanvas SDK

I am using ClearCanvas sdk to c-echo verifiy a remote dicom entity but the result I am always getting is 'Failed'. It seems that it is not even associating with the remote entity. below is my code to do this in vb.net. Am I doing it right?
Dim hostname As String = "RemoteHost"
Dim ae As String = "RemoteAETitle"
Dim port As Integer = "RemotePort"
Dim lhost As String = "LocalAETitle"
Dim checkremote = New VerificationScu()
Dim result As VerificationResult = checkremote.Verify(lhost, ae, hostname, port)
If result = VerificationResult.Success Then
MessageBox.Show(result.ToString)
Else
MessageBox.Show(result.ToString)
End If
checkremote.Join(New TimeSpan(0, 0, 4))
You are using the API correctly, this should verify the connection. Have you taken a look at any log messages generated? This would help identify the problem.

What is the best method for determination ASP.net website clients?

I have a asp.net webapp, and runs in private network
I want determine PCs clients for
allow or block the requests
knows who is connected
connects only by special PCs
and more
I used IP Addresses, but anyone can connect when change the IP Address by one that passed in webapp, I want users login by just some PCs . any suggestions ?
LOGIN and PASSWORD going to a database of preferences... The best way to control everything about users (IP control can be bypassed, it´s not a valid control).
UPDATE
New method to pass info in URL:
To get hardware information:
Dim query As New SelectQuery("Win32_bios")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
For Each info In search.Get()
BIOS_Msg = info("version").ToString()
Next
Dim searchMainboard As New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
Dim infoMain As ManagementObject
For Each infoMain In searchMainboard.Get()
Computer_Mainboard = infoMain("model").ToString()
Next
To encode Strings:
You may set a KEY and IV as byte array. The key may change according date and even some specific parameters according to the current time.
Add also:
Imports System.Security.Cryptography
Imports System.Text
Friend Function EncryptStringToBytes_Aes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
' Check arguments.
Dim encrypted() As Byte
' Create an AesCryptoServiceProvider object
' with the specified key and IV.
Using aesAlg As New AesCryptoServiceProvider()
aesAlg.Key = Key
aesAlg.IV = IV
Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return Convert.ToBase64(encrypted)
End Function 'EncryptStringToBytes_Aes
To decrypt it:
Friend Function DecryptStringFromBytes_Aes(ByVal cipherText As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
Dim plaintext As String = Nothing
Dim SourceText as Byte() = Convert.FromBase64(CipherText)
' Create an AesCryptoServiceProvider object
' with the specified key and IV.
Using aesAlg As New AesCryptoServiceProvider()
aesAlg.Key = Key
aesAlg.IV = IV
' Create a decrytor to perform the stream transform.
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(SourceText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function 'DecryptStringFromBytes_Aes
Using these functions, you can:
- Get specific hardware info;
- Encode any string and convert it to Base64
- Pass them in URL using normal convention.
- Receive them in your code-behind and translate them.
I guess that´s the best way to get reliable and specific information of each workstation instead IP-number. You may also work with the Windows Serial Number.

ASP.net This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms

Hey all i am getting this error when trying to compare a password in my database using my ASP.net page.
This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
The code looks like this:
Public Shared Function UserAuthentication(ByVal user As String, ByVal pass As String) As WebUserSession
Dim strSQL As String = ""
Dim strForEncryption As String = pass
Dim result As Byte()
Dim sHA1Managed As SHA1 = New SHA1Managed()
Dim encryptedString As New System.Text.StringBuilder()
result = sHA1Managed.ComputeHash(ASCIIEncoding.ASCII.GetBytes(pass))
For Each outputByte As Byte In result
'convert each byte to a Hexadecimal upper case string
encryptedString.Append(outputByte.ToString("x2").ToUpper())
Next
strSQL &= "SELECT email, name, id, permission_id, username FROM (user) INNER JOIN user_per ON user.id = user_per.user_id "
strSQL &= "WHERE(username = '" & user & "' And password = '" & encryptedString.ToString() & "')"
We recently had to update/lock down our server to be compliance with security holes and the like. But doing so caused this error for one of the websites we are hosting on the same server. Prior to all these security settings the web site worked just fine.
The odd part is that i am able to run the website local (debug mode) within VS 2010 and it does just fine. No errors at all.
Would anyone have any tips on how to go around this to make the website work again as it did before we added all these security settings to be complaint? We simply can not just disable it because that would cause our other websites to go out of compliance.
I've already tried the suggestions on these pages:
http://blogs.msdn.com/b/brijs/archive/2010/08/10/issue-getting-this-implementation-is-not-part-of-the-windows-platform-fips-validated-cryptographic-algorithms-exception-while-building-outlook-vsto-add-in-in-vs-2010.aspx
http://social.msdn.microsoft.com/Forums/en/clr/thread/7a62c936-b3cc-4493-a3cd-cc5fd18b6b2a
http://support.microsoft.com/kb/935434
http://blogs.iis.net/webtopics/archive/2009/07/20/parser-error-message-this-implementation-is-not-part-of-the-windows-platform-fips-validated-cryptographic-algorithms-when-net-page-has-debug-true.aspx
http://blog.aggregatedintelligence.com/2007/10/fips-validated-cryptographic-algorithms.html
Thanks.
Tried using this code as well
Dim p As String = Password.Text.ToString
Dim data(p) As Byte
Dim result() As Byte
Dim sha As New SHA1CryptoServiceProvider()
result = sha.ComputeHash(data)
The error is:
Conversion from string "S51998Dg5" to type 'Integer' is not valid.
And that error is on the line: Dim data(p) As Byte
According to this sha1managed is not fips compliant. It throws an InvalidOperationException because this class is not compliant with the FIPS algorithm.
You need to either disalbe FIPS compliance or use a FIPS compliant implementation. sha1cryptoserviceprovider I think is FIPS complaint.

Decrypting ASPNET_Membership Password

I am trying to decrypt my password stored in aspnet_membership table...
I am using the following code,
Dim encodedPassword() As Byte = System.Text.Encoding.UTF8.GetBytes(password)
encodedPassword = MyBase.EncryptPassword(encodedPassword)
Dim decryptedPassword() As Byte = MyBase.DecryptPassword(encodedPassword)
If (decryptedPassword IsNot Nothing) Then
Return System.Text.Encoding.UTF8.GetString(decryptedPassword, 0, decryptedPassword.Length)
End If
but at the line of DecryptPassword(encodedPassword) it shows error as
"Length of the data to decrypt is invalid."
I think you need to Base64 Decode it first:
byte[] encodedPassword = Convert.FromBase64String(pass);
byte[] bytes = this.DecryptPassword(encodedPassword);
or in VB.NET:
Dim encodedPassword As Byte() = Convert.FromBase64String(pass)
Dim bytes As Byte() = Me.DecryptPassword(encodedPassword)
Edit: As #Eranga pointed out, this is provided that the MembershipProvider used actually supports decryption and for the default provider the passwordFormat setting controls if it's "hashed", "encrypted" or "plain". By default the setting is "hashed", which means no decryption possible.
Encrypted passwords are base64 encoded before being saved to the database and for that reason they need to be decoded before being decrypted.

Setting user's password via System.DirectoryServices.Protocols in AD 2008 R2

I am connecting to a Microsoft Active Directory server in a DMZ from my .net application (asp.net VB .net 4.0). I need to create a new "inetorgperson" in an orgunit called "SingleCustomerAccount".
I have had to use the System.DirectoryServices.Protocols namespace for all the work, because the ADSI classes (System.DirectoryServices namespace) wouldn't work across the DMZ properly.
Anyway it's been working fine connecting to Active Directory on Windows Server 2003 R2; however we're running tests against Active Directory on Windows Server 2008 R2 (2008r2 in native mode for forest and domain) in order to upgrade.
My existing code to create a user does not work.
System.DirectoryServices.Protocols.DirectoryOperationException: The server cannot handle directory requests.
at System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32 messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, Boolean exceptionOnTimeOut)
at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)
at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request)
at Salford.LDAP.LDAPUser.SaveNewToDirectory(String UsersFirstPassword) in C:\Projects\SCA\App_Code\SCA\LDAPUser.vb:line 1059
at SCA.Web.Service.CitizenService.CreateNewAccount(String Username, String Title, String FirstName, String Surname, String Street, String City, String County, String Postcode, String EmailAddress, String HomeTel, String MobileTel, String UPRN, String SpinID, Int16 AccountLevel) in C:\Projects\SCA\App_Code\CitizenService.vb:line 255
I have found that when I remove the bit of code that adds the password attribute, the user is created, but just without a password. So the code at fault is where I am adding the password. But what has changed between 2003 and 2008 which would have stopped it from working?
Here is my code.
Using ldapConn As New LdapConnection(New LdapDirectoryIdentifier(LDAPServerAddress), credential)
ldapConn.SessionOptions.ProtocolVersion = 3
ldapConn.SessionOptions.Signing = Not _UseSecureConnection
ldapConn.SessionOptions.Sealing = Not _UseSecureConnection
ldapConn.SessionOptions.SecureSocketLayer = _UseSecureConnection
If _UseSecureConnection Then
ldapConn.SessionOptions.VerifyServerCertificate = New VerifyServerCertificateCallback(AddressOf ServerCallback)
End If
ldapConn.AuthType = AuthType.Negotiate
ldapConn.Bind()
Dim DistinguishedName As String = String.Format("CN={0},OU={1},{2}", Me.AccountName, Me.OrgUnit, Me.DCSuffix)
' Save this distinguished name to the local object; so that the group memberships addition works in a minute.
Me._DistinguishedName = DistinguishedName
Dim addRequest As New AddRequest(DistinguishedName, Me.LDAPUserObjectType)
'' Add an AccountName attribute
addRequest.Attributes.Add(New DirectoryAttribute(GetLDAPSchemaMapping(LDAPUserProperties.AccountName), AccountName))
'' Look in any derived classes, if they want any attributes adding as part of this save operation.
'' Hint: Derived classes will override the "GetDirectoryAttributesForAddNewRequest" function and return a list of anything they want adding
'' to the AD at the time of creation.
If Not GetDirectoryAttributesForAddNewRequest() Is Nothing Then
For Each kvp As KeyValuePair(Of String, String) In GetDirectoryAttributesForAddNewRequest()
addRequest.Attributes.Add(New DirectoryAttribute(kvp.Key, kvp.Value))
Next
End If
'' Hash up the password into a Unicode byte array and send this as the requried initial password.
addRequest.Attributes.Add(New DirectoryAttribute("unicodePwd", GetPasswordData(UsersFirstPassword)))
' Execute the request on the directory server.
Dim addResponse As DirectoryResponse = ldapConn.SendRequest(addRequest)
' Need to return the GUID, need to search against the ldap server:
Dim request As New SearchRequest(String.Format("OU={0},{1}", Me.OrgUnit, Me.DCSuffix), "(&(objectCategory=" & Me.LDAPUserObjectType & ")(sAMAccountName=" & Me.AccountName & "))", System.DirectoryServices.Protocols.SearchScope.Subtree)
Dim searchResponse As SearchResponse = DirectCast(ldapConn.SendRequest(request), SearchResponse)
returnedGuid = DirectCast(searchResponse.Entries(0).Attributes("objectGuid").Item(0), Byte())
' Set up the search request object so we can do searches now based on this new user:
Dim rq As SearchRequest = BuildLdapSearchRequest("sAMAccountName", Me.AccountName)
' ** Send the query to the LDAP server, and save the response into the private _SearchResponse object **
_SearchResponse = DirectCast(ldapConn.SendRequest(rq), SearchResponse)
End Using
_useSecureConnection is false for this call - the bind works fine.
Like I have said, when I comment out this line, it works:
addRequest.Attributes.Add(New DirectoryAttribute("unicodePwd", GetPasswordData(UsersFirstPassword)))
The GetPasswordData method is below for completeness.
''' <summary>
''' Returns a unicode-encoded byte array based on the incoming password string.
''' </summary>
''' <param name="password">The password to turn into a byte array</param>
Public Function GetPasswordData(ByVal password As String) As Byte()
Dim formattedPassword As String
formattedPassword = String.Format("""{0}""", password)
Return Encoding.Unicode.GetBytes(formattedPassword)
End Function
I appreciate any insights...
Regards
bgs264
Is it possible that the password policies are different for the two servers? Or that there's some other policy difference?
One way to check might be to use the ldp.exe tool and see if you can do the same operations with the exact same password with it. Here's a link that describes changing the password using that tool.
This was fixed by a combination of using LDAPS instead of LDAP; relaxing the password policy; doing a full rebuild of the application; clearing the browser cache and rebooting all the servers.

Resources