Skip to content

Instantly share code, notes, and snippets.

@codeachange
Created December 5, 2016 03:40
Show Gist options
  • Save codeachange/a0d1218c9ef0b0670904e62778f6ed12 to your computer and use it in GitHub Desktop.
Save codeachange/a0d1218c9ef0b0670904e62778f6ed12 to your computer and use it in GitHub Desktop.
RSA encrypt and decrypt in JAVA
package tests;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Test {
/**
Generate key file using openssl
1、key pair
openssl genrsa -out private_key.pem 2048
2、public key
openssl rsa -in private_key.pem -pubout -outform DER -out tst_public.der
3、private key
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
*/
public static void main(String[] args) throws Exception {
String privateKeyFilePath = "/path/to/private/key/file";
Path privateKeyPath = Paths.get(privateKeyFilePath);
byte[] privateKeyBytes = Files.readAllBytes(privateKeyPath);
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
String publicKeyFilePath = "/path/to/public/key/file";
Path publicKeyPath = Paths.get(publicKeyFilePath);
byte[] publicKeyBytes = Files.readAllBytes(publicKeyPath);
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
String str = "abcdefghijklmnopqrstuvwxyz1234567890";
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encStr = cipher.doFinal(str.getBytes());
System.out.println(new String(Base64.encodeBase64(encStr)));
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decStr = cipher1.doFinal(encStr);
System.out.println(new String(decStr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment