利用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));
	}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值