Skip to content

Instantly share code, notes, and snippets.

@toraj58
Last active March 8, 2017 04:12
Show Gist options
  • Save toraj58/82c7f1205e3a9ea7cab953f22b21345a to your computer and use it in GitHub Desktop.
Save toraj58/82c7f1205e3a9ea7cab953f22b21345a to your computer and use it in GitHub Desktop.
RSA Example
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rsaexample;
/**
*
* @author touraj ebrahimi
*/
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class Main {
private static KeyPair keyPair;
private static KeyPair initKeyPair() {
try {
keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
} catch (NoSuchAlgorithmException e) {
System.err.println("Algorithm not supported! " + e.getMessage() + "!");
}
return keyPair;
}
public static void main(String[] args) throws InvalidKeyException, IllegalBlockSizeException {
initKeyPair();
try {
final Cipher cipher = Cipher.getInstance("RSA");
final String plaintext = "My Name Is Touraj...Hey Man";
// ENCRYPT using the PUBLIC key
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
System.out.println("enc byte : " + encryptedBytes);
//String chipertext = new String(Base64.getEncoder().encode(encryptedBytes));
// String chipertext = DatatypeConverter.printBase64Binary(encryptedBytes);
String chipertext = new String(encryptedBytes);
System.out.println("encrypted (chipertext) = " + chipertext);
// DECRYPT using the PRIVATE key
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
//byte[] ciphertextBytes = Base64.getDecoder().decode(chipertext.getBytes());
// byte[] ciphertextBytes = DatatypeConverter.parseBase64Binary(chipertext);
byte[] ciphertextBytes = chipertext.getBytes();
byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
String decryptedString = new String(decryptedBytes);
System.out.println("dec bytes : " + decryptedBytes);
System.out.println("decrypted (plaintext) = " + decryptedString);
} catch (NoSuchAlgorithmException e) {
System.err.println("Algorithm not supported! " + e.getMessage() + "!");
} catch (NoSuchPaddingException e) {
System.err.println("Cipher cannot be created!");
e.printStackTrace();
} catch (BadPaddingException e) {
System.err.println("An error occurred during the encryption!");
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment