How can I encode URL parameters? - asp.net-mvc-4

I used this method in class library and calling the method from controller. But the value i passed is not encoding. I cant trace the reason behind it.
Class Library
using System.Web;
public static class CommonLogic
{
public static string UrlEncode(string value)
{
return HttpUtility.UrlEncode(value);
}
}
Controller
var test = CommonLogic.UrlEncode("2")
test value is "2" and it not encoded.
Update:
I just realized the reason from comments below. What i really need is not encoding but encryption and decryption. I don't want the Url parameters to be exposed as plain text, instead i want that to be encrypted value and later in controller i will decrypt it again before processing that value. Any Ideas on this?

"2" doesn't need to be UrlEncoded. It's not a reserved symbol in Urls. Try testing a string such as "<".

The purpose of the UrlEncode method is to convert a string to a format that can be used in an URL. "2" is already can be used in an URL so this is a null-conversion it will result in the same value of "2".
Section 2 of RFC 3986 outlines what characters have to be encoded to become part of an URL.

Character "2" is part of the "unreserved" set as defined in RFC3986 https://www.rfc-editor.org/rfc/rfc3986#section-2.3
The "unreserved" do not need to be percent-encoded.
Regarding your comment about exposing it in the URL: encoding is not encryption. If you don't want to expose the integer user id in the URL you may need to have another unique identifier for the user that is OK to expose. For example, a random string that is unique in the user table (similar to how say youtube.com identifies videos) or a GUID.
Example of how to do simple symmetric encryption in C# using RijndaelManaged:
Simple insecure two-way data "obfuscation"?
Make sure you keep the encryption key secret.

Related

Need to change encryption algorithm to AES-256

I wrote a test program to read a users cert from the cert store, and encrypt some text. However, I realize that the encryption algorithm used is 3DES. I need to change this to AES-256. I read a similar post on here, but for me, i think my situation is slightly different...So, I'll get straight to the point.
Using the suggested method:
var recipient = new CmsRecipient("MyCert.cer");
recipient.EncryptionAlgorithms = new EncryptionAlgorithm[] {
EncryptionAlgorithm.Aes256
};
var CmsCollection = new CmsRecipientCollection();
CmsCollection.Add(recipient);
// Followed by calling ApplicationPkcs7Mime.Encrypt(CmsCollection, p7m);
I'm able to change the encryption algorithm... However my key-encryption algorithm, is not the same if I were to do it using my original method of simply using the MailboxAddress to encrypt. E.g.:
MimeMessage mm = new MimeMessage();
mm.From.Add(new MailboxAddress(from));
mm.To.Add(new MailboxAddress(to));
ApplicationPkcs7Mime.Encrypt(mm.To.Mailboxes, p7m);
Using the CmsRecipientCollection method, this is the result of my pkcs7m file:
You can see, that the key-encryption algorithm has changed to rsaOAEP,and the email client that I'm sending this message to cannot recognize this algorithm.
Whereas, using the Mailbox method to encrypt:
I'm stuck with 3DES, while the key encryption algorithm is correct...
So I guess, end of day, what I'm asking is, is there a way to get both key-encryption algorithm to be rsaEncryption, and the block cipher to be AES-256?
I saw an method UpdateSecureMimeCapabilities in the API reference, would this be able to do the job?
Also, I guess a more fundamental question is, why would the key-encryption algorithm change if both methods are essentially using the same cert?
Thanks!
Update:
So I created a custom class to override the GetPreferredEncryptionAlgorithm function, however it's still falling back to 3DES.
public class CustomWindowsSecureMimeContext : WindowsSecureMimeContext
{
public CustomWindowsSecureMimeContext () : base ()
{
}
protected override EncryptionAlgorithm GetPreferredEncryptionAlgorithm(CmsRecipientCollection recipients)
{
return EncryptionAlgorithm.Aes256;
}
}
Did I override it correctly?
The UpdateSecureMimeCapabilities method isn't going to help in your case. It's not used when enveloping data, it's only used when decoding signed messages (it's a way for you to update your database of S/MIME capabilities of the email clients used by your correspondents).
There is no way to specify a key encryption algorithm in MimeKit because I haven't been able to figure out how to specify it in BouncyCastle (used by any of the BouncyCastleSecureMimeContext subclasses) nor in Microsoft's CMS API (used by WindowsSecureMimeContext). It seems to make that decision on its own.
Whichever SecureMimeContext class you use, you can override the GetPreferredEncryptionAlgorithm() method(s) to provide your own algorithm for choosing an encryption algorithm that would be suitable to use to encrypt the message to all of the specified recipients -or- you could override the GetCmsRecipient() method which takes a MailboxAddress and creates a new CmsRecipient for that recipient.
The other option is to use the MimeKit.Cryptography.CmsRecipient[Collection] API's in order to set the CmsRecipient.EncryptionAlgorithms property which represents the encryption algorithms supported by that recipient's email client. If you set an array of EncryptionAlgorithms that includes Aes256 for each recipient, then that algorithm will be chosen.

Jackson and Bean Validation: Deserialize empty String as null

I've a RESTeasy application using Jackson and Bean Validation. A POJO might loo like this:
public class Foo {
#Size(min = 2)
private String bar;
}
Bar is validated if the client sends the bar property. And es expected: If the client does not send the property nothing will be validated.
If the client sends an empty String I'll get a constraint violation. This may be correct but it's hard to control what the value of an empty input field really is. For instance in my angular application the field will not be present if the user did not enter anything. Once he enters and deletes something I'll have an empty String.
I thought I could configure Jacksons behavior via DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT but as answered here this is only working for POJOs not for Strings. The only ways I see is not using #Size or writing an own deserializer for Strings. Both doesn't seem to be good solutions. Anyone other ideas?
If you want to accept the empty string, you could use the #Pattern constraint matching also the empty string: #Pattern(regexp = "^$|(.){2}") or #Pattern(regexp = "^$|...
The alternative is to write your own custom constraint.

How to create the (header) of this JSON in VB.net?

Here is the json that I am struggling to recreate. :
WorkLoadResult({
"AreaReturned":[
{
"ResultCode":"0"
}
],
"Process":"Generic",
"WorkLoadId":"megaupload_server_798811",
"Status":"1",
"TotalSuccessfulRuns":"3"
});
I have all of this created just perfectly in my code rolling my class into another class. I have been attempting to create the WorkLoadResult header ( I know this really isn't a header but for lack of a better word I will call it this), but I don't see how this can even be created. When I run this through a JSON formatter the JSON is determined to be valid. This is something I am receiving back from a webservice. I in turn need to have a class created in order to catch this JSON. I have looked at multiple different json examples and see no examples that have JSON formatted in this manner with some sort of a header at the beginning of the data.
My one current option is to strip this out of the data prior to doing pushing it into a class. I do not like this option and have to think that it is possible to have this WorkLoadResult in my class.
Quite new to JSON, any advice/direction is greatly appreciated.
Thanks.
This looks like a JSONP response. If the webservice returns exactly this string and you can't tell the webservice to return plain JSON, you have no choice but removing the function call around the real JSON object.

Recommended naming conventions for same method with different signatures?

been creating a few wcf methods and i have a method called IsValidLogin ... there various versions, 1 takes 2 strings, 1 takes an object etc.
Of course in WCF you can't overload methods can anyone suggest the best way to name these methods..
I was thinking of IsValidLogin1, IsValidLogin2??
But I am open to any suggestions.
When you start adding index numbers to your identifiers, you're usually doing it wrong.
One way I've seen is adding "With" and the parameter names to the name, i.e. IsValidLoginWithUsernamePassword, and IsValidLoginWithToken (assuming your object is some kind of authentication token). These are kind of long though.
I'd just call the methods IsValidUsernamePassword and IsValidToken.
First of all, you should stick with message/contract first methodology when working with wcf services, passing in a request and returning a response. This will save you a lot of headache down the road.
That being said, you should create two methods like so:
public LoginValidResponse IsLoginValid(UserObjectRequest userRequest)
and
public LoginValidResponse IsLoginValid(UsernamePasswordRequest usernameRequest)
There are probably better names for these, but you get the idea. If you provided more information about what you were passing in and back, I could help out with naming a bit more.
Notice these two methods return the same response LoginValidResponse.
Put your two strings in the UsernamePasswordRequest (I'm assuming the strings are username and password). Put the User Object in the UserObjectRequest.
You can also reuse these requests / responses in later methods, e.g, GetUserInfo(UserObjectRequest request).
The LoginValidResponse will contain your bool (and any other information you want to pass back in your response).
*Note - I only named the methods IsLoginValid b/c that was your question. On top of the request / response pattern, I might also rename the methods to something like ValidateLoginByUser and ValidateLoginByUsername (or something like that).
Of course in WCF you can't overload methods can anyone suggest the best way to name these methods..
You can overload methods in WCF by adding unique OperationContract behaviours. OperationContract has the Name property that exposes the WCF methods to WSDL Schemas. Your service-side (WCF) code would remain clean. But you would still have to call the methods by signature you defined in the Name property of the OperationContract behaviour.
[OperationContract(Name="IsValidLoginWithUsernameAndPassword")]
void IsValidLogin(string username,string password);
[OperationContract(Name="IsValidLoginWithToken")]
void IsValidLogin(AuthToken token);
Usage......
TestClient client = new TestClient();
string callMethod1 = client.IsValidLoginWithUsernameAndPassword("user","pass");
string callMethod2 = client.IsValidLoginWithToken(authToken);
You can read more here
http://www.codeproject.com/Tips/656042/Method-Overloading-in-WCF
I don't think that IsValidLogin1,2, etc. is clear enough. When you overload methods normally, you don't have to worry about names because it's the same name with different parameters, however in this case you have to remember the parameters for each method, and numbers could get confusting.
I might suggest IsValidLoginNumStr etc, which is to say, maybe list key parameters in the method name to help remind you which method you're referring to. Either that or if one takes a password, then IsValidLoginPass, or something of the like. I say this because I'm a fan of long, descriptive method names. If you want to keep the name short as possible, and you can think of a letter that would help, like P for password, or O for object, then tack on a helpful letter at the end. Something more than a number will help you in the long run

How to transfer objects through the header in WCF

I'm trying to transfer some user information in the header of the message through message inspectors.
I have created a behavior which adds the inspector to the service (both client and server).
But when I try to communicate with the service I get the following error:
XmlException:
Name cannot begin with the '<' character, hexadecimal value 0x3C.
I have also get exception telling me that DataContracts where unexpected.
Type
'System.DelegateSerializationHolder+DelegateEntry'
with data contract name
'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System'
is not expected. Consider using a
DataContractResolver or add any types
not known statically to the list of
known types - for example, by using
the KnownTypeAttribute attribute or by
adding them to the list of known types
passed to DataContractSerializer.
The thing is that my object contains other objects which are marked as DataContract and I'm not interested adding the KnownType attribute for those types.
Another problem might be that my object to serialize is very restricted in form of internal class and internal properties etc.
Can anyone guide me in the right direction. What I'm I doing wrong?
Some code:
public virtual object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var header = MessageHeader.CreateHeader("<name>", "<namespace>", object);
request.Headers.Add(header);
return Guid.NewGuid();
}
Don't put the angle brackets into the actual strings. Remember, the serialization format may not even be text based, all you're doing is specifying the name of the element and the namespace. So your code should look more like this:
var header = MessageHeader.CreateHeader("name", "urn:myNamespace", object);
request.Headers.Add(header);
To close this question, I never solved the exception. Instead I implementated ISerializable which worked great for me.