利用BC轮换X509证书的公钥
利用BC替换X509证书的公钥
public static X509Certificate replaceCertPublicKey(final X509Certificate certificate,PublicKey _publicKey) throws CertificateException { //公钥算法 String pubAlg = _publicKey.getAlgorithm(); //签名算法 String sAlg = null; try { sAlg = AlgorithmId.get(pubAlg).getOID().toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } //证书主题 String subjectDN = certificate.getSubjectDN().getName(); String issueDn = certificate.getIssuerDN().getName(); X500Name subject = new X500Name(subjectDN); X500Name issuer = new X500Name(issueDn); //组装SubjectPublicKeyInfo byte[] publicKey = _publicKey.getEncoded(); SubjectPublicKeyInfo publicKeyInfo; if (sAlg.equals("1.2.156.197.1.301")) { publicKeyInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier( sAlg), publicKey); } else { publicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(publicKey)); } //序列号 BigInteger serial = certificate.getSerialNumber(); //有效日期 Date notBefore = certificate.getNotBefore(); Date notAfter = certificate.getNotAfter(); //组装 X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( issuer, serial, notBefore, notAfter, subject, publicKeyInfo); //签名 ContentSigner signer = new ContentSigner() { public byte[] getSignature() { return certificate.getSignature(); } public OutputStream getOutputStream() { return new ByteArrayOutputStream(); } public AlgorithmIdentifier getAlgorithmIdentifier() { return new AlgorithmIdentifier( AlgorithmId.sha1WithRSAEncryption_oid.toString()); } }; //生成证书 X509CertificateHolder certHolder = certBuilder.build(signer); byte[] certBuf = null; try { certBuf = certHolder.getEncoded(); } catch (IOException e) { e.printStackTrace(); } CertificateFactory cf = CertificateFactory.getInstance("X509"); return (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(certBuf)); }