Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing image as hash code C#

Tags:

c#

.net

image

hash

Im building a website which will store millions of images so i need a unique id for each image. What Cryptography is best for storing images. Right now this is what my code looks like im using SHA1.

Is there a standard hash used beside sha1 and is it possible that two images could have the same hash code?

 Image img = Image.FromFile("image.jpg");

 ImageConverter converter = new ImageConverter();
 byte[] byteArray = (byte[])converter.ConvertTo(img, typeof(byte[]));

 string hash;

 using (SHA1CryptoServiceProvidersha1 = new SHA1CryptoServiceProvider())
 {
     hash = Convert.ToBase64String(sha1.ComputeHash(byteArray));
 }
like image 553
Leslie Jones Avatar asked Dec 19 '22 06:12

Leslie Jones


1 Answers

If I understand correctly you want to assign an SHA1 value as a filename so you can detect whether you have that image in your collection already. I don't think this is the best approach (if you're not running a database then maybe it is) but still, if you're planning to have millions of images then (for practical reasons) just think that it's impossible for collisions to occur.

For this purpose I would not recommend SHA256 since the main two advantages (collision resistance + immunity to some theoretical attacks) are not really worth it because it's something around 10 times slower than SHA1 (and you'll be hashing a lot of fairly big files).

You shouldn't be scared about it's 128 bitlength: In order to have a 50% chance of finding a collision in 128 bits you will need to have 18446744073709600000 images in your collection (sqrt of 2^128).

Oh and I don't wanna sound conceited or anything, but hash and cryptography are too different things. In fact, I'd say that hashing is closer to code signing/digital signatures than to cryptography.

like image 106
Gaspa79 Avatar answered Jan 05 '23 06:01

Gaspa79