TBonfim
TBonfim

Reputation: 65

Node crypto - define output cypher length

I need to have a limit in the output length of my cipher. I know it depends on which algorithm you use, but I didnt find how do do this.

const crypto = require('crypto');
const options = {secret : 'SECRET', algorithm : 'CAST-cbc'};

exports.encrypt = (url) => {
  const encrypt = crypto.createCipher(options.algorithm, options.secret);
  let cipher = encrypt.update(url, 'utf8', 'hex');
  cipher += encrypt.final('hex');
  return cipher;
};

This is how im generating the cipher. Thanks.

Upvotes: 0

Views: 2384

Answers (3)

Brenn
Brenn

Reputation: 1384

Given the updates that you need a hash, not encryption, then here is how this works.

You hash the original URL and save a file to disk (or wherever, S3). That file has the name that corresponds to the hash. So if the URL is 'http://google.com' the hash may be 'C7B920F57E553DF2BB68272F61570210' (MD5 hash), so you would save 'C7B920F57E553DF2BB68272F61570210'.txt or something on the server with 'http://google.com' as the file contents.

Now when someone goes to http://yourURLShortnener.com/C7B920F57E553DF2BB68272F61570210 you just look on disk for that file and load the contents, then issue a redirect for that URL.

Obviously you'd prefer a shorter hash, but you can just take a 10 digit substring from the original hash. It increases chances of hash collisions, but that's just the risk you take.

Upvotes: 0

gusto2
gusto2

Reputation: 12085

limit in the output length of my cipher
...
'm trying to build a url shortener without having to have a database behind it

Encryption will be always longer than the original plaintext. You will need to have some IV (initialization vector), encrypted information, optionally an authentication code and then all encoded into an url safe format.

In theory you may sacrifice some level of security and have some sort of format-preserving encryption, but it will be at least as long as the original source.

final hash example: 1d6ca5252ff0e6fe1fa8477f6e8359b4

You won't be able to reconstruct original value from a hash. That's why for serious url shortening service you will need a database with key-value pair, where the key can be id or hash

You may still properly encrypt and encode the original data, just the output won't be shorter.

Upvotes: 2

Brenn
Brenn

Reputation: 1384

The output depends on input, always. What you could do is pad the input or output to the desired length to generate a consistent final hash. This requires there be a maximum length to the input, however.

Beyond that, there is no way to force a length and still have something decryptable. If you simply need a hash for validation, that's a bit different. If you clarify the purpose we can help more.

Upvotes: 1

Related Questions