Java Code Examples for org.bouncycastle.asn1.x509.Certificate#getInstance()
The following examples show how to use
org.bouncycastle.asn1.x509.Certificate#getInstance() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CaHelper.java From julongchain with Apache License 2.0 | 6 votes |
public static Certificate loadCertificateSM2(String certPath) throws JulongChainException { File certDir = new File(certPath); File[] files = certDir.listFiles(); if (!certDir.isDirectory() || files == null) { log.error("invalid directory for certPath " + certPath); return null; } for (File file : files) { if (!file.getName().endsWith(".pem")) { continue; } try { InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); PemReader pemReader = new PemReader(reader); PemObject pemObject = pemReader.readPemObject(); reader.close(); byte[] certBytes = pemObject.getContent(); return Certificate.getInstance(certBytes); } catch (Exception e) { throw new JulongChainException("An error occurred :" + e.getMessage()); } } throw new JulongChainException("no pem file found"); }
Example 2
Source File: MspValidateTest.java From julongchain with Apache License 2.0 | 6 votes |
@Test public void certTest() throws IOException { String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" + "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" + "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" + "C8r6EmyE"; byte[] sk = org.bouncycastle.util.encoders.Base64.decode(privateKey); System.out.println("私钥长度" + sk.length); System.out.println(Hex.toHexString(sk)); String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath(); byte[] idBytes = FileUtils.readFileBytes(cert_path); Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent()); byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); System.out.println(certificate.getSubject()); System.out.println("公钥:" + Hex.toHexString(publickey)); System.out.println("公钥长度:" + publickey.length); }
Example 3
Source File: CertTest.java From julongchain with Apache License 2.0 | 6 votes |
@Test public void szcaCertTest() throws Exception { String skPath = "/szca/sk-test"; String certPath = "/szca/signcert.pem"; String testData = "this is test data"; String privateKeyPath = CertTest.class.getResource(skPath).getPath(); String signCertPath = CertTest.class.getResource(certPath).getPath(); byte[] sk = CryptoUtil.getPrivateKey(privateKeyPath); byte[] certBytes = FileUtils.readFileBytes(signCertPath); Certificate signCert = Certificate.getInstance( new PemReader(new InputStreamReader(new ByteArrayInputStream(certBytes))).readPemObject().getContent()); byte[] pk = signCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); byte[] sign = sm2.sign(sk, testData.getBytes()); boolean result = sm2.verify(pk, sign, testData.getBytes()); assertEquals(true, result); }
Example 4
Source File: CtLogTest.java From xipki with Apache License 2.0 | 6 votes |
private void parseCtLogInCert(String certFile) throws Exception { byte[] certBytes = IoUtil.read(getClass().getResourceAsStream(certFile)); certBytes = X509Util.toDerEncoded(certBytes); Certificate cert = Certificate.getInstance(certBytes); Extension extn = cert.getTBSCertificate().getExtensions().getExtension( ObjectIdentifiers.Extn.id_SCTs); byte[] encodedScts = DEROctetString.getInstance(extn.getParsedValue()).getOctets(); SignedCertificateTimestampList sctList2 = SignedCertificateTimestampList.getInstance(encodedScts); SignedCertificateTimestamp sct = sctList2.getSctList().get(0); sct.getDigitallySigned().getEncoded(); sctList2.getSctList().get(0).getDigitallySigned().getSignatureObject(); byte[] encoded2 = sctList2.getEncoded(); Assert.assertArrayEquals(encodedScts, encoded2); }
Example 5
Source File: CAdESTimestampSource.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@Override protected List<Identifier> getEncapsulatedCertificateIdentifiers(CAdESAttribute unsignedAttribute) { List<Identifier> certificateIdentifiers = new ArrayList<>(); ASN1Sequence seq = (ASN1Sequence) unsignedAttribute.getASN1Object(); for (int ii = 0; ii < seq.size(); ii++) { try { final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii)); CertificateToken certificateToken = DSSUtils.loadCertificate(cs.getEncoded()); certificateIdentifiers.add(certificateToken.getDSSId()); } catch (Exception e) { String errorMessage = "Unable to parse an encapsulated certificate : {}"; if (LOG.isDebugEnabled()) { LOG.warn(errorMessage, e.getMessage(), e); } else { LOG.warn(errorMessage, e.getMessage()); } } } return certificateIdentifiers; }
Example 6
Source File: CMSCertificateSource.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void extractCertificateValues() { AttributeTable unsignedAttributes = currentSignerInformation.getUnsignedAttributes(); if (unsignedAttributes != null) { Attribute attribute = unsignedAttributes.get(id_aa_ets_certValues); if (attribute != null) { final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0); for (int ii = 0; ii < seq.size(); ii++) { try { final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii)); addCertificate(DSSUtils.loadCertificate(cs.getEncoded()), CertificateOrigin.CERTIFICATE_VALUES); } catch (Exception e) { LOG.warn("Unable to parse encapsulated certificate : {}", e.getMessage()); } } } } }
Example 7
Source File: Msp.java From julongchain with Apache License 2.0 | 5 votes |
/** * 解析x509证书 * * @param idBytes * @return * @throws IOException * @throws MspException */ public Certificate getCertFromPem(byte[] idBytes) throws IOException, MspException { Certificate certificate = null; if (idBytes == null) { throw new MspException("GetCertFrom Pem error the idBytes is null"); } certificate = Certificate.getInstance(new PemReader (new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent()); return certificate; }
Example 8
Source File: IssuerEntry.java From xipki with Apache License 2.0 | 5 votes |
private static Map<HashAlgo, byte[]> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException { byte[] encodedName; byte[] encodedKey; try { Certificate bcCert = Certificate.getInstance(encodedCert); encodedName = bcCert.getSubject().getEncoded("DER"); encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); } catch (IllegalArgumentException | IOException ex) { throw new CertificateEncodingException(ex.getMessage(), ex); } Map<HashAlgo, byte[]> hashes = new HashMap<>(); for (HashAlgo ha : HashAlgo.values()) { int hlen = ha.getLength(); byte[] nameAndKeyHash = new byte[(2 + hlen) << 1]; int offset = 0; nameAndKeyHash[offset++] = 0x04; nameAndKeyHash[offset++] = (byte) hlen; System.arraycopy(ha.hash(encodedName), 0, nameAndKeyHash, offset, hlen); offset += hlen; nameAndKeyHash[offset++] = 0x04; nameAndKeyHash[offset++] = (byte) hlen; System.arraycopy(ha.hash(encodedKey), 0, nameAndKeyHash, offset, hlen); hashes.put(ha, nameAndKeyHash); } return hashes; }
Example 9
Source File: EjbcaIssuerEntry.java From xipki with Apache License 2.0 | 5 votes |
private static Map<HashAlgo, byte[]> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException { byte[] encodedName; byte[] encodedKey; try { Certificate bcCert = Certificate.getInstance(encodedCert); encodedName = bcCert.getSubject().getEncoded("DER"); encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); } catch (IllegalArgumentException | IOException ex) { throw new CertificateEncodingException(ex.getMessage(), ex); } Map<HashAlgo, byte[]> hashes = new HashMap<>(); for (HashAlgo ha : HashAlgo.values()) { int hlen = ha.getLength(); byte[] nameAndKeyHash = new byte[(2 + hlen) << 1]; int offset = 0; nameAndKeyHash[offset++] = 0x04; nameAndKeyHash[offset++] = (byte) hlen; System.arraycopy(ha.hash(encodedName), 0, nameAndKeyHash, offset, hlen); offset += hlen; nameAndKeyHash[offset++] = 0x04; nameAndKeyHash[offset++] = (byte) hlen; System.arraycopy(ha.hash(encodedKey), 0, nameAndKeyHash, offset, hlen); hashes.put(ha, nameAndKeyHash); } return hashes; }
Example 10
Source File: ProxyMessage.java From xipki with Apache License 2.0 | 5 votes |
private static Certificate getCertificate0(ASN1Encodable object) throws BadAsn1ObjectException { try { return Certificate.getInstance(object); } catch (IllegalArgumentException ex) { throw new BadAsn1ObjectException("invalid object Certificate: " + ex.getMessage(), ex); } }
Example 11
Source File: ScepUtil.java From xipki with Apache License 2.0 | 5 votes |
public static List<X509Cert> getCertsFromSignedData(SignedData signedData) throws CertificateException { Args.notNull(signedData, "signedData"); ASN1Set set = signedData.getCertificates(); if (set == null) { return Collections.emptyList(); } final int n = set.size(); if (n == 0) { return Collections.emptyList(); } List<X509Cert> certs = new LinkedList<>(); X509Cert eeCert = null; for (int i = 0; i < n; i++) { X509Cert cert; try { cert = new X509Cert(Certificate.getInstance(set.getObjectAt(i))); } catch (IllegalArgumentException ex) { throw new CertificateException(ex); } if (eeCert == null && cert.getBasicConstraints() == -1) { eeCert = cert; } else { certs.add(cert); } } if (eeCert != null) { certs.add(0, eeCert); } return certs; }
Example 12
Source File: CrlStreamParserTest.java From xipki with Apache License 2.0 | 5 votes |
private static Certificate parseCert(String fileName) throws IOException, CertificateEncodingException { try { return Certificate.getInstance( X509Util.toDerEncoded(Files.readAllBytes(Paths.get(fileName)))); } catch (RuntimeException ex) { throw new CertificateEncodingException("error decoding certificate: " + ex.getMessage()); } }
Example 13
Source File: CertTest.java From julongchain with Apache License 2.0 | 5 votes |
@Test public void cryptogenCertTest() throws IOException, CspException { String skPath = "msp/keystore"; String signcerts = "msp/signcerts"; String testData = "this is test data"; //签名证书 List<byte[]> signCerts = new LoadLocalMspFiles().getCertFromDir(signcerts); Certificate signCert = Certificate.getInstance( new PemReader(new InputStreamReader(new ByteArrayInputStream(signCerts.get(0)))).readPemObject().getContent()); byte[] publickey = signCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); List<byte[]> sks = new LoadLocalMspFiles().getSkFromDir(skPath); byte[] sign = sm2.sign(sks.get(0), testData.getBytes()); boolean result = sm2.verify(publickey, sign, testData.getBytes()); assertEquals(true, result); }
Example 14
Source File: MspValidateTest.java From julongchain with Apache License 2.0 | 5 votes |
@Test public void base64() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CryptoException, CspException { Security.addProvider(new BouncyCastleProvider()); String sk = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" + "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" + "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" + "C8r6EmyE"; KeyFactory keyf = keyf = KeyFactory.getInstance("EC"); PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(sk)); BCECPrivateKey priKey = (BCECPrivateKey) keyf.generatePrivate(priPKCS8); System.out.println("16进制私钥:" + priKey.getD().toString(16)); String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath(); byte[] idBytes = FileUtils.readFileBytes(cert_path); Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent()); byte[] pb = certificate.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); System.out.println(certificate.getSubject()); System.out.println("tbs 公钥" + Hex.toHexString(pb)); System.out.println("公钥:" + Hex.toHexString(publickey)); System.out.println("公钥长度:" + publickey.length); SM2 sm2 = new SM2(); byte[] v = sm2.sign(priKey.getD().toByteArray(), "123".getBytes()); System.out.println(sm2.verify(publickey, v, "123".getBytes())); }
Example 15
Source File: Msp.java From julongchain with Apache License 2.0 | 5 votes |
public IIdentity deserializeIdentityInternal(byte[] serializedIdentity) throws MspException { Certificate cert = Certificate.getInstance(serializedIdentity); byte[] pbBytes = cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); IKey certPubK = null; try { certPubK = csp.keyImport(pbBytes, new SM2PublicKeyImportOpts(true)); } catch (JulongChainException e) { throw new MspException(e.getMessage()); } IIdentity identity = new Identity(cert, certPubK, this); return identity; }
Example 16
Source File: KeyStoreGenerator.java From cute-proxy with BSD 2-Clause "Simplified" License | 4 votes |
/** * Generate cert for the domain signed by root certificate * look at RFC 2818 * * @param host add to san extension, can be generic * @throws Exception */ public PrivateKeyAndCertChain generateCertChain(String host, int validityDays) throws Exception { logger.debug("Generating certificate for host {}", host); // generate the key pair for the new certificate KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, secureRandom); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); Calendar calendar = Calendar.getInstance(); // in case client time behind server time calendar.add(Calendar.DAY_OF_YEAR, -1); Date startDate = calendar.getTime(); calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_YEAR, validityDays); Date expireDate = calendar.getTime(); String appDName = "CN=ClearTheSky, OU=TianCao, O=TianCao, L=Beijing, ST=Beijing, C=CN"; X500Name subject = new X500Name(appDName); var sigOID = PKCSObjectIdentifiers.sha256WithRSAEncryption; var sigAlgId = new AlgorithmIdentifier(sigOID, DERNull.INSTANCE); var generator = new V3TBSCertificateGenerator(); generator.setSerialNumber(new ASN1Integer(random.nextLong() + System.currentTimeMillis())); generator.setIssuer(getSubject(rootCert)); generator.setSubject(subject); generator.setSignature(sigAlgId); generator.setSubjectPublicKeyInfo(getPublicKeyInfo(publicKey)); generator.setStartDate(new Time(startDate)); generator.setEndDate(new Time(expireDate)); // Set SubjectAlternativeName var extensionsGenerator = new ExtensionsGenerator(); extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, () -> { ASN1EncodableVector nameVector = new ASN1EncodableVector(); int hostType = Networks.getHostType(host); if (hostType == Networks.HOST_TYPE_IPV4 || hostType == Networks.HOST_TYPE_IPV6) { nameVector.add(new GeneralName(GeneralName.iPAddress, host)); } else { nameVector.add(new GeneralName(GeneralName.dNSName, host)); } return GeneralNames.getInstance(new DERSequence(nameVector)).toASN1Primitive(); }); Extensions x509Extensions = extensionsGenerator.generate(); generator.setExtensions(x509Extensions); var tbsCertificateStructure = generator.generateTBSCertificate(); byte[] data = toBinaryData(tbsCertificateStructure); byte[] signatureData = signData(sigOID, data, privateKeyParameters, secureRandom); var asn1EncodableVector = new ASN1EncodableVector(); asn1EncodableVector.add(tbsCertificateStructure); asn1EncodableVector.add(sigAlgId); asn1EncodableVector.add(new DERBitString(signatureData)); var derSequence = new DERSequence(asn1EncodableVector); Certificate certificate = Certificate.getInstance(derSequence); X509CertificateObject clientCertificate = new X509CertificateObject(certificate); logger.debug("Verifying certificate for correct signature with CA public key"); clientCertificate.verify(rootCert.getPublicKey()); clientCertificate.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString("Certificate for CuteProxy App")); clientCertificate.setBagAttribute(pkcs_9_at_localKeyId, jcaX509ExtensionUtils.createSubjectKeyIdentifier(publicKey)); return new PrivateKeyAndCertChain(privateKey, new X509Certificate[]{clientCertificate, rootCert}); }
Example 17
Source File: CaHelperTest.java From julongchain with Apache License 2.0 | 4 votes |
@Test public void loadCertificateSM2() throws Exception { String caDir = Paths.get(testDir, "ca").toString(); String certDir = Paths.get(testDir, "certs").toString(); IKey priv = CspHelper.generatePrivateKey(certDir); ECPublicKey ecPubKey = CspHelper.getSM2PublicKey(priv); Assert.assertNotNull(ecPubKey); CaHelper rootCA = CaHelper.newCA(caDir, testCA3Name, testCA3Name, testCountry, testProvince, testLocality, testOrganizationalUnit, testStreetAddress, testPostalCode); X509Certificate cert = rootCA.signCertificate(certDir, testName3, null, null, ecPubKey, KeyUsage.digitalSignature | KeyUsage.keyEncipherment, new int[]{Util.EXT_KEY_USAGE_ANY}); try { KeyUsageExtension keyUsageExt = (KeyUsageExtension) X509CertImpl.toImpl(cert).getExtension(new ObjectIdentifier(new int[]{2,5,29,15})); Assert.assertEquals(KeyUsage.digitalSignature | KeyUsage.keyEncipherment, parseKeyUsage(keyUsageExt.getBits())); } catch (Exception e) { Assert.fail(); } if (!certDir.endsWith(File.separator)) { certDir += File.separator; } Certificate bcCert = Certificate.getInstance(cert.getEncoded()); Certificate loadedCert = CaHelper.loadCertificateSM2(certDir); Assert.assertNotNull(loadedCert); Assert.assertEquals(bcCert.getSerialNumber(), loadedCert.getSerialNumber()); Assert.assertEquals(X509CertificateUtil.getSubject(cert.getSubjectDN().getName()).getCommonName(), X509CertificateUtil.getSubject(loadedCert.getSubject().toString()).getCommonName()); FileUtil.removeAll(testDir); }
Example 18
Source File: CtLogServlet.java From xipki with Apache License 2.0 | 4 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { AddPreChainRequest req0 = parse(req.getInputStream(), AddPreChainRequest.class); List<byte[]> chain = req0.getChain(); if (chain == null || chain.size() < 2) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "chain has less than two certificates"); return; } Certificate cert = Certificate.getInstance(chain.get(0)); Certificate caCert = Certificate.getInstance(chain.get(1)); byte[] issuerKeyHash = HashAlgo.SHA256.hash(caCert.getSubjectPublicKeyInfo().getEncoded()); byte[] preCertTbsCert = CtLog.getPreCertTbsCert(cert.getTBSCertificate()); byte sctVersion = 0; long timestamp = System.currentTimeMillis(); byte[] sctExtensions = null; Signature sig = Signature.getInstance(signatureAlgo); sig.initSign(signingKey); CtLog.update(sig, sctVersion, timestamp, sctExtensions, issuerKeyHash, preCertTbsCert); byte[] signature = sig.sign(); AddPreChainResponse resp0 = new AddPreChainResponse(); resp0.setSct_version(sctVersion); resp0.setId(logId); resp0.setTimestamp(timestamp); DigitallySigned digitallySigned = new DigitallySigned(signatureAndHashAlgorithm, signature); resp0.setSignature(digitallySigned.getEncoded()); byte[] respContent = JSON.toJSONBytes(resp0); resp.setContentType("application/json"); resp.setContentLengthLong(respContent.length); resp.getOutputStream().write(respContent); resp.setStatus(HttpServletResponse.SC_OK); } catch (Exception ex) { throw new ServletException(ex.getMessage(), ex); } }
Example 19
Source File: CaHelper.java From julongchain with Apache License 2.0 | 4 votes |
public static CaHelper newCA(String baseDir, String org, String name, String country, String province, String locality, String orgUnit, String streetAddress, String postalCode) throws JulongChainException { FileUtil.mkdirAll(Paths.get(baseDir)); IKey privateKey = CspHelper.generatePrivateKey(baseDir); ECPublicKey ecPublicKey = CspHelper.getSM2PublicKey(privateKey); try { if (!(privateKey instanceof SM2Key)) { throw new JulongChainException("privateKey is not the instance of SM2Key"); } X509CertInfo x509CertInfo = new X509CertInfo(); x509CertInfo.set("version", new CertificateVersion(2)); x509CertInfo.set("serialNumber", new CertificateSerialNumber((new Random()).nextInt() & 2147483647)); x509CertInfo.set("key", new CertificateX509Key(ecPublicKey)); // 设置证书 organization 字段 X500Name subject = subjectTemplateAdditional(name, country, province, locality, org, new String[]{orgUnit}, streetAddress, postalCode); x509CertInfo.set("subject", subject); x509CertInfo.set("issuer", subject); AlgorithmId algorithmId = SM2X509CertImpl.SM3_WITH_SM2_ALGORITHM_ID; x509CertInfo.set("algorithmID", new CertificateAlgorithmId(algorithmId)); x509CertInfo.set("validity", Util.getCertificateValidity(10, 0, 0)); CertificateExtensions exts = new CertificateExtensions(); exts.set("keyUsage", Util.parseKeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.keyEncipherment | KeyUsage.cRLSign)); exts.set("extendedKeyUsage", Util.parseExtendedKeyUsage(new int[]{Util.EXT_KEY_USAGE_ANY})); x509CertInfo.set("extensions", exts); exts.set("SubjectKeyIdentifier", new SubjectKeyIdentifierExtension(privateKey.ski())); SM2X509CertImpl caCert = new SM2X509CertImpl(x509CertInfo); genCertificateSM2(baseDir, name, caCert, algorithmId, privateKey); return new CaHelper(name, country, province, locality, orgUnit, streetAddress, postalCode, privateKey, Certificate.getInstance(caCert.getEncoded())); } catch (Exception e) { throw new JulongChainException("An error occurred on newCA: " + e.getMessage()); } }