List of usage examples for org.bouncycastle.asn1 ASN1Integer getInstance
public static ASN1Integer getInstance(Object obj)
From source file:org.xipki.ca.client.shell.GetCRLCommand.java
License:Open Source License
@Override protected Object _doExecute() throws Exception { Set<String> caNames = caClient.getCaNames(); if (isEmpty(caNames)) { throw new IllegalCmdParamException("no CA is configured"); }/*from w ww.j a v a 2 s. co m*/ if (caName != null && !caNames.contains(caName)) { throw new IllegalCmdParamException("CA " + caName + " is not within the configured CAs " + caNames); } if (caName == null) { if (caNames.size() == 1) { caName = caNames.iterator().next(); } else { throw new IllegalCmdParamException("no caname is specified, one of " + caNames + " is required"); } } X509CRL crl = null; try { crl = retrieveCRL(caName); } catch (PKIErrorException e) { throw new CmdFailure("received no CRL from server: " + e.getMessage()); } if (crl == null) { throw new CmdFailure("received no CRL from server"); } saveVerbose("saved CRL to file", new File(outFile), crl.getEncoded()); if (withBaseCRL.booleanValue()) { byte[] octetString = crl.getExtensionValue(Extension.deltaCRLIndicator.getId()); if (octetString != null) { if (baseCRLOut == null) { baseCRLOut = outFile + "-baseCRL"; } byte[] extnValue = DEROctetString.getInstance(octetString).getOctets(); BigInteger baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); RequestResponseDebug debug = getRequestResponseDebug(); try { crl = caClient.downloadCRL(caName, baseCrlNumber, debug); } catch (PKIErrorException e) { throw new CmdFailure("received no baseCRL from server: " + e.getMessage()); } finally { saveRequestResponse(debug); } if (crl == null) { throw new CmdFailure("received no baseCRL from server"); } else { saveVerbose("saved baseCRL to file", new File(baseCRLOut), crl.getEncoded()); } } } return null; }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private void checkPublicKey(final SubjectPublicKeyInfo publicKey) throws BadCertTemplateException { if (CollectionUtil.isEmpty(keyAlgorithms)) { return;/*w ww . j ava 2s. co m*/ } ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm(); if (keyAlgorithms.containsKey(keyType) == false) { throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted"); } KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType); if (keyParamsOption instanceof AllowAllParametersOption) { return; } else if (keyParamsOption instanceof ECParamatersOption) { ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption; // parameters ASN1Encodable algParam = publicKey.getAlgorithm().getParameters(); ASN1ObjectIdentifier curveOid; if (algParam instanceof ASN1ObjectIdentifier) { curveOid = (ASN1ObjectIdentifier) algParam; if (ecOption.allowsCurve(curveOid) == false) { throw new BadCertTemplateException("EC curve " + SecurityUtil.getCurveName(curveOid) + " (OID: " + curveOid.getId() + ") is not allowed"); } } else { throw new BadCertTemplateException("only namedCurve or implictCA EC public key is supported"); } // point encoding if (ecOption.getPointEncodings() != null) { byte[] keyData = publicKey.getPublicKeyData().getBytes(); if (keyData.length < 1) { throw new BadCertTemplateException("invalid publicKeyData"); } byte pointEncoding = keyData[0]; if (ecOption.getPointEncodings().contains(pointEncoding) == false) { throw new BadCertTemplateException("unaccepted EC point encoding " + pointEncoding); } } try { checkECSubjectPublicKeyInfo(curveOid, publicKey.getPublicKeyData().getBytes()); } catch (BadCertTemplateException e) { throw e; } catch (Exception e) { LOG.debug("populateFromPubKeyInfo", e); throw new BadCertTemplateException("invalid public key: " + e.getMessage()); } return; } else if (keyParamsOption instanceof RSAParametersOption) { RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption; ASN1Integer modulus; try { ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes()); modulus = ASN1Integer.getInstance(seq.getObjectAt(0)); } catch (IllegalArgumentException e) { throw new BadCertTemplateException("invalid publicKeyData"); } int modulusLength = modulus.getPositiveValue().bitLength(); if ((rsaOption.allowsModulusLength(modulusLength))) { return; } } else if (keyParamsOption instanceof DSAParametersOption) { DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption; ASN1Encodable params = publicKey.getAlgorithm().getParameters(); if (params == null) { throw new BadCertTemplateException("null Dss-Parms is not permitted"); } int pLength; int qLength; try { ASN1Sequence seq = ASN1Sequence.getInstance(params); ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0)); ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(1)); pLength = p.getPositiveValue().bitLength(); qLength = q.getPositiveValue().bitLength(); } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException e) { throw new BadCertTemplateException("illegal Dss-Parms"); } boolean match = dsaOption.allowsPLength(pLength); if (match) { match = dsaOption.allowsQLength(qLength); } if (match) { return; } } else { throw new RuntimeException("should not reach here, unknown keyParamsOption " + (keyParamsOption == null ? "null" : keyParamsOption.getClass().getName())); } throw new BadCertTemplateException("the given publicKey is not permitted"); }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private void checkExtensionInhibitAnyPolicy(final StringBuilder failureMsg, final byte[] extensionValue, final Extensions requestExtensions, final ExtensionControl extControl) { QaInhibitAnyPolicy conf = inhibitAnyPolicy; if (conf == null) { byte[] expected = getExpectedExtValue(Extension.inhibitAnyPolicy, requestExtensions, extControl); if (Arrays.equals(expected, extensionValue) == false) { failureMsg.append("extension valus is '").append(hex(extensionValue)); failureMsg.append("' but expected '").append(expected == null ? "not present" : hex(expected)) .append("'"); failureMsg.append("; "); }/*from ww w .ja v a 2s . c o m*/ return; } ASN1Integer asn1Int = ASN1Integer.getInstance(extensionValue); int iSkipCerts = asn1Int.getPositiveValue().intValue(); if (iSkipCerts != conf.getSkipCerts()) { failureMsg.append("skipCerts is '" + iSkipCerts + "' but expected '" + conf.getSkipCerts() + "'"); failureMsg.append("; "); } }
From source file:org.xipki.ca.server.impl.store.CertStoreQueryExecutor.java
License:Open Source License
void addCRL(final X509CertWithDBCertId caCert, final X509CRL crl) throws DataAccessException, CRLException, OperationException { byte[] encodedExtnValue = crl.getExtensionValue(Extension.cRLNumber.getId()); Long crlNumber = null;//from ww w . j a v a 2 s . co m if (encodedExtnValue != null) { byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets(); crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue(); } encodedExtnValue = crl.getExtensionValue(Extension.deltaCRLIndicator.getId()); Long baseCrlNumber = null; if (encodedExtnValue != null) { byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets(); baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue(); } final String sql = "INSERT INTO CRL (ID, CA_ID, CRL_NO, THISUPDATE, NEXTUPDATE, DELTACRL, BASECRL_NO, CRL)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; int currentMaxCrlId = (int) dataSource.getMax(null, "CRL", "ID"); int crlId = currentMaxCrlId + 1; PreparedStatement ps = null; try { int caId = getCaId(caCert); ps = borrowPreparedStatement(sql); int idx = 1; ps.setInt(idx++, crlId); ps.setInt(idx++, caId); if (crlNumber != null) { ps.setInt(idx++, crlNumber.intValue()); } else { ps.setNull(idx++, Types.INTEGER); } Date d = crl.getThisUpdate(); ps.setLong(idx++, d.getTime() / 1000); d = crl.getNextUpdate(); if (d != null) { ps.setLong(idx++, d.getTime() / 1000); } else { ps.setNull(idx++, Types.BIGINT); } ps.setInt(idx++, baseCrlNumber != null ? 1 : 0); if (baseCrlNumber != null) { ps.setLong(idx++, baseCrlNumber); } else { ps.setNull(idx++, Types.BIGINT); } byte[] encodedCrl = crl.getEncoded(); String b64Crl = Base64.toBase64String(encodedCrl); ps.setString(idx++, b64Crl); ps.executeUpdate(); } catch (SQLException e) { throw dataSource.translate(sql, e); } finally { releaseDbResources(ps, null); } }
From source file:org.xipki.ca.server.impl.X509CACmpResponder.java
License:Open Source License
private PKIBody cmpGeneralMsg(final PKIHeaderBuilder respHeader, final CmpControl cmpControl, final PKIHeader reqHeader, final PKIBody reqBody, final CmpRequestorInfo requestor, final String user, final ASN1OctetString tid, final AuditEvent auditEvent) throws InsuffientPermissionException { GenMsgContent genMsgBody = (GenMsgContent) reqBody.getContent(); InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray(); InfoTypeAndValue itv = null;//from www. j a v a 2 s . c o m if (itvs != null && itvs.length > 0) { for (InfoTypeAndValue _itv : itvs) { String itvType = _itv.getInfoType().getId(); if (knownGenMsgIds.contains(itvType)) { itv = _itv; break; } } } if (itv == null) { String statusMessage = "PKIBody type " + PKIBody.TYPE_GEN_MSG + " is only supported with the sub-types " + knownGenMsgIds.toString(); return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage); } InfoTypeAndValue itvResp = null; ASN1ObjectIdentifier infoType = itv.getInfoType(); int failureInfo; try { X509CA ca = getCA(); if (CMPObjectIdentifiers.it_currentCRL.equals(infoType)) { addAutitEventType(auditEvent, "CRL_DOWNLOAD"); checkPermission(requestor, Permission.GET_CRL); CertificateList crl = ca.getCurrentCRL(); if (itv.getInfoValue() == null) { // as defined in RFC 4210 crl = ca.getCurrentCRL(); } else { // xipki extension ASN1Integer crlNumber = ASN1Integer.getInstance(itv.getInfoValue()); crl = ca.getCRL(crlNumber.getPositiveValue()); } if (crl == null) { String statusMessage = "no CRL is available"; return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage); } itvResp = new InfoTypeAndValue(infoType, crl); } else if (ObjectIdentifiers.id_xipki_cmp.equals(infoType)) { ASN1Encodable asn1 = itv.getInfoValue(); ASN1Integer asn1Code = null; ASN1Encodable reqValue = null; try { ASN1Sequence seq = ASN1Sequence.getInstance(asn1); asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0)); if (seq.size() > 1) { reqValue = seq.getObjectAt(1); } } catch (IllegalArgumentException e) { String statusMessage = "invalid value of the InfoTypeAndValue for " + ObjectIdentifiers.id_xipki_cmp.getId(); return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage); } ASN1Encodable respValue; int action = asn1Code.getPositiveValue().intValue(); switch (action) { case XipkiCmpConstants.ACTION_GEN_CRL: addAutitEventType(auditEvent, "CRL_GEN_ONDEMAND"); checkPermission(requestor, Permission.GEN_CRL); X509CRL _crl = ca.generateCRLonDemand(auditEvent); if (_crl == null) { String statusMessage = "CRL generation is not activated"; return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage); } else { respValue = CertificateList.getInstance(_crl.getEncoded()); } break; case XipkiCmpConstants.ACTION_GET_CRL_WITH_SN: addAutitEventType(auditEvent, "CRL_DOWNLOAD_WITH_SN"); checkPermission(requestor, Permission.GET_CRL); ASN1Integer crlNumber = ASN1Integer.getInstance(reqValue); respValue = ca.getCRL(crlNumber.getPositiveValue()); if (respValue == null) { String statusMessage = "no CRL is available"; return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage); } break; case XipkiCmpConstants.ACTION_GET_CAINFO: addAutitEventType(auditEvent, "GET_SYSTEMINFO"); Set<Integer> acceptVersions = new HashSet<>(); if (reqValue != null) { ASN1Sequence seq = DERSequence.getInstance(reqValue); int size = seq.size(); for (int i = 0; i < size; i++) { ASN1Integer a = ASN1Integer.getInstance(seq.getObjectAt(i)); acceptVersions.add(a.getPositiveValue().intValue()); } } if (CollectionUtil.isEmpty(acceptVersions)) { acceptVersions.add(1); } String systemInfo = getSystemInfo(requestor, acceptVersions); respValue = new DERUTF8String(systemInfo); break; case XipkiCmpConstants.ACTION_REMOVE_EXPIRED_CERTS: checkPermission(requestor, Permission.REMOVE_CERT); String info = removeExpiredCerts(requestor, itv.getInfoValue()); respValue = new DERUTF8String(info); break; default: String statusMessage = "unsupported XiPKI action code '" + action + "'"; return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage); } // end switch(action) ASN1EncodableVector v = new ASN1EncodableVector(); v.add(asn1Code); if (respValue != null) { v.add(respValue); } itvResp = new InfoTypeAndValue(infoType, new DERSequence(v)); } GenRepContent genRepContent = new GenRepContent(itvResp); return new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent); } catch (OperationException e) { failureInfo = PKIFailureInfo.systemFailure; String statusMessage = null; ErrorCode code = e.getErrorCode(); switch (code) { case BAD_REQUEST: failureInfo = PKIFailureInfo.badRequest; statusMessage = e.getErrorMessage(); break; case DATABASE_FAILURE: case SYSTEM_FAILURE: statusMessage = code.name(); break; default: statusMessage = code.name() + ": " + e.getErrorMessage(); break; } // end switch(code) return createErrorMsgPKIBody(PKIStatus.rejection, failureInfo, statusMessage); } catch (CRLException e) { String statusMessage = "CRLException: " + e.getMessage(); return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage); } }
From source file:org.xipki.commons.security.pkcs11.proxy.Asn1Util.java
License:Open Source License
public static BigInteger getInteger(final ASN1Encodable object) throws BadAsn1ObjectException { try {// w w w .j av a 2 s.co m return ASN1Integer.getInstance(object).getValue(); } catch (IllegalArgumentException ex) { throw new BadAsn1ObjectException("invalid object ASN1Integer: " + ex.getMessage(), ex); } }
From source file:org.xipki.commons.security.pkcs11.proxy.ProxyP11Slot.java
License:Open Source License
private List<Long> getMechanismsFromServer() throws P11TokenException { Asn1P11SlotIdentifier asn1SlotId = new Asn1P11SlotIdentifier(slotId); ASN1Encodable resp = module.send(P11ProxyConstants.ACTION_getMechanisms, asn1SlotId); ASN1Sequence seq = requireSequence(resp); final int n = seq.size(); List<Long> mechs = new ArrayList<>(n); for (int i = 0; i < n; i++) { long mech = ASN1Integer.getInstance(seq.getObjectAt(i)).getValue().longValue(); mechs.add(mech);/* ww w.j av a 2s . c o m*/ } return mechs; }
From source file:org.xipki.commons.security.shell.CrlInfoCmd.java
License:Open Source License
@Override protected Object doExecute() throws Exception { CertificateList crl = CertificateList.getInstance(IoUtil.read(inFile)); if (crlNumber != null && crlNumber) { ASN1Encodable asn1 = crl.getTBSCertList().getExtensions().getExtensionParsedValue(Extension.cRLNumber); if (asn1 == null) { return "null"; }//from w w w. jav a 2 s. c om return getNumber(ASN1Integer.getInstance(asn1).getPositiveValue()); } else if (issuer != null && issuer) { return crl.getIssuer().toString(); } else if (thisUpdate != null && thisUpdate) { return toUtcTimeyyyyMMddhhmmssZ(crl.getThisUpdate().getDate()); } else if (nextUpdate != null && nextUpdate) { return crl.getNextUpdate() == null ? "null" : toUtcTimeyyyyMMddhhmmssZ(crl.getNextUpdate().getDate()); } return null; }
From source file:org.xipki.commons.security.util.SignerUtil.java
License:Open Source License
public static byte[] convertX962DSASigToPlain(final byte[] x962Signature, final int keyBitLen) throws XiSecurityException { ParamUtil.requireNonNull("x962Signature", x962Signature); ASN1Sequence seq = ASN1Sequence.getInstance(x962Signature); if (seq.size() != 2) { throw new IllegalArgumentException("invalid X962Signature"); }//from w w w . j av a 2s .c o m BigInteger sigR = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue(); BigInteger sigS = ASN1Integer.getInstance(seq.getObjectAt(1)).getPositiveValue(); return convertDSASigToPlain(sigR, sigS, keyBitLen); }
From source file:org.xipki.dbtool.CaCertStoreDbImporter.java
License:Open Source License
private void import_crl(final Crls crls) throws Exception { final String sql = "INSERT INTO CRL (ID, CA_ID, CRL_NO, THISUPDATE, NEXTUPDATE, DELTACRL, BASECRL_NO, CRL)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; System.out.println("importing table CRL"); PreparedStatement ps = prepareStatement(sql); try {/* w w w.java2 s . c om*/ int id = 1; for (CrlType crl : crls.getCrl()) { try { String filename = baseDir + File.separator + crl.getCrlFile(); byte[] encodedCrl = IoUtil.read(filename); X509CRL c = null; try { c = X509Util.parseCRL(new ByteArrayInputStream(encodedCrl)); } catch (CertificateException | CRLException e) { LOG.error("could not parse CRL in file {}", filename); LOG.debug("could not parse CRL in file " + filename, e); } if (c == null) { continue; } byte[] octetString = c.getExtensionValue(Extension.cRLNumber.getId()); if (octetString == null) { LOG.warn("CRL without CRL number, ignore it"); continue; } byte[] extnValue = DEROctetString.getInstance(octetString).getOctets(); BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); BigInteger baseCrlNumber = null; octetString = c.getExtensionValue(Extension.deltaCRLIndicator.getId()); if (octetString != null) { extnValue = DEROctetString.getInstance(octetString).getOctets(); baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); } int idx = 1; ps.setInt(idx++, id++); ps.setInt(idx++, crl.getCaId()); ps.setLong(idx++, crlNumber.longValue()); ps.setLong(idx++, c.getThisUpdate().getTime() / 1000); if (c.getNextUpdate() != null) { ps.setLong(idx++, c.getNextUpdate().getTime() / 1000); } else { ps.setNull(idx++, Types.INTEGER); } if (baseCrlNumber == null) { setBoolean(ps, idx++, false); ps.setNull(idx++, Types.BIGINT); } else { setBoolean(ps, idx++, true); ps.setLong(idx++, baseCrlNumber.longValue()); } String s = Base64.toBase64String(encodedCrl); ps.setString(idx++, s); ps.executeUpdate(); } catch (SQLException e) { System.err.println( "error while importing CRL with ID=" + crl.getId() + ", message: " + e.getMessage()); throw translate(sql, e); } catch (Exception e) { System.err.println( "error while importing CRL with ID=" + crl.getId() + ", message: " + e.getMessage()); throw e; } } } finally { releaseResources(ps, null); } System.out.println(" imported table CRL"); }