Last active
November 2, 2023 15:56
-
-
Save prahladyeri/15a6ec12c0da3a7ea9615170ccf93ea9 to your computer and use it in GitHub Desktop.
Basic implementation of text encryption/decryption in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.prahladyeri.utils; | |
import java.util.Arrays; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
public class Crypto | |
{ | |
private String salt="972$%#@!)(><?|:}"; | |
//private String salt = "1234567890123456"; | |
//never use space in the message | |
public String encrypt(String message) throws Exception | |
{ | |
//String salt = "1111111111111111"; | |
SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
byte[] cipherBytes= cipher.doFinal(message.getBytes()); | |
return new String(cipherBytes); | |
} | |
public String decrypt(String message) throws Exception | |
{ | |
//String salt = "1111111111111111"; | |
SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); | |
cipher.init(Cipher.DECRYPT_MODE, key); | |
byte[] plainBytes= cipher.doFinal(message.getBytes()); | |
return new String(plainBytes); | |
} | |
public String Encode(String text) | |
{ | |
String result=""; | |
for(int i=0;i<text.length();i++) | |
{ | |
int ccode= (int)text.charAt(i); | |
ccode+=3; | |
result+=ccode; | |
} | |
return result; | |
} | |
public String Decode(String text) | |
{ | |
String result=""; | |
for(int i=0;i<text.length();i+=2) | |
{ | |
int ccode= Integer.parseInt( text.substring(i, i+2)); | |
ccode-=3; | |
result+=(char)ccode; | |
} | |
return result; | |
} | |
public static void main(String[] args) throws Exception | |
{ | |
Crypto crypto=new Crypto(); | |
//String plain="11680-364"; | |
//String cipher=crypto.encrypt(plain); | |
//System.out.println("plain:" + plain); | |
//System.out.println("cipher:" + cipher); | |
//System.out.println("back to plain:" + crypto.decrypt(cipher)); | |
//System.out.println("Result:" + crypto.decrypt("?l&*?Z?t?#?(???")); | |
System.out.println(crypto.Encode("0Z")); | |
System.out.println(crypto.Decode("52575159515160")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment