Skip to content

Instantly share code, notes, and snippets.

@armanso
Last active July 11, 2024 07:20
Show Gist options
  • Save armanso/007c52c746608cd8d66d7fb11239e621 to your computer and use it in GitHub Desktop.
Save armanso/007c52c746608cd8d66d7fb11239e621 to your computer and use it in GitHub Desktop.
RSA Helper for java, Works with PEM format
/**
* Simple object that keep private and public key
*/
public class PPKeys {
private String privateKey;
private String publicKey;
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getPrivatekey() {
return privateKey;
}
public void setPrivatekey(String privatekey) {
this.privateKey = privatekey;
}
}
import com.sun.jersey.core.util.Base64;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.InvalidKeyException;
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.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
*
* RSA Helper class
* Generate private/public keys with PEM format
* Encrypt/Decrypt with public/private key in PEM format
*
*
*/
public class RSA {
static {
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
/**
*
* @param keySize
* @return PPKeys object that contain private and public keys
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static PPKeys createKeys(int keySize) throws NoSuchAlgorithmException, IOException {
PPKeys keys = new PPKeys();
// Create keyPair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Convert PrivateKey to PEM format
StringWriter privateWrite = new StringWriter();
PEMWriter privatePemWriter = new PEMWriter(privateWrite);
privatePemWriter.writeObject(keyPair.getPrivate());
privatePemWriter.close();
keys.setPrivatekey(privateWrite.toString());
privatePemWriter.close();
privateWrite.close();
// Convert PublicKey to PEM format
StringWriter publicWrite = new StringWriter();
PEMWriter publicPemWriter = new PEMWriter(publicWrite);
publicPemWriter.writeObject(keyPair.getPublic());
publicPemWriter.close();
keys.setPublicKey(publicWrite.toString());
publicPemWriter.close();
publicWrite.close();
return keys;
}
/**
*
* @param publicKeyPem
* @param plainText
* @return encrypted string
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String encrypt(String publicKeyPem,String plainText) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// Read PEM Format
PemReader pemReader = new PemReader(new StringReader(publicKeyPem));
byte[] content = pemReader.readPemObject().getContent();
// Get X509EncodedKeySpec format
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(content);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKeySecret = kf.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKeySecret);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return new String(Base64.encode(encryptedBytes));
}
/**
*
* @param privateKeyPem
* @param encryptedString
* @return decrypted string
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String decrypt(String privateKeyPem,String encryptedString) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// Read PEM Format
PemReader pemReader = new PemReader(new StringReader(privateKeyPem));
PemObject pemObject = pemReader.readPemObject();
pemReader.close();
// Get PKCS8EncodedKeySpec for decrypt
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemObject.getContent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKeySecret = kf.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKeySecret);
return new String(cipher.doFinal(Base64.decode(encryptedString)), "UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment