Caesar Cipher in Dataweave

Bharath Kesavan
3 min readJan 1, 2023

--

Caesar cipher is a substitution cipher where each letter of the word is replaced with another. Each letter is replaced by another letter some fixed number of positions.

“application” → “dssolfdwlrq”

Example:
Input — “aaa”
Shift — 3
Output — “ddd”

The challenge here is to rotate past “z”. Thereby if the input is “wxyz” with shift 3, then the output should be “zabc”.

How to

Below are the steps used for cipher implementation

  1. Input string to char List
  2. Convert each char to unicode
  3. Increment with the given shifter
  4. Rotate for the values where necessary
  5. Convert unicode back to char
  6. Put together as string

The DW given below is broken into smaller steps listed above for easier understanding. The DW String module is imported here. Its used for converting from char to unicode and back.

Unicode for small alphabets runs from 97 to 122.

charCode(“a”) => 97

fromCharCode(97) => “a”

%dw 2.0
output application/json
import * from dw::core::Strings


var shift = 3
var inp = "aaa"


var arr = inp splitBy ("")
var unic = arr map ( charCode($) + shift)
var rotater = unic map (
if (($) < 123) ($)
else $-26
)
var list = rotater map ( fromCharCode($) )
var str = list joinBy ""
---
str

After shifting, the values are checked. If they are higher than 122, they are above the a-z spectrum. Thus 26 is subtracted in those cases only to make them within the range thus the name rotater.

The variables:

“arr” will contain [ “a”, “a”, “a”]

“unic” will contain [ 100, 100, 100 ] which is 97 unicode + 3 shifter

“rotater” will contain same as “unic” here. There is no rotation in some scenario

“list” will contain [ “d”, “d”, “d” ]

“str” will contain “ddd”

Below example where we have to rotate:

Next steps

  1. Multiple variables are created of easier understanding of this concept. This can be improved by creating only necessary vars.
  2. Negative shift of chars also possible “ddd” -> “aaa”. The shifter has to be given “-3” to achieve this. The rotater has to check for values below 97 and increased by 26.
  3. This negative shifter can also be used as cipher decryption
  4. The capital alphabets’ unicode fall in the 65–90 spectrum. It can also be added to support capital letter ciphers.
  5. For the scope of this, spacebar and special characters are not considered. Add them if needed.

Play around!

References

https://en.wikipedia.org/wiki/Caesar_cipher

https://docs.mulesoft.com/dataweave/2.4/dw-strings-functions-charcode

https://docs.mulesoft.com/dataweave/2.4/dw-strings-functions-fromcharcode

https://en.wikipedia.org/wiki/List_of_Unicode_characters

--

--