Caesar Cipher Encrption and Decryption in java

     Caesar Cipher -a simplest form of encryption and decryption technique. Each letter is substituted by another letter. The substitution is based on shifting. for eg: ‘A’ is substituted by ‘E’ and so on is shift of 4.

This technique was used by Julius Caesar for communicating in military operations.

Let us implement this in java language.

Program implementation:

              This program implementation starts with including Built in header file import java.util.Scanner;.

A public class is created with encryption and decryption methods.

Encryption:encryptIt()

  • This function creates an object for StringBuilder.
  • Each character is separated and check for uppercase or lowercase.
  • According to it, the shifting value is added, and appropriate alphabet is replaced.

Decrption:decryptIt()

              This reads the character in the String and replace the alphabet by previous alphabet according to the shifting value.

‘main()’:

  •               This function reads the text to decrypted and shifting value from user. Call the encrypt and decrypt function.
  • Finally, print both values.

Program:

import java.util.Scanner;

public class CaesarCipherEg {

    // Encryption method

    public static String encryptIt(String txt, int shift) {

        StringBuilder encrypTex = new StringBuilder();

        for (char cha : txt.toCharArray()) {

            if (Character.isLetter(cha)) {

                char base1 = Character.isUpperCase(cha) ? 'A' : 'a';

                encrypTex.append((char) ((cha - base1 + shift) % 26 + base1));

            } else {

                encrypTex.append(cha);

            }

        }

        return encrypTex.toString();

    }

 

    // Decryption method

    public static String decryptIt(String txt, int shift) {

        return encryptIt(txt, 26 - (shift % 26));

    }

     public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        System.out.println("Enter the text to be encrypted");

        String p_text = s1.nextLine();

        System.out.println("Enter the shift");

        int shift = s1.nextInt();

         String encrypTex = encryptIt(p_text, shift);

        String decrypTex = decryptIt(encrypTex, shift);

         System.out.println("Encrypted: " + encrypTex);

        System.out.println("Decrypted: " + decrypTex);

    }

}

Output:

C:\raji\blog>javac CaesarCipherEg.java

C:\raji\blog>java CaesarCipherEg

Enter the text to be encrypted

Welcome to Java

Enter the shift

2

Encrypted: Ygneqog vq Lcxc

Decrypted: Welcome to Java

This is the way of creating classic Caesar cipher encryption and decryption program in java. Hope this code is useful to you!!!

Update data in XML file using java

              XML is Extensible Markup Language. It has root node and elements. Once it’s elements created, it stored in .xml file.

When you want to update the file, use java language to make it effective manner.

Let us create a XML file for students.

  • A xml file version is assigned as 1.0,encoding type is “UTF-8”.
  • Here,the root node is students.
  • Elements are name, class, grade.
  • All tags are opened and closed.

“students.xml”

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<students>

  <student id="s_1">

    <name>Aarvi</name>

    <class>7 </class>

    <grade>A++</grade>

  </student>

</students>

Java program to update XML file:

              To implement this in java, use the built in packages javax.xm.parsers and xml.tranform,java.io.File and org.w3c.dom and its sub packages.

  • Create a public class with main() function.
  • A new file object instance is created and it point out ‘students.xml’.
  • Three more objects are created for documentbuilder,documentbuilderfactory and document.
  • First element of xml file is extracted and its ‘name’ tag is assigned with new value.
  • To update this in file,four more objects created for transformfactory,transformer,DOMSource and StreamResult.
  • To transform the data from source to destination,transform() function is used.
  • Finally,it displays the updated message.

Program:           

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import java.io.File;

public class UpdateXMLEg {

    public static void main(String[] args) {

        try {

            File file1 = new File("students.xml");

            DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder1 = factory1.newDocumentBuilder();

            Document doc1 = builder1.parse(file1);

            Element student = (Element) doc1.getElementsByTagName("student").item(0);

            student.getElementsByTagName("name").item(0).setTextContent("arthi"); // Update name

            TransformerFactory transformerFactory1 = TransformerFactory.newInstance();

            Transformer transformer1 = transformerFactory1.newTransformer();

            DOMSource source1 = new DOMSource(doc1);

            StreamResult result = new StreamResult(file1);

            transformer1.transform(source1, result);

            System.out.println("The XML File is Updated!");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac UpdateXMLEg.java

C:\raji\blog>java UpdateXMLEg

The XML File is Updated!

The xml file is changed the name

This is the way of updating XML file using java is implemented. Hope this code will helpful to you.