Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
The formulas for encryption and decryption require a positive value of the modulo operation. However, this is not guaranteed for all implementations of the modulo operator. For instance, in Python ...
Answer
#1: Initial revision
The formulas for encryption and decryption require a positive value of the modulo operation. However, this is not guaranteed for all implementations of the modulo operator. For instance, in Python the modulo value is always positive (e.g. `-2 % 5 = 3`), while in Java it can be negative (e.g. `-2 % 5 = -2`). The following Java implementation reliably generates a *positive* value: ```java private static int mod(int a, int b) { return ((a % b) + b) % b; } ``` --------- Since encryption and decryption differ only in the sign of `shift`, encryption and decryption can be implemented together. A possible implementation for e.g. the alphabet `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzۤ$%&` could be: ```java private static String encryptDecrypt(String text, int shift) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzۤ$%&"; int size = alphabet.length(); StringBuffer result = new StringBuffer(); for (int i = 0; i < text.length(); i++) { int u = alphabet.indexOf(text.charAt(i)); if (u == -1) { throw new RuntimeException(text.charAt(i) + " not allowed..."); } int v = mod(u + shift, size); result.append(alphabet.charAt(v)); } return result.toString(); } ``` ---------- Test: ```java String plaintext = "ۤ$%&0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String ciphertext = encryptDecrypt(plaintext, 3); // Encryption: right shift String decrypted = encryptDecrypt(ciphertext, -3); // Decryption: left shift System.out.println(plaintext); // ۤ$%&0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ System.out.println(ciphertext); // %&ABC3456789abcdefghijklmnopqrstuvwxyzۤ$DEFGHIJKLMNOPQRSTUVWXYZ012 System.out.println(decrypted); // ۤ$%&0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ```