Created
March 31, 2015 01:54
-
-
Save zhaozg/22a38d9ad333f479dff1 to your computer and use it in GitHub Desktop.
java privatekey certificate pfx
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
/** | |
* @(#)文本1.java | |
* | |
* | |
* @author | |
* @version 1.00 2015/3/31 | |
*/ | |
import java.security.PrivateKey; | |
import java.io.*; | |
import java.security.*; | |
import java.security.spec.*; | |
import java.security.cert.*; | |
import org.bouncycastle.jce.provider.BouncyCastleProvider; | |
public class main { | |
public static PrivateKey getPrivateKey(String filename) | |
throws Exception { | |
File f = new File(filename); | |
FileInputStream fis = new FileInputStream(f); | |
DataInputStream dis = new DataInputStream(fis); | |
byte[] keyBytes = new byte[(int)f.length()]; | |
dis.readFully(keyBytes); | |
dis.close(); | |
PKCS8EncodedKeySpec spec = | |
new PKCS8EncodedKeySpec(keyBytes); | |
KeyFactory kf = KeyFactory.getInstance("RSA"); | |
return kf.generatePrivate(spec); | |
} | |
public static X509Certificate getCertificate(String filename) | |
throws Exception { | |
CertificateFactory fact = CertificateFactory.getInstance("X.509"); | |
FileInputStream is = new FileInputStream (filename); | |
X509Certificate cer = (X509Certificate) fact.generateCertificate(is); | |
return cer; | |
} | |
public static void main(String args[]) throws Exception{ | |
Security.addProvider(new BouncyCastleProvider()); | |
PrivateKey pkey = getPrivateKey("2048.der"); | |
X509Certificate cert = getCertificate("2048.cer"); | |
KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); | |
char[] password = "abc123".toCharArray(); | |
ks.load(null,null); | |
ks.setCertificateEntry(cert.getSerialNumber().toString(), cert); | |
ks.setKeyEntry(cert.getSerialNumber().toString(), pkey, password, new java.security.cert.Certificate[]{cert,cert}); | |
FileOutputStream fos = new FileOutputStream("2048.pfx"); | |
ks.store(fos, password); | |
fos.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment