String Encryption Java

String Encryption Java

If you are working on project where you need to encrypt string using Java then you could use below simple program to encrypt and decrypt string:

  • SimpleEncrypter.java:
import java.nio.charset.StandardCharsets;

public class SimpleEncrypter {

	public static void main(String[] args) {
		String encryptMe = "Java Honk";
		String encryptedString = encryptString(encryptMe);
		String decryptedString = decryptString(encryptedString);
		
		System.out.println("Original String: "+ encryptMe);
		System.out.println("Encrypted String: "+ encryptedString);
		System.out.println("Decrypted String: "+ decryptedString);

	}

	public static String decryptString(String encryptedString) {
		byte[] byteArray = encryptedString.getBytes(StandardCharsets.US_ASCII);
		for (int i = 0; i < byteArray.length; i++) {
			byteArray[i] += 8;
			byteArray[i] += 5;
		}

		return new String(byteArray, StandardCharsets.US_ASCII);
	}

	public static String encryptString(String plainText) {

		byte[] byteArray = plainText.getBytes(StandardCharsets.US_ASCII);
		for (int i = 0; i < byteArray.length; i++) {
			byteArray[i] -= 8;
			byteArray[i] -= 5;
		}

		return new String(byteArray, StandardCharsets.US_ASCII);

	}

}

 

  • Output:

String Encryption Java

 

  • For more information please visit Oracle documentation on encryption here

Leave a Reply

Your email address will not be published. Required fields are marked *