- red hat, centos
- yum install openssl
- ubuntu
- apt-get install openssl
- openssl genrsa -out private.pem 1024
- openssl rsa -in private.pem -out public.pem -outform PEM -pubout
# encrypt
openssl rsautl -encrypt -inkey public.pem -pubin -in plainTxt.file -out cipher.ssl
# decrypt
openssl rsautl -decrypt -inkey private.pem -in cihper.ssl -out decodePlainTxt.file
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
이런 에러가 난다면 pkcs8 방식으로 인코딩 변경 필요
-
private
- openssl rsa -in private.pem -inform pem -out private.der -outform der
- openssl pkcs8 -topk8 -in private.der -inform der -out private.key -outform der -nocrypt
-
public
- openssl rsa -in private.pem -inform pem -out public.key -outform der -pubout
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.io.IOUtils;
public class RSATest {
private String projectPath = System.getProperty("user.dir");
private String rsaPublicKeyPath = projectPath + "/pki/public.key";
private String rsaPrivateKeyPath = projectPath + "/pki/private.key";
private String rsaTransformation = "RSA/ECB/PKCS1Padding";
private String rsaEncoding = "UTF-8";
public static void main(String[] ar) {
RSATest rsa = new RSATest();
String enc = rsa.RSAEncrypt("test");
System.out.println(enc);
System.out.println(rsa.RSADecrypt(enc));
}
/*
* RSA Encrypt
*/
public String RSAEncrypt(String plainText) {
if ( plainText == null || "".equals(plainText)) {
return "";
}
try {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(IOUtils.toByteArray(new FileInputStream(rsaPublicKeyPath)));
Cipher cipher = Cipher.getInstance(rsaTransformation);
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec));
return org.apache.commons.codec.binary.Base64.encodeBase64String(cipher.doFinal(plainText.getBytes(rsaEncoding)));
} catch ( IOException | GeneralSecurityException e ) {
e.printStackTrace();
return plainText;
}
}
/*
* RSA Decrypt
*/
public String RSADecrypt(String cipherText) {
if ( cipherText == null || "".equals(cipherText)) {
return "";
}
try {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(new FileInputStream(rsaPrivateKeyPath)));
Cipher cipher = Cipher.getInstance(rsaTransformation);
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec));
return new String(cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(cipherText)), rsaEncoding);
} catch ( IOException | GeneralSecurityException e ) {
e.printStackTrace();
return cipherText;
}
}
}