List of usage examples for org.bouncycastle.asn1.x509 Certificate getSubjectPublicKeyInfo
public SubjectPublicKeyInfo getSubjectPublicKeyInfo()
From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.DHClientKeyExchangeHandler.java
License:Apache License
@Override byte[] prepareKeyExchangeMessage() { if (tlsContext.getServerDHParameters() == null) { // we are probably handling a simple DH ciphersuite, we try to // establish server public key parameters from the server // certificate message Certificate x509Cert = tlsContext.getServerCertificate(); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); DHPublicKeyParameters parameters; try {//from w ww .j a v a 2 s . c o m parameters = (DHPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); tlsContext.setServerDHParameters(new ServerDHParams(parameters)); } catch (IOException e) { throw new WorkflowExecutionException("Problem in parsing public key parameters from certificate", e); } } // generate client's original dh public and private key, based on the // server's public parameters AsymmetricCipherKeyPair kp = TlsDHUtils.generateDHKeyPair(new SecureRandom(), tlsContext.getServerDHParameters().getPublicKey().getParameters()); DHPublicKeyParameters dhPublic = (DHPublicKeyParameters) kp.getPublic(); DHPrivateKeyParameters dhPrivate = (DHPrivateKeyParameters) kp.getPrivate(); protocolMessage.setG(dhPublic.getParameters().getG()); protocolMessage.setP(dhPublic.getParameters().getP()); protocolMessage.setY(dhPublic.getY()); protocolMessage.setX(dhPrivate.getX()); // set the modified values of client's private and public parameters DHParameters newParams = new DHParameters(protocolMessage.getP().getValue(), protocolMessage.getG().getValue()); // DHPublicKeyParameters newDhPublic = new // DHPublicKeyParameters(dhMessage.getY().getValue(), newParams); DHPrivateKeyParameters newDhPrivate = new DHPrivateKeyParameters(protocolMessage.getX().getValue(), newParams); byte[] serializedPublicKey = BigIntegers.asUnsignedByteArray(protocolMessage.getY().getValue()); protocolMessage.setSerializedPublicKey(serializedPublicKey); protocolMessage.setSerializedPublicKeyLength(serializedPublicKey.length); byte[] result = ArrayConverter .concatenate( ArrayConverter.intToBytes(protocolMessage.getSerializedPublicKeyLength().getValue(), HandshakeByteLength.DH_PARAM_LENGTH), protocolMessage.getSerializedPublicKey().getValue()); byte[] premasterSecret = TlsDHUtils .calculateDHBasicAgreement(tlsContext.getServerDHParameters().getPublicKey(), newDhPrivate); protocolMessage.setPremasterSecret(premasterSecret); LOGGER.debug("Computed PreMaster Secret: {}", ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue())); byte[] random = tlsContext.getClientServerRandom(); PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getProtocolVersion(), tlsContext.getSelectedCipherSuite()); byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm, protocolMessage.getPremasterSecret().getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random, HandshakeByteLength.MASTER_SECRET); LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret)); protocolMessage.setMasterSecret(masterSecret); tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue()); return result; }
From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.ECDHClientKeyExchangeHandler.java
License:Apache License
@Override byte[] prepareKeyExchangeMessage() { if (tlsContext.getEcContext().getServerPublicKeyParameters() == null) { // we are probably handling a simple ECDH ciphersuite, we try to // establish server public key parameters from the server // certificate message Certificate x509Cert = tlsContext.getServerCertificate(); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); ECPublicKeyParameters parameters; try {/*from w ww .ja va 2 s .c o m*/ parameters = (ECPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters) parameters; tlsContext.getEcContext().setServerPublicKeyParameters(parameters); LOGGER.debug("Parsed the following EC domain parameters from the certificate: "); LOGGER.debug(" Curve order: {}", publicKeyParameters.getParameters().getCurve().getOrder()); LOGGER.debug(" Parameter A: {}", publicKeyParameters.getParameters().getCurve().getA()); LOGGER.debug(" Parameter B: {}", publicKeyParameters.getParameters().getCurve().getB()); LOGGER.debug(" Base point: {} ", publicKeyParameters.getParameters().getG()); LOGGER.debug(" Public key point Q: {} ", publicKeyParameters.getQ()); } catch (NoSuchMethodError e) { LOGGER.debug("The method was not found. It is possible that it is because an older bouncy castle" + " library was used. We try to proceed the workflow.", e); } catch (IOException e) { throw new WorkflowExecutionException("Problem in parsing public key parameters from certificate", e); } } AsymmetricCipherKeyPair kp = TlsECCUtils.generateECKeyPair(new SecureRandom(), tlsContext.getEcContext().getServerPublicKeyParameters().getParameters()); ECPublicKeyParameters ecPublicKey = (ECPublicKeyParameters) kp.getPublic(); ECPrivateKeyParameters ecPrivateKey = (ECPrivateKeyParameters) kp.getPrivate(); // do some ec point modification protocolMessage.setPublicKeyBaseX(ecPublicKey.getQ().getAffineXCoord().toBigInteger()); protocolMessage.setPublicKeyBaseY(ecPublicKey.getQ().getAffineYCoord().toBigInteger()); ECCurve curve = ecPublicKey.getParameters().getCurve(); ECPoint point = curve.createPoint(protocolMessage.getPublicKeyBaseX().getValue(), protocolMessage.getPublicKeyBaseY().getValue()); LOGGER.debug("Using the following point:"); LOGGER.debug("X: " + protocolMessage.getPublicKeyBaseX().getValue().toString()); LOGGER.debug("Y: " + protocolMessage.getPublicKeyBaseY().getValue().toString()); // System.out.println("-----------------\nUsing the following point:"); // System.out.println("X: " + point.getAffineXCoord()); // System.out.println("Y: " + point.getAffineYCoord()); // System.out.println("-----------------\n"); ECPointFormat[] pointFormats = tlsContext.getEcContext().getServerPointFormats(); try { byte[] serializedPoint = ECCUtilsBCWrapper.serializeECPoint(pointFormats, point); protocolMessage.setEcPointFormat(serializedPoint[0]); protocolMessage.setEcPointEncoded(Arrays.copyOfRange(serializedPoint, 1, serializedPoint.length)); protocolMessage.setPublicKeyLength(serializedPoint.length); byte[] result = ArrayConverter.concatenate( new byte[] { protocolMessage.getPublicKeyLength().getValue().byteValue() }, new byte[] { protocolMessage.getEcPointFormat().getValue() }, protocolMessage.getEcPointEncoded().getValue()); byte[] premasterSecret = TlsECCUtils.calculateECDHBasicAgreement( tlsContext.getEcContext().getServerPublicKeyParameters(), ecPrivateKey); byte[] random = tlsContext.getClientServerRandom(); protocolMessage.setPremasterSecret(premasterSecret); LOGGER.debug("Computed PreMaster Secret: {}", ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue())); LOGGER.debug("Client Server Random: {}", ArrayConverter.bytesToHexString(random)); PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getProtocolVersion(), tlsContext.getSelectedCipherSuite()); byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm, protocolMessage.getPremasterSecret().getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random, HandshakeByteLength.MASTER_SECRET); LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret)); protocolMessage.setMasterSecret(masterSecret); tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue()); return result; } catch (IOException ex) { throw new WorkflowExecutionException("EC point serialization failure", ex); } }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * /*from ww w .j a va 2 s. c om*/ * Inspected and display various informations from the Certificate passed as * parameter. Keys are presented in HEX values and ASN1 structures dumped * using ASN1Dump.dumpAsString. * * This method is intended for debug purposes only. * * * @param cert * The X509CertificateStructure to be inspected. * */ public static void dumpCertificateInfo(org.bouncycastle.asn1.x509.Certificate cert) { boolean valid = false; TBSCertificate tbs = cert.getTBSCertificate(); RSAEngine engine = new RSAEngine(); SHA1Digest digest = new SHA1Digest(); GenericSigner signer = new GenericSigner((engine), digest); RSAPublicKey signingKey; try { signingKey = RSAPublicKey.getInstance(cert.getSubjectPublicKeyInfo().parsePublicKey()); HttpsConnectionUtils.logDebug("Public Key:[[" + cert.getSubjectPublicKeyInfo().parsePublicKey() + "]]"); RSAKeyParameters keySpec = new RSAKeyParameters(false, signingKey.getModulus(), signingKey.getPublicExponent()); signer.init(false, keySpec); HttpsConnectionUtils.logDebug("TBS DER object:[[" + tbs.getEncoded("DER") + "]]"); signer.update(tbs.getEncoded(), 0, tbs.getEncoded().length); valid = signer.verifySignature(cert.getSignature().getBytes()); HttpsConnectionUtils.logDebug("signer.verifySignature:[[" + valid + "]]"); SHA1Digest d2 = new SHA1Digest(); d2.update(tbs.getEncoded("DER"), 0, tbs.getEncoded("DER").length); byte[] hash = new byte[d2.getDigestSize()]; d2.doFinal(hash, 0); HttpsConnectionUtils.logDebug("tbs.getDEREncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]"); DEROctetString asn1Hash = new DEROctetString(hash); HttpsConnectionUtils.logDebug( "ASN1 DEROctetString hash:[[" + new String(Hex.encode(asn1Hash.getEncoded("DER"))) + "]]"); d2 = new SHA1Digest(); d2.update(cert.getEncoded(), 0, cert.getEncoded().length); hash = new byte[d2.getDigestSize()]; d2.doFinal(hash, 0); HttpsConnectionUtils.logDebug("cert.getEncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]"); byte[] signature = cert.getSignature().getBytes(); HttpsConnectionUtils .logDebug("cert.getSignature().getBytes():[[" + new String(Hex.encode(signature)) + "]]"); PKCS1Encoding engine2 = new PKCS1Encoding(new RSAEngine()); engine2.init(false, keySpec); byte[] decryptedHash = engine2.processBlock(signature, 0, signature.length); HttpsConnectionUtils.logDebug("decryptedHash:[[" + new String(Hex.encode(decryptedHash)) + "]]"); ASN1Object o = ASN1Primitive.fromByteArray(decryptedHash); HttpsConnectionUtils.logDebug( "decryptedHash.getDEREncoded():[[" + new String(Hex.encode(o.getEncoded("DER"))) + "]]"); HttpsConnectionUtils.logDebug( "ASN1Dump.dumpAsString(decryptedHash,true):[[" + ASN1Dump.dumpAsString(o, true) + "]]"); HttpsConnectionUtils.logDebug("engine.getInputBlockSize():[[" + engine2.getInputBlockSize() + "]]"); HttpsConnectionUtils.logDebug("engine.getOutputBlockSize():[[" + engine2.getOutputBlockSize() + "]]"); ASN1Sequence asn1SignSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(decryptedHash); HttpsConnectionUtils .logDebug("Signature ASN1 Sequence:[[" + ASN1Dump.dumpAsString(asn1SignSeq, true) + "]]"); AlgorithmIdentifier algorithm = AlgorithmIdentifier.getInstance(asn1SignSeq.getObjectAt(0)); HttpsConnectionUtils.logDebug("AlgorithmIdentifier:[[" + ASN1Dump.dumpAsString(algorithm, true) + "]]"); DEROctetString signedHash = (DEROctetString) DEROctetString.getInstance(asn1SignSeq.getObjectAt(1)); HttpsConnectionUtils.logDebug("signedHash:[[" + ASN1Dump.dumpAsString(signedHash, true) + "]]"); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
@Override public ValidationResult checkCert(final byte[] certBytes, final X509IssuerInfo issuerInfo, final X500Name requestedSubject, final SubjectPublicKeyInfo requestedPublicKey, final Extensions requestedExtensions) { ParamChecker.assertNotNull("certBytes", certBytes); ParamChecker.assertNotNull("issuerInfo", issuerInfo); ParamChecker.assertNotNull("requestedSubject", requestedSubject); ParamChecker.assertNotNull("requestedPublicKey", requestedPublicKey); List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>(); Certificate bcCert; X509Certificate cert;//from w w w .j a v a 2s .c o m // certificate encoding { ValidationIssue issue = new ValidationIssue("X509.ENCODING", "certificate encoding"); resultIssues.add(issue); try { bcCert = Certificate.getInstance(certBytes); cert = X509Util.parseCert(certBytes); } catch (CertificateException | IOException e) { issue.setFailureMessage("certificate is not corrected encoded"); return new ValidationResult(resultIssues); } } // syntax version { ValidationIssue issue = new ValidationIssue("X509.VERSION", "certificate version"); resultIssues.add(issue); int versionNumber = cert.getVersion(); if (versionNumber != version.getVersion()) { issue.setFailureMessage("is '" + versionNumber + "' but expected '" + version.getVersion() + "'"); } } // signatureAlgorithm if (CollectionUtil.isNotEmpty(signatureAlgorithms)) { ValidationIssue issue = new ValidationIssue("X509.SIGALG", "signature algorithm"); resultIssues.add(issue); AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm(); AlgorithmIdentifier tbsSigAlgId = bcCert.getTBSCertificate().getSignature(); if (tbsSigAlgId.equals(sigAlgId) == false) { issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm"); } else { try { String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId); if (signatureAlgorithms.contains(sigAlgo) == false) { issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed"); } } catch (NoSuchAlgorithmException e) { issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId()); } } } // notBefore if (notBeforeMidnight) { ValidationIssue issue = new ValidationIssue("X509.NOTBEFORE", "not before midnight"); resultIssues.add(issue); Calendar c = Calendar.getInstance(UTC); c.setTime(cert.getNotBefore()); int hourOfDay = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); if (hourOfDay != 0 || minute != 0 || second != 0) { issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)"); } } // validity { ValidationIssue issue = new ValidationIssue("X509.VALIDITY", "cert validity"); resultIssues.add(issue); Date expectedNotAfter = validity.add(cert.getNotBefore()); if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) { issue.setFailureMessage("cert validity is not within " + validity.toString()); } } // public key { SubjectPublicKeyInfo publicKey = bcCert.getSubjectPublicKeyInfo(); if (keyAlgorithms != null) { ValidationIssue issue = new ValidationIssue("X509.PUBKEY.SYN", "whether public key is permitted"); resultIssues.add(issue); try { checkPublicKey(publicKey); } catch (BadCertTemplateException e) { issue.setFailureMessage(e.getMessage()); } } ValidationIssue issue = new ValidationIssue("X509.PUBKEY.REQ", "whether public key matches the request one"); resultIssues.add(issue); SubjectPublicKeyInfo c14nRequestedPublicKey; try { c14nRequestedPublicKey = X509Util.toRfc3279Style(requestedPublicKey); if (c14nRequestedPublicKey.equals(publicKey) == false) { issue.setFailureMessage("public key in the certificate does not equal the requested one"); } } catch (InvalidKeySpecException e) { issue.setFailureMessage("public key in request is invalid"); } } // Signature { ValidationIssue issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA"); resultIssues.add(issue); try { cert.verify(issuerInfo.getCert().getPublicKey(), "BC"); } catch (Exception e) { issue.setFailureMessage("invalid signature"); } } // issuer { ValidationIssue issue = new ValidationIssue("X509.ISSUER", "certificate issuer"); resultIssues.add(issue); if (cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal()) == false) { issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate"); } } // subject X500Name subject = bcCert.getTBSCertificate().getSubject(); resultIssues.addAll(checkSubject(subject, requestedSubject)); // extensions resultIssues.addAll(checkExtensions(bcCert, cert, issuerInfo, requestedExtensions)); return new ValidationResult(resultIssues); }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private List<ValidationIssue> checkExtensions(final Certificate bcCert, final X509Certificate cert, final X509IssuerInfo issuerInfo, final Extensions requestExtensions) { List<ValidationIssue> result = new LinkedList<>(); // detect the list of extension types in certificate Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(bcCert, issuerInfo, requestExtensions); Extensions extensions = bcCert.getTBSCertificate().getExtensions(); ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); if (oids == null) { ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general"); result.add(issue);//from w w w . ja va2 s . c o m issue.setFailureMessage("no extension is present"); return result; } List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids); for (ASN1ObjectIdentifier extType : presentExtenionTypes) { if (certExtTypes.contains(extType) == false) { ValidationIssue issue = createExtensionIssue(extType); result.add(issue); issue.setFailureMessage("extension is absent but is required"); } } for (ASN1ObjectIdentifier oid : certExtTypes) { ValidationIssue issue = createExtensionIssue(oid); result.add(issue); if (presentExtenionTypes.contains(oid) == false) { issue.setFailureMessage("extension is present but is not permitted"); continue; } Extension ext = extensions.getExtension(oid); StringBuilder failureMsg = new StringBuilder(); ExtensionControl extControl = extensionControls.get(oid); if (extControl.isCritical() != ext.isCritical()) { failureMsg.append( "critical is '" + ext.isCritical() + "' but expected '" + extControl.isCritical() + "'"); failureMsg.append("; "); } byte[] extensionValue = ext.getExtnValue().getOctets(); try { if (Extension.authorityKeyIdentifier.equals(oid)) { // AuthorityKeyIdentifier checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectKeyIdentifier.equals(oid)) { // SubjectKeyIdentifier checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, bcCert.getSubjectPublicKeyInfo()); } else if (Extension.keyUsage.equals(oid)) { // KeyUsage checkExtensionKeyUsage(failureMsg, extensionValue, cert.getKeyUsage(), requestExtensions, extControl); } else if (Extension.certificatePolicies.equals(oid)) { // CertificatePolicies checkExtensionCertificatePolicies(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.policyMappings.equals(oid)) { // Policy Mappings checkExtensionPolicyMappings(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.subjectAlternativeName.equals(oid)) { // SubjectAltName checkExtensionSubjectAltName(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.issuerAlternativeName.equals(oid)) { // IssuerAltName checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo); } else if (Extension.basicConstraints.equals(oid)) { // Basic Constraints checkExtensionBasicConstraints(failureMsg, extensionValue); } else if (Extension.nameConstraints.equals(oid)) { // Name Constraints checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl); } else if (Extension.policyConstraints.equals(oid)) { // PolicyConstrains checkExtensionPolicyConstraints(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.extendedKeyUsage.equals(oid)) { // ExtendedKeyUsage checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.cRLDistributionPoints.equals(oid)) { // CRL Distribution Points checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); continue; } else if (Extension.inhibitAnyPolicy.equals(oid)) { // Inhibit anyPolicy checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl); } else if (Extension.freshestCRL.equals(oid)) { // Freshest CRL checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); } else if (Extension.authorityInfoAccess.equals(oid)) { // Authority Information Access checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectInfoAccess.equals(oid)) { // SubjectInfoAccess checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestExtensions, extControl); } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) { // Admission checkExtensionAdmission(failureMsg, extensionValue, requestExtensions, extControl); } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) { // ocsp-nocheck checkExtensionOcspNocheck(failureMsg, extensionValue); } else { byte[] expected = getExpectedExtValue(oid, requestExtensions, extControl); if (Arrays.equals(expected, extensionValue) == false) { failureMsg.append("extension valus is '" + hex(extensionValue) + "' but expected '" + (expected == null ? "not present" : hex(expected)) + "'"); failureMsg.append("; "); } } if (failureMsg.length() > 0) { issue.setFailureMessage(failureMsg.toString()); } } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException e) { LOG.debug("extension value does not have correct syntax", e); issue.setFailureMessage("extension value does not have correct syntax"); } } return result; }
From source file:org.xipki.ca.server.impl.publisher.OCSPStoreQueryExecutor.java
License:Open Source License
void addIssuer(final X509CertWithDBCertId issuerCert) throws CertificateEncodingException, DataAccessException { if (issuerStore.getIdForCert(issuerCert.getEncodedCert()) != null) { return;//from w ww . j a v a 2 s . co m } String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, issuerCert.getEncodedCert()); Certificate bcCert = Certificate.getInstance(issuerCert.getEncodedCert()); byte[] encodedName; try { encodedName = bcCert.getSubject().getEncoded("DER"); } catch (IOException e) { throw new CertificateEncodingException(e.getMessage(), e); } byte[] encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); long maxId = dataSource.getMax(null, "ISSUER", "ID"); int id = (int) maxId + 1; final String sql = "INSERT INTO ISSUER (ID, SUBJECT, NOTBEFORE, NOTAFTER," + " SHA1_NAME, SHA1_KEY, SHA224_NAME, SHA224_KEY, SHA256_NAME, SHA256_KEY," + " SHA384_NAME, SHA384_KEY, SHA512_NAME, SHA512_KEY,SHA1_CERT, CERT)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement ps = borrowPreparedStatement(sql); try { String b64Cert = Base64.toBase64String(issuerCert.getEncodedCert()); String subject = issuerCert.getSubject(); int idx = 1; ps.setInt(idx++, id); ps.setString(idx++, subject); ps.setLong(idx++, issuerCert.getCert().getNotBefore().getTime() / 1000); ps.setLong(idx++, issuerCert.getCert().getNotAfter().getTime() / 1000); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedName)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedName)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedKey)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedName)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedKey)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedName)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedKey)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedName)); ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedKey)); ps.setString(idx++, hexSha1FpCert); ps.setString(idx++, b64Cert); ps.execute(); IssuerEntry newInfo = new IssuerEntry(id, subject, hexSha1FpCert, b64Cert); issuerStore.addIdentityEntry(newInfo); } catch (SQLException e) { throw dataSource.translate(sql, e); } finally { releaseDbResources(ps, null); } }
From source file:org.xipki.ca.server.impl.X509SelfSignedCertBuilder.java
License:Open Source License
public static GenerateSelfSignedResult generateSelfSigned(final SecurityFactory securityFactory, final String signerType, final String signerConf, final IdentifiedX509Certprofile certprofile, final CertificationRequest p10Request, final long serialNumber, final List<String> cacertUris, final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris) throws OperationException, ConfigurationException { if (securityFactory.verifyPOPO(p10Request) == false) { throw new ConfigurationException("could not validate POP for the pkcs#10 requst"); }/* w w w.j a va 2 s.c o m*/ if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) { CmpUtf8Pairs keyValues = new CmpUtf8Pairs(signerConf); String keystoreConf = keyValues.getValue("keystore"); if (keystoreConf == null) { throw new ConfigurationException( "required parameter 'keystore', for types PKCS12 and JKS, is not specified"); } } ConcurrentContentSigner signer; try { List<String[]> signerConfs = CAManagerImpl.splitCASignerConfs(signerConf); List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms(); String thisSignerConf = null; if (CollectionUtil.isEmpty(restrictedSigAlgos)) { thisSignerConf = signerConfs.get(0)[1]; } else { for (String algo : restrictedSigAlgos) { for (String[] m : signerConfs) { if (m[0].equals(algo)) { thisSignerConf = m[1]; break; } } if (thisSignerConf != null) { break; } } } if (thisSignerConf == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile"); } signer = securityFactory.createSigner(signerType, thisSignerConf, (X509Certificate[]) null); } catch (SignerException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, e.getClass().getName() + ": " + e.getMessage()); } // this certificate is the dummy one which can be considered only as public key container Certificate bcCert; try { bcCert = Certificate.getInstance(signer.getCertificate().getEncoded()); } catch (Exception e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + e.getMessage()); } SubjectPublicKeyInfo publicKeyInfo = bcCert.getSubjectPublicKeyInfo(); X509Certificate newCert = generateCertificate(signer, certprofile, p10Request, serialNumber, publicKeyInfo, cacertUris, ocspUris, crlUris, deltaCrlUris); return new GenerateSelfSignedResult(signerConf, newCert); }
From source file:org.xipki.commons.security.IssuerHash.java
License:Open Source License
public IssuerHash(final HashAlgoType hashAlgo, final Certificate issuerCert) throws IOException { this.hashAlgo = ParamUtil.requireNonNull("hashAlgo", hashAlgo); ParamUtil.requireNonNull("issuerCert", issuerCert); byte[] encodedName = issuerCert.getSubject().getEncoded(); byte[] encodedKey = issuerCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); this.issuerNameHash = HashCalculator.hash(hashAlgo, encodedName); this.issuerKeyHash = HashCalculator.hash(hashAlgo, encodedKey); }
From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java
License:Open Source License
@Override protected Object doExecute() throws Exception { hashAlgo = hashAlgo.trim().toUpperCase(); if (hashAlgo.indexOf('-') != -1) { hashAlgo = hashAlgo.replaceAll("-", ""); }//from w w w.java 2 s . c o m if (needExtensionTypes == null) { needExtensionTypes = new LinkedList<>(); } if (wantExtensionTypes == null) { wantExtensionTypes = new LinkedList<>(); } // SubjectAltNames List<Extension> extensions = new LinkedList<>(); ASN1OctetString extnValue = createExtnValueSubjectAltName(); if (extnValue != null) { ASN1ObjectIdentifier oid = Extension.subjectAlternativeName; extensions.add(new Extension(oid, false, extnValue)); needExtensionTypes.add(oid.getId()); } // SubjectInfoAccess extnValue = createExtnValueSubjectInfoAccess(); if (extnValue != null) { ASN1ObjectIdentifier oid = Extension.subjectInfoAccess; extensions.add(new Extension(oid, false, extnValue)); needExtensionTypes.add(oid.getId()); } // Keyusage if (isNotEmpty(keyusages)) { Set<KeyUsage> usages = new HashSet<>(); for (String usage : keyusages) { usages.add(KeyUsage.getKeyUsage(usage)); } org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages); ASN1ObjectIdentifier extType = Extension.keyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // ExtendedKeyusage if (isNotEmpty(extkeyusages)) { ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages)); ASN1ObjectIdentifier extType = Extension.extendedKeyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // QcEuLimitValue if (isNotEmpty(qcEuLimits)) { ASN1EncodableVector vec = new ASN1EncodableVector(); for (String m : qcEuLimits) { StringTokenizer st = new StringTokenizer(m, ":"); try { String currencyS = st.nextToken(); String amountS = st.nextToken(); String exponentS = st.nextToken(); Iso4217CurrencyCode currency; try { int intValue = Integer.parseInt(currencyS); currency = new Iso4217CurrencyCode(intValue); } catch (NumberFormatException ex) { currency = new Iso4217CurrencyCode(currencyS); } int amount = Integer.parseInt(amountS); int exponent = Integer.parseInt(exponentS); MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent); QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue); vec.add(statment); } catch (Exception ex) { throw new Exception("invalid qc-eu-limit '" + m + "'"); } } ASN1ObjectIdentifier extType = Extension.qCStatements; ASN1Sequence extValue = new DERSequence(vec); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // biometricInfo if (biometricType != null && biometricHashAlgo != null && biometricFile != null) { TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType)); ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo); byte[] biometricBytes = IoUtil.read(biometricFile); MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId()); md.reset(); byte[] tmpBiometricDataHash = md.digest(biometricBytes); DERIA5String tmpSourceDataUri = null; if (biometricUri != null) { tmpSourceDataUri = new DERIA5String(biometricUri); } BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri); ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(biometricData); ASN1ObjectIdentifier extType = Extension.biometricInfo; ASN1Sequence extValue = new DERSequence(vec); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) { // Do nothing } else { throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set"); } for (Extension addExt : getAdditionalExtensions()) { extensions.add(addExt); } needExtensionTypes.addAll(getAdditionalNeedExtensionTypes()); wantExtensionTypes.addAll(getAdditionalWantExtensionTypes()); if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) { ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes)); extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded())); } ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain)); Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>(); if (CollectionUtil.isNonEmpty(extensions)) { attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0]))); } if (StringUtil.isNotBlank(challengePassword)) { attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword)); } SubjectPublicKeyInfo subjectPublicKeyInfo; if (signer.getCertificate() != null) { Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded()); subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo(); } else { subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey()); } X500Name subjectDn = getSubject(subject); PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes); File file = new File(outputFilename); saveVerbose("saved CSR to file", file, csr.getEncoded()); return null; }
From source file:org.xipki.dbtool.CaCertStoreDbImporter.java
License:Open Source License
private int[] do_import_cert(final PreparedStatement ps_cert, final PreparedStatement ps_rawcert, final String certsZipFile, final int minId, final File processLogFile, final int totalProcessedSum) throws IOException, JAXBException, DataAccessException, CertificateException { ZipFile zipFile = new ZipFile(new File(baseDir, certsZipFile)); ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml"); CertsType certs;// w ww. java 2 s . co m try { @SuppressWarnings("unchecked") JAXBElement<CertsType> rootElement = (JAXBElement<CertsType>) unmarshaller .unmarshal(zipFile.getInputStream(certsXmlEntry)); certs = rootElement.getValue(); } catch (JAXBException e) { try { zipFile.close(); } catch (Exception e2) { } throw XMLUtil.convert(e); } disableAutoCommit(); try { List<CertType> list = certs.getCert(); final int size = list.size(); final int n = 100; int numProcessed = 0; int numEntriesInBatch = 0; int lastSuccessfulCertId = 0; for (int i = 0; i < size; i++) { CertType cert = list.get(i); int id = cert.getId(); lastSuccessfulCertId = id; if (id < minId) { continue; } int certArt = cert.getArt() == null ? 1 : cert.getArt(); numEntriesInBatch++; String filename = cert.getCertFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); Certificate c; try { c = Certificate.getInstance(encodedCert); } catch (Exception e) { LOG.error("could not parse certificate in file {}", filename); LOG.debug("could not parse certificate in file " + filename, e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert); // cert try { int idx = 1; ps_cert.setInt(idx++, id); ps_cert.setInt(idx++, certArt); ps_cert.setLong(idx++, cert.getLastUpdate()); ps_cert.setLong(idx++, c.getSerialNumber().getPositiveValue().longValue()); ps_cert.setString(idx++, X509Util.getRFC4519Name(c.getSubject())); ps_cert.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps_cert.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); setBoolean(ps_cert, idx++, cert.isRevoked()); setInt(ps_cert, idx++, cert.getRevReason()); setLong(ps_cert, idx++, cert.getRevTime()); setLong(ps_cert, idx++, cert.getRevInvTime()); setInt(ps_cert, idx++, cert.getProfileId()); setInt(ps_cert, idx++, cert.getCaId()); setInt(ps_cert, idx++, cert.getRequestorId()); setInt(ps_cert, idx++, cert.getUserId()); ps_cert.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey)); String sha1FpSubject = X509Util.sha1sum_canonicalized_name(c.getSubject()); ps_cert.setString(idx++, sha1FpSubject); Extension extension = c.getTBSCertificate().getExtensions() .getExtension(Extension.basicConstraints); boolean ee = true; if (extension != null) { ASN1Encodable asn1 = extension.getParsedValue(); try { ee = BasicConstraints.getInstance(asn1).isCA() == false; } catch (Exception e) { } } ps_cert.setInt(idx++, ee ? 1 : 0); ps_cert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CERT, e); } try { int idx = 1; ps_rawcert.setInt(idx++, cert.getId()); ps_rawcert.setString(idx++, hexSha1FpCert); ps_rawcert.setString(idx++, Base64.toBase64String(encodedCert)); ps_rawcert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_RAWCERT, e); } if (numEntriesInBatch > 0 && (numEntriesInBatch % n == 0 || i == size - 1)) { String sql = null; try { sql = SQL_ADD_CERT; ps_cert.executeBatch(); sql = SQL_ADD_RAWCERT; ps_rawcert.executeBatch(); sql = null; commit("(commit import cert to CA)"); } catch (SQLException e) { rollback(); throw translate(sql, e); } catch (DataAccessException e) { rollback(); throw e; } numProcessed += numEntriesInBatch; numEntriesInBatch = 0; echoToFile((totalProcessedSum + numProcessed) + ":" + lastSuccessfulCertId, processLogFile); } } return new int[] { numProcessed, lastSuccessfulCertId }; } finally { try { recoverAutoCommit(); } catch (DataAccessException e) { } zipFile.close(); } }