Home > Enterprise >  Encrypt/decrypt string n JavaScript
Encrypt/decrypt string n JavaScript

Time:09-04

I have a string, length of which is X => 0 && X <= 26;

I need encrypt function which will encrypt this string to get X-character-length string: encrypt("My String", "Passphrase", xLengthOutput) -> "01234567890123456789012345";

I also need decrypt function, which will take X-character-length string and output my original string decrypt("01234567890123456789012345", "Passphrase") -> "My String";

NOTE: it's not a compression, original string is always smaller than or equal to encrypted result.

CodePudding user response:

You could use the Crypto API Crypto.subtle which returns a SubtleCrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption.

Then you can use every method in SubtleCryptography such as encrypt and decrypt.

CodePudding user response:

I dont think that there is a library that could do what you want.

If you want a simple encryption then you could try something I build and change it to work like you want.

Here is the code https://snack.expo.dev/@alentoma/enc-dec

CodePudding user response:

you can use following function to encrypt and decrypt a string via javascript , it is simple one , for advanced version please use crypto API.

var encrypt = function(str, key) {
  var result = "";
  for (var i = 0; i < str.length; i  ) {
    var charCode = (str.charCodeAt(i)   key) % 256;
    result  = String.fromCharCode(charCode);
  }
  return result;
}

var decrypt = function(str, key) {
  var result = "";
  for (var i = 0; i < str.length; i  ) {
    var charCode = (str.charCodeAt(i) - key   256) % 256;
    result  = String.fromCharCode(charCode);
  }
  return result;
}
  • Related