Caesar Decryption of string using javascript

Caesar Decryption of string using javascript

Caesar decryption is basically reversing the encryption. Before you go ahead, you should look at Caesar encryption, this will help you understand the concept of encryption, using which you can decrypt the encrypted string.

In brief, Caesar decryption is downshifting of string by some amount. i.e. if unshifting amount is 3, and want to decrypt “d”, the result will be “a”.

Let’s see, how can we achieve via code-

function CaesarDecryption (encryptedString, unshiftAmount) {
    var plainText = "";
    for(var i = 0; i < encryptedString.length; i++) {
        var encryptedCharacter = encryptedString.charCodeAt(i);
        if(encryptedCharacter >= 97 && encryptedCharacter <= 122) {
            plainText += String.fromCharCode((encryptedCharacter-97 - unshiftAmount + 26) %26 + 97 );
        } else if(encryptedCharacter >= 65 && encryptedCharacter <= 90) {
            plainText += String.fromCharCode((encryptedCharacter-65 - unshiftAmount + 26) %26 + 65 );
        } else {
            plainText += String.fromCharCode(plainCharacter);
        }
    }
    return plainText;
}

Output:

//Here we'll decrypt the string which we encrypted in previous example by 3
console.log(CaesarDecryption("Ldpehlqjhqfubswhg",3));

//Here is how decrypted string looks like

Iambeingencrypted

 

Leave a Reply

Your email address will not be published. Required fields are marked *