This is a java program to implement Caesar Cipher Encryption algorithm. This is the simplest of all, where every character of the message is replaced by its next 3rd character.
Here is the source code of the Java Program to Implement Caesar Cypher. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
package com.maixuanviet.setandstring; import java.util.Scanner; public class CaesarCipher { public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; public static String encrypt(String plainText, int shiftKey) { plainText = plainText.toLowerCase(); String cipherText = ""; for (int i = 0; i < plainText.length(); i++) { int charPosition = ALPHABET.indexOf(plainText.charAt(i)); int keyVal = (shiftKey + charPosition) % 26; char replaceVal = ALPHABET.charAt(keyVal); cipherText += replaceVal; } return cipherText; } public static String decrypt(String cipherText, int shiftKey) { cipherText = cipherText.toLowerCase(); String plainText = ""; for (int i = 0; i < cipherText.length(); i++) { int charPosition = ALPHABET.indexOf(cipherText.charAt(i)); int keyVal = (charPosition - shiftKey) % 26; if (keyVal < 0) { keyVal = ALPHABET.length() + keyVal; } char replaceVal = ALPHABET.charAt(keyVal); plainText += replaceVal; } return plainText; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the String for Encryption: "); String message = new String(); message = sc.next(); System.out.println(encrypt(message, 3)); System.out.println(decrypt(encrypt(message, 3), 3)); sc.close(); } }
Output:
$ javac CaesarCipher.java $ java CaesarCipher Enter the String for Encryption: Sanfoundry vdqirxqgub sanfoundry
Related posts:
Spring Boot - Bootstrapping
Custom HTTP Header with the HttpClient
Finding Max/Min of a List or Collection
Multipart Upload with HttpClient 4
Setting Up Swagger 2 with a Spring REST API
Handle EML file with JavaMail
Send email with authentication
Adding Shutdown Hooks for JVM Applications
Spring Boot - Build Systems
New Features in Java 12
Getting a File’s Mime Type in Java
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Receive email using IMAP
How to Change the Default Port in Spring Boot
Remove the First Element from a List
Using the Not Operator in If Conditions in Java
Java Program to Implement Word Wrap Problem
New Features in Java 14
Guide to Selenium with JUnit / TestNG
Java Program to Check Cycle in a Graph using Graph traversal
Tính trừu tượng (Abstraction) trong Java
JPA/Hibernate Persistence Context
Jackson – Unmarshall to Collection/Array
Java Program to Implement Direct Addressing Tables
The Registration Process With Spring Security
Java – Combine Multiple Collections
HttpClient with SSL
New Features in Java 13
Java Program to Perform Matrix Multiplication
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Functional Interface trong Java 8
A Guide to Spring Cloud Netflix – Hystrix