Created
June 18, 2019 08:35
-
-
Save seraphy/3ad22ce2def1cdb7c344a5a15764e403 to your computer and use it in GitHub Desktop.
JavaのKeytoolを使ってRSA署名用のキーペアをPkcs12として作成し、公開キーをderファイルとしてエクスポートし、そのキーを使った暗号化と復号を行うための実装例。
This file contains 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 jp.seraphyware.example.java8learn.security; | |
import java.io.InputStream; | |
import java.nio.charset.StandardCharsets; | |
import java.security.KeyStore; | |
import java.security.PrivateKey; | |
import java.security.cert.CertificateFactory; | |
import java.security.cert.X509Certificate; | |
import java.util.Base64; | |
import javax.crypto.Cipher; | |
/** | |
* keytool -keystore rsa.p12 -storetype pkcs12 -keysize 2048 -keyalg rsa -genkeypair -validity 10000 -v | |
* | |
* でリソースディレクトリ上にpkcs12を生成する。 | |
* aliasを指定しない場合はデフォルト名は mykey になる。 | |
* | |
* keytool -keystore rsa.p12 -storetype pkcs12 -exportcert -alias mykey -file rsa.der | |
* | |
* で mykeyのpublickeyを証明書にしてエクスポートする。 | |
*/ | |
public class Pkcs12RsaEncryptExample { | |
public static void main(String[] args) throws Exception { | |
String plainText = "暗号化したい平文の文書テキスト"; | |
// 暗号化 | |
byte[] encrypted; | |
{ | |
// pkcs12のロード | |
KeyStore keyStore = KeyStore.getInstance("pkcs12"); | |
try (InputStream is = Pkcs12RsaEncryptExample.class.getResourceAsStream("/rsa.p12")) { | |
keyStore.load(is, "password".toCharArray()); | |
} | |
// rsaプライベートキーの取得 | |
PrivateKey privateKey = (PrivateKey) keyStore.getKey("mykey", "password".toCharArray()); | |
// 暗号機 | |
// https://docs.oracle.com/javase/jp/7/technotes/guides/security/StandardNames.html | |
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // ※ RSAはECBしかサポートしていないので | |
cipher.init(Cipher.ENCRYPT_MODE, privateKey); | |
// 暗号化 | |
encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); | |
System.out.println(Base64.getEncoder().encodeToString(encrypted)); | |
} | |
// 復号化 | |
{ | |
// x509証明書のロード | |
X509Certificate cert; | |
CertificateFactory x509Factory = CertificateFactory.getInstance("X.509"); | |
try (InputStream is = Pkcs12DsaSignatureExample.class.getResourceAsStream("/rsa.der")) { | |
cert = (X509Certificate) x509Factory.generateCertificate(is); | |
} | |
// 復号機 | |
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); | |
cipher.init(Cipher.DECRYPT_MODE, cert); | |
// 復号化 | |
byte[] decrypted = cipher.doFinal(encrypted); | |
String decryptedText = new String(decrypted, StandardCharsets.UTF_8); | |
System.out.println("decrypted=" + decryptedText); | |
boolean verified = plainText.equals(decryptedText); | |
System.out.println("verified=" + verified); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment