-
-
Save tomkul/d13adb4bf8c2d161b081695d5ecf5ae2 to your computer and use it in GitHub Desktop.
RSA encrypt and decrypt in JAVA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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