Java-RSA Encryption and Decryption with example

RSA is a asymmetric encryption, in which a key needed to encrypt data is made public, but the corresponding key needed to decrypt it is kept private, for example in a file on the server to which clients connect. In principle, such a system solves the problem of how to send a temporary encryption key securely to the server when opening a secure connection*. A very common asymmetric encryption system is RSA, named after inventors Rivest, Shamir & Adleman.

Example:


package com.knowledgefactory;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSA {
public PrivateKey privateKey;
public PublicKey publicKey;
public RSA() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair pair = keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public PublicKey getPublicKey() {
return publicKey;
}
// convert String publickey to Key object
public static Key loadPublicKey(String stored) throws GeneralSecurityException, IOException {
byte[] data = Base64.getDecoder().decode((stored.getBytes()));
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}
// Encrypt using publickey
public static String encryptMessage(String plainText, String publickey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publickey));
return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes()));
}
// Decrypt using privatekey
public static String decryptMessage(String encryptedText, String privatekey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privatekey));
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)));
}
// Convert String private key to privateKey object
public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
byte[] clear = Base64.getDecoder().decode((key64.getBytes()));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}
public static void main(String[] args) throws Exception {
final String secretText = "www.knowledgefactory.net";
RSA keyPairGenerator = new RSA();
// Generate private and public key
String privateKey = Base64.getEncoder().encodeToString(keyPairGenerator.getPrivateKey().getEncoded());
String publicKey = Base64.getEncoder().encodeToString(keyPairGenerator.getPublicKey().getEncoded());
System.out.println("Private Key: " + privateKey);
System.out.println("Public Key: " + publicKey);
// Encrypt secret text using public key
String encryptedValue = RSA.encryptMessage(secretText, publicKey);
System.out.println("Encrypted Value: " + encryptedValue);
// Decrypt
String decryptedText = RSA.decryptMessage(encryptedValue, privateKey);
System.out.println("Decrypted output: " + decryptedText);
}
}


Output:



Private Key: MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIPEiMuc3Oqaatphpp+ZjdngrH5o+Lu/+2PdpzU0rYYj9J701jOf/mEGZavu86vjymxamIHaqjiWGXg43oSAVZQQ7U6xbw1tj+Kju7VoNCaZavEf3gD9HiVHZkTVSLcUSaVCbEu00KU3vgaJMJEXiBh0b0whczS0aoK5Tev5+lAHAgMBAAECgYAjqGC4cQebeRQnaruTfxNS/ajQQInnDOnzuXzROiMnJL3C8lCxAb/t87Q51d0dC/SwY8fXhBwCWiQkU4dr5erCVZEz50vDAGjGjGokzpSI7Iq4/YWT50bWfLlR0OiOUHLdtqpAv3+v5Kd2EArdeQPJhSAMHErCuvecXyKwhqQ4MQJBANIMQOS9fhTVoSa+O7+zM049YAnBabXaDo6P1MwHwLvO0ed/8GO4qWKKViCPToyJk+bd3fUJ/aZJNFXeRd+HIF8CQQCgmDHsKoh81QEFHTbJPJvrSwyZ0geGZI5OQR3xSWdEuwAF44RFjdZxIp3sy55SGmmTZDtYCNzmV9JA3TLsflFZAkAc7okluKAcOIy47G0Ia6N+fF+1GEn6PW3R3yfdbpfyhntNGsc+xRm3s/xHAdY871pK63Z+IQEqHV0zEqmnL1KbAkBZP/wOqhysc5xbgT7fW8WzYEQigG0aLWxA5UOEwyyXL+31V9o85XTV700hOpBERNWDymKIrHRHt2rsDYKtmA4RAkBhnc5RikW21u9ULKlcs12WgCZmXbeONLPOgL9kC+PKzY2YcZD2vnAWD/nk0MlKaUUcO9h3mCGE23DEr6v8GlKf

Public Key: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDxIjLnNzqmmraYaafmY3Z4Kx+aPi7v/tj3ac1NK2GI/Se9NYzn/5hBmWr7vOr48psWpiB2qo4lhl4ON6EgFWUEO1OsW8NbY/io7u1aDQmmWrxH94A/R4lR2ZE1Ui3FEmlQmxLtNClN74GiTCRF4gYdG9MIXM0tGqCuU3r+fpQBwIDAQAB

Encrypted Value: cvf47ykaM7IAuJuXZhFWzE5eaYEweMI/nmRTeH+ku1ITtu+qDxGpX/GH5tIGZU4Qo6PccgzZ4qDBDV/ZY860FfeG8zIiarSIB0guU5bd3sAPD6e/E3jWOFl8QkY5SMqQVf2Rg6PgwV6fAUuK8qn5vnPtK6WoXStkFZAOYaSyI5E=

Decrypted output: www.knowledgefactory.net




This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments