Java Implementation – ROT-13 Encoding Algorithm

ROT-13 is the simplest of all encoding algorithms. The idea is simple, rotate the characters by 13. If you assume characters A-Z (or a-z) to be in a circle, for any characters, go to 13 characters ahead in the circle and replace it with that character.

The following diagram taken from Wikipedia (under wikipedia commons license), demonstrates the character substitution fact clearly.

Interestingly, if you encode a plain text, to decode it, you need to re-encode it.

That means for a character ABC, encode (encode( ABC)) is ABC

The following is the Java Implementation of ROT-13 Algorithm. Since having only A-Z or a-z characters may not suffice, I have added a condition where other characters will remain the same.

 * @author Kushal Paudyal
 * Last Modified on 5th September 2008
package com.kushal.utilities;
/**Java Implementation of ROT-13 Encoding algorithm**/
public class Rot13Encryption {

	public static void main(String args[]) {
		//Original Text
		String plainText="Sanjaal.Com";
		//Let's Encode It
		String encodedText=rot13Encode(plainText);
		//Then Decide It
		String decodedText=rot13Encode(encodedText);

		System.out.println("Original Text: tt"+plainText);
		System.out.println("After ROT-13 Encoding: t"+encodedText);
		System.out.println("After ROT-13 Decoding: t"+decodedText);

	 * @param textToEncode
	 * @return encoded (or decoded)text.
	 * Note: if you encode a text, and encode the result again,
	 * you will get the original text.
	public static String rot13Encode(String textToEncode) {
		String encodedText = "";
		int textLength = textToEncode.length();

		for (int i = 0; i < textLength; i++) {
			char currentChar = textToEncode.charAt(i);
			if ((currentChar >= 65 && currentChar <= 77)
					|| (currentChar >= 97 && currentChar <= 109)) {
				encodedText += (char) (currentChar + 13);
			} else if ((currentChar >= 78 && currentChar <= 90)
					|| (currentChar >= 110 && currentChar <= 122)) {
				encodedText += (char) (currentChar - 13);
			} else {
				encodedText += currentChar;
		return encodedText;


Here is the sample output:

Original Text:                     Sanjaal.Com
After ROT-13 Encoding:     Fnawnny.Pbz
After ROT-13 Decoding:     Sanjaal.Com

Tutorial: Java DES Encryption And Decryption

The Data Encryption Standard (DES) is a block cipher (a form of shared secret encryption) that was selected by the National Bureau of Standards as an official Federal Information Processing Standard (FIPS) for the United States in 1976 and which has subsequently enjoyed widespread use internationally. It is based on a symmetric-key algorithm that uses a 56-bit key. The algorithm was initially controversial with classified design elements, a relatively short key length, and suspicions about a National Security Agency (NSA) backdoor. DES consequently came under intense academic scrutiny which motivated the modern understanding of block ciphers and their cryptanalysis.

DES is now considered to be insecure for many applications. This is chiefly due to the 56-bit key size being too small; in January, 1999, and the Electronic Frontier Foundation collaborated to publicly break a DES key in 22 hours and 15 minutes. There are also some analytical results which demonstrate theoretical weaknesses in the cipher, although they are unfeasible to mount in practice. The algorithm is believed to be practically secure in the form of Triple DES, although there are theoretical attacks. In recent years, the cipher has been superseded by the Advanced Encryption Standard (AES).

In some documentation, a distinction is made between DES as a standard and DES the algorithm which is referred to as the DEA (the Data Encryption Algorithm). (Source: Wikipedia. See LicenseTerms)

In the following tutorial, I have tried to demonstrate in a very simple way:

  • How to do a DES Encryption of a plain text
  • How to decrypt a text that has once been encrypted using DES Encryption

Note that there is a secretKey involved (myEncryptionKey).

 * Author - Kushal Paudyal
 * Last Modified On 06-19-2009
package com.kushal.utils;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESEncryption {

	private static final String UNICODE_FORMAT = "UTF8";
	public static final String DES_ENCRYPTION_SCHEME = "DES";
	private KeySpec myKeySpec;
	private SecretKeyFactory mySecretKeyFactory;
	private Cipher cipher;
	byte[] keyAsBytes;
	private String myEncryptionKey;
	private String myEncryptionScheme;
	SecretKey key;

	public DESEncryption() throws Exception
		myEncryptionKey = "ThisIsSecretEncryptionKey";
		myEncryptionScheme = DES_ENCRYPTION_SCHEME;
		keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
		myKeySpec = new DESKeySpec(keyAsBytes);
		mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
		cipher = Cipher.getInstance(myEncryptionScheme);
		key = mySecretKeyFactory.generateSecret(myKeySpec);

	 * Method To Encrypt The String
	public String encrypt(String unencryptedString) {
		String encryptedString = null;
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
			byte[] encryptedText = cipher.doFinal(plainText);
			BASE64Encoder base64encoder = new BASE64Encoder();
			encryptedString = base64encoder.encode(encryptedText);
		} catch (Exception e) {
		return encryptedString;
	 * Method To Decrypt An Ecrypted String
	public String decrypt(String encryptedString) {
		String decryptedText=null;
		try {
			cipher.init(Cipher.DECRYPT_MODE, key);
			BASE64Decoder base64decoder = new BASE64Decoder();
			byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
			byte[] plainText = cipher.doFinal(encryptedText);
			decryptedText= bytes2String(plainText);
		} catch (Exception e) {
		return decryptedText;
	 * Returns String From An Array Of Bytes
	private static String bytes2String(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			stringBuffer.append((char) bytes[i]);
		return stringBuffer.toString();

	 * Testing the DES Encryption And Decryption Technique
	public static void main(String args []) throws Exception
		DESEncryption myEncryptor= new DESEncryption();

		String stringToEncrypt="";
		String encrypted=myEncryptor.encrypt(stringToEncrypt);
		String decrypted=myEncryptor.decrypt(encrypted);

		System.out.println("String To Encrypt: "+stringToEncrypt);
		System.out.println("Encrypted Value :" + encrypted);
		System.out.println("Decrypted Value :"+decrypted);



Here is the sample output:

String To
Encrypted Value: x57YpwPaa4Wa4kIAURuT1A==
Decrypted Value

One Way Password Encryption Using Java

Wonder how your passwords are generally stored by the web applications? One thing for sure, they are not stored as plain text, if the developers out there care about your password security. In this little Java Tutorial, I would like to demonstrate how to generate an encrypted password that can be stored in the database and is safe. I will show how the change in encryption algorithm and encoding affects the generation of the encrypted password. There are varieties of encrypting algorithms, I am using SHA and MD5.

 * @Author Kushal Paudyal
 * Last Modified On 2009-04-28
package com.kushal.utils;

import sun.misc.BASE64Encoder;

public final class MyPasswordEncrypt {
	public static synchronized String encrypt(String plaintext,
			String algorithm, String encoding) throws Exception {
		MessageDigest msgDigest = null;
		String hashValue = null;
		try {
			msgDigest = MessageDigest.getInstance(algorithm);
			byte rawByte[] = msgDigest.digest();
			hashValue = (new BASE64Encoder()).encode(rawByte);

		} catch (NoSuchAlgorithmException e) {
			System.out.println("No Such Algorithm Exists");
		} catch (UnsupportedEncodingException e) {
			System.out.println("The Encoding Is Not Supported");
		return hashValue;

	public static void main(String args[]) throws Exception {
		String plainPassword = "SecretPassword";

		System.out.println("PlainTexttAlgotEncodingtEncrypted Password");
		System.out.println(plainPassword + "tSHAtUTF-8t"
				+ encrypt("MySecretPassword", "SHA", "UTF-8"));
		System.out.println(plainPassword + "tSHA-1tUTF-16t"
				+ encrypt("MySecretPassword", "SHA-1", "UTF-16"));
		System.out.println(plainPassword + "tMD5tUTF-8t"
				+ encrypt("MySecretPassword", "MD5", "UTF-8"));
		System.out.println(plainPassword + "tMD5tUTF-16t"
				+ encrypt("MySecretPassword", "MD5", "UTF-16"));


Here is the output of this program. Note the different
Encrypted Passwords for the same Plain Text Password

PlainText	        Algo	   Encoding	Encrypted Password
SecretPassword	SHA	   UTF-8	lScpxhyrfgHktfW6e5WDDSB190s=
SecretPassword	SHA-1  UTF-16	NfsACTQRTvkEV5kzrDY55vQR1ec=
SecretPassword	MD5	   UTF-8	cxWgEuytEFmjY0+L4TR4Rg==
SecretPassword	MD5	   UTF-16	JulkQ6YpxzLMlpIgU28xmg==


If you are interested in understanding what is SHA /MD5 and UTF Encoding, read below:

The SHA hash functions are a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the NIST as a U.S. Federal Information Processing Standard. SHA stands for Secure Hash Algorithm. The three SHA algorithms are structured differently and are distinguished as SHA-0, SHA-1, and SHA-2. The SHA-2 family uses an identical algorithm with a variable digest size which is distinguished as SHA-224, SHA-256, SHA-384, and SHA-512.

SHA-1 is the best established of the existing SHA hash functions, and is employed in several widely used security applications and protocols. In 2005, security flaws were identified in SHA-1, namely that a possible mathematical weakness might exist, indicating that a stronger hash function would be desirable. Although no attacks have yet been reported on the SHA-2 variants, they are algorithmically similar to SHA-1 and so efforts are underway to develop improved alternatives. A new hash standard, SHA-3, is currently under development the function will be selected via an open competition running between 2008 and 2012. [From Wikipedia. See License Terms]

In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value. As an Internet standard (RFC 1321), MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of files. However, it has been shown that MD5 is not collision resistant; as such, MD5 is not suitable for applications like SSL certificates or digital signatures that rely on this property. An MD5 hash is typically expressed as a 32 digit hexadecimal number.

MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. In 1996, a flaw was found with the design of MD5. While it was not a clearly fatal weakness, cryptographers began recommending the use of other algorithms, such as SHA-1 (which has since been found vulnerable). In 2004, more serious flaws were discovered, making further use of the algorithm for security purposes questionable. In 2007 a group of researchers including Arjen Lenstra described how to create a pair of files that share the same MD5 checksum. In an attack on MD5 published in December 2008, a group of researchers used this technique to fake SSL certificate validity. [From Wikipedia. See License Terms]

UTF Stands for Unicode Transformation Format. It is one of the method of character encoding for unicode.