1

I have a string, length of which is 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.

kelalaka
  • 5,064
  • 5
  • 27
  • 44
David Chanturia
  • 83
  • 1
  • 11
  • It sounds like what you are looking for is a simple padding. – Bergi Sep 03 '22 at 17:33
  • 2
    Modern encryption modes need Nonce/IV to be secure ( i.e. have at least Ind-CPA). The IV increases the size. In addition, block cipher in CBC mode requires padding that can increase the ciphertext size with block length. The stream cipher like AES-CTR or ChaCha20 doesn't need padding, however, you still need to live the IV. If you want to keep formatting you need to use Format Preserving Encryption ( there you will still IV). So, what is your security model so that you may use or not AES-CTR or ChaCha20 with fixed IVs? – kelalaka Sep 05 '22 at 11:08

4 Answers4

0

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.

Lior Pollak
  • 3,362
  • 5
  • 27
  • 48
  • Thanks Lior, I found some libraries which let me encrypt/decrypt, but I'm having trouble finding one, which lets you set encryption output length. – David Chanturia Sep 03 '22 at 16:46
  • I'm afraid that controlling the output length is not quite feasible. You could encrypt using a one time pad key using XOR over the data which will give you the same output length, but it is quite hard to get it right security wise. – Lior Pollak Sep 06 '22 at 16:32
0

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;
}
Gracie williams
  • 1,287
  • 2
  • 16
  • 39
0

Please note that the below code is for demonstration purposes only and more complex encryption algorithms and more secure key management schemes should be used in real-world applications. In addition, since the Crypto API needs to run in HTTPS or local environment, the above code cannot run in a normal HTTP environment.

// Encryption function
function encrypt(str, key) {
  // Convert the key to a byte array
  var keyBytes = new TextEncoder().encode(key);

  // Convert the plaintext to a byte array
  var textBytes = new TextEncoder().encode(str);

  // Generate an AES key using the Crypto API
  crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["encrypt"]).then(function(key) {
    // Encrypt using AES algorithm
    crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, key, textBytes).then(function(encryptedBytes) {
      // Convert the encrypted byte array to a Base64 string
      var encryptedBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(encryptedBytes)));
      console.log("Encrypted string: ", encryptedBase64);
    });
  });
}

// Decryption function
function decrypt(encryptedBase64, key) {
  // Convert the key to a byte array
  var keyBytes = new TextEncoder().encode(key);

  // Convert the Base64 string to a byte array
  var encryptedBytes = new Uint8Array(atob(encryptedBase64).split("").map(function(c) { return c.charCodeAt(0); }));

  // Generate an AES key using the Crypto API
  crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["decrypt"]).then(function(key) {
    // Decrypt using AES algorithm
    crypto.subtle.decrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, key, encryptedBytes).then(function(decryptedBytes) {
      // Convert the decrypted byte array to a string
      var decryptedText = new TextDecoder().decode(decryptedBytes);
      console.log("Decrypted string: ", decryptedText);
    });
  });
}

// Example code
var key = "MySecretKey12345"; // Key, can be any string of any length
var plaintext = "Hello World!"; // String to be encrypted

encrypt(plaintext, key);

var ciphertext = "q3Hx4zA4PTGZf41zZSSbEg=="; // Encrypted string, can be obtained from the encrypt function
decrypt(ciphertext, key);
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
0

use xor encryption. it's very simple. my code is working fine

function encrypt(text, key){
    return [...text].map((x, i) => 
    (x.codePointAt() ^ key.charCodeAt(i % key.length) % 255)
     .toString(16)
     .padStart(2,"0")
   ).join('')
}
function decrypt(text, key){
    return String.fromCharCode(...text.match(/.{1,2}/g)
     .map((e,i) => 
       parseInt(e, 16) ^ key.charCodeAt(i % key.length) % 255)
     )
}
let enc = encrypt("My String", "Passphrase")
let dec = decrypt(enc, "Passphrase")

console.log(enc) // 1d185320041a1b0f14
console.log(dec) // My String
perona chan
  • 101
  • 1
  • 8