bokkie
bokkie

Reputation: 1590

Encrypt string into int in C#

I have looked a lot on the internet, couldn't find what I needed. I found either string to string, or md5, which doesn't return an int and so on.

So what I need is a bit of guidance on how I could encrypt a string into an int. The framework I am working on is used for a while so I cannot change that.

At some point, I have a UniqueID property which should be the ID of an entity, but that sometimes is null, therefore I cannot use it, so I need to use other two ID-s to create a unique id, to assign to my UniqueID, something like string.format("{0}-{1}", branchId, agentId), then encrypt this into int, assign it to UniqueID which gets sent to a whatever method, decrypt UniqueID back into a string, and split by "-" and get my two Ids. And to mention that I don't have any security worries. Grateful for your help.

Upvotes: 0

Views: 645

Answers (2)

BillJam
BillJam

Reputation: 221

If there's a way to compress two 18 bit numbers into 32 bits, I sure don't know of it. If you can't be sure that the two ID's can be under 65536 (or one of them under 16384) then the best I can come up with is for you to change UniqueID to a long - then it's straight forward, no strings, just put AgentId into the first 32 bits and branchId into the last 32 bits.

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 133975

What you're asking can't be done, in general. You have two numbers, each of which can range from 0 to 150,000. It takes 18 bits to represent 150,000. So it would take 36 bits to represent the two numbers. An int32 is 32 bits.

Unless you can exploit some special knowledge about the relationship between branches and agents (if there is any), then it will be impossible to squeeze those 36 bits into a 32 bit integer.

You could, however, create a lookup table that assigns a unique key to each branch-agent pair. A simple incrementing key. You could then build the pair (i.e. `142096-037854') and look up the id. Or, given the id, look up the branch/agent pair.

Upvotes: 1

Related Questions