Convert the int from c# gethashcode() back to string?

会有一股神秘感。 提交于 2019-12-11 01:33:21

问题


A really simple question:

I am doing a simple thing. I have few string like:

 string A = "usd";

And I want to get the hashcode in C#:

 int audusdReqId = Convert.ToInt32("usd".GetHashCode());

Now how could I convert the 32-bit integer audusdReqId back to the string "usd"?


回答1:


You cannot. A hash code does not contain all of the necessary information to convert it back to a string. More importantly, you should be careful what you use GetHashCode for. This article explains what you should use it for. You can't even guarantee that GetHashCode will return the same thing in different environments. So you should not be using GetHashCode for any cryptographic purposes.

If you are trying to create a binary representation of a string, you can use

var bytes = System.Text.Encoding.UTF8.GetBytes(someString);

This will give you a byte[] for that particular string. You can use GetString on Encoding to convert it back to a string:

var originalString = System.Text.Encoding.UTF8.GetString(bytes);

If you are trying to cryptographically secure the string, you can use a symmetric encryption algorithm like AES as Robert Harvey pointed out in the comments.




回答2:


The purpose of the hashcode/hash function is that it has to be one way and that it cannot be converted back to the original value.

There are good reasons as to why this is so. A common usage would be password storage in a database for example. You shouldn't know the original value(the plain text password) and that is why you would normally use a hashcode to encode it one way.

There are also other usages as storing values to hashsets etc.



来源:https://stackoverflow.com/questions/8806186/convert-the-int-from-c-sharp-gethashcode-back-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!