Skip to content

Instantly share code, notes, and snippets.

@Anass-ABEA
Last active November 11, 2021 09:57
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Anass-ABEA/2579fc6cbdc4ecf5a7d7e5e581f69ca1 to your computer and use it in GitHub Desktop.
helper methods to encode and decode Strings using the Base64 encoder and decoder
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
/**
* @author Anass AIT BEN EL ARBI
* <ul>
* <li>RSA/ECB/PKCS1Padding (1024, 2048)</li>
* </ul>
* <p>
* for more details @see <a href="https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html">Java Ciphers</a>
*/
public class RSA {
private PrivateKey privateKey;
private PublicKey publicKey;
public RSA() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair pair = generator.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
} catch (Exception ignored) {
}
}
public String encrypt(String message) throws Exception{
byte[] messageToBytes = message.getBytes();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] encryptedBytes = cipher.doFinal(messageToBytes);
return encode(encryptedBytes);
}
private String encode(byte[] data){
return Base64.getEncoder().encodeToString(data);
}
public String decrypt(String encryptedMessage) throws Exception{
byte[] encryptedBytes = decode(encryptedMessage);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] decryptedMessage = cipher.doFinal(encryptedBytes);
return new String(decryptedMessage,"UTF8");
}
private byte[] decode(String data){
return Base64.getDecoder().decode(data);
}
public static void main(String[] args) {
RSA rsa = new RSA();
try{
String encryptedMessage = rsa.encrypt("Hello World");
String decryptedMessage = rsa.decrypt(encryptedMessage);
System.err.println("Encrypted:\n"+encryptedMessage);
System.err.println("Decrypted:\n"+decryptedMessage);
}catch (Exception ingored){}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment