protected void processCertificateVerify( ServerHandshakeState state, byte[] body, TlsHandshakeHash prepareFinishHash) throws IOException { ByteArrayInputStream buf = new ByteArrayInputStream(body); DigitallySigned clientCertificateVerify = DigitallySigned.parse(state.serverContext, buf); TlsProtocol.assertEmpty(buf); // Verify the CertificateVerify message contains a correct signature. try { // TODO For TLS 1.2, this needs to be the hash specified in the DigitallySigned byte[] certificateVerifyHash = TlsProtocol.getCurrentPRFHash(state.serverContext, prepareFinishHash, null); org.bouncycastle.asn1.x509.Certificate x509Cert = state.clientCertificate.getCertificateAt(0); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(keyInfo); TlsSigner tlsSigner = TlsUtils.createTlsSigner(state.clientCertificateType); tlsSigner.init(state.serverContext); tlsSigner.verifyRawSignature( clientCertificateVerify.getAlgorithm(), clientCertificateVerify.getSignature(), publicKey, certificateVerifyHash); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.decrypt_error); } }
public CryptEngineImpl(Context ctx) throws Exception { // Получаем действующее хранилище IKeyStorage storage = KeyStorageFactory.getKeyStorage(ctx); Log.v("TFORWARD.CryptEngineImpl", "Decoding public key..."); byte[] publicKey = Base64.decode(storage.getKey(IKeyStorage.PUBLIC_KEY_TYPE), Base64.DEFAULT); Log.v("TFORWARD.CryptEngineImpl", "Decoding ASN1 Structure"); ASN1InputStream asnStream = new ASN1InputStream(publicKey); ASN1Sequence sequence = null; try { Log.v("TFORWARD.CryptEngineImpl", "Reading ASN1 Sequence"); sequence = (ASN1Sequence) asnStream.readObject(); } finally { asnStream.close(); } Log.v("TFORWARD.CryptEngineImpl", "Creating certificate. " + sequence.size()); Certificate certificate = Certificate.getInstance(sequence); SubjectPublicKeyInfo publicKeyInfo = certificate.getSubjectPublicKeyInfo(); RSAPublicKey publicKeyStructure = RSAPublicKey.getInstance(publicKeyInfo.parsePublicKey()); BigInteger mod = publicKeyStructure.getModulus(); BigInteger pubExp = publicKeyStructure.getPublicExponent(); publicRsaKey = new RSAKeyParameters(false, mod, pubExp); // ------------------------ PRIVATE KEY -------------------------------- byte[] privateKeyData = Base64.decode(storage.getKey(IKeyStorage.SECRET_KEY_TYPE), Base64.DEFAULT); asnStream = new ASN1InputStream(privateKeyData); ASN1Sequence asnSequence = null; try { asnSequence = (ASN1Sequence) asnStream.readObject(); } finally { asnStream.close(); } RSAPrivateKey privateKey = RSAPrivateKey.getInstance(asnSequence); privateRsaKey = new RSAPrivateCrtKeyParameters( privateKey.getModulus(), privateKey.getPublicExponent(), privateKey.getPrivateExponent(), privateKey.getPrime1(), privateKey.getPrime2(), privateKey.getExponent1(), privateKey.getExponent2(), privateKey.getCoefficient()); RSAEngine engine = new RSAEngine(); digest = new MD5Digest(); cipher = new PKCS1Encoding(engine); }
public void notifyClientCertificate(org.bouncycastle.crypto.tls.Certificate clientCertificate) throws IOException { Certificate[] chain = clientCertificate.getCertificateList(); System.out.println("TLS server received client certificate chain of length " + chain.length); for (int i = 0; i != chain.length; i++) { Certificate entry = chain[i]; // TODO Create fingerprint based on certificate signature algorithm digest System.out.println( " fingerprint:SHA-256 " + TlsTestUtils.fingerprint(entry) + " (" + entry.getSubject() + ")"); } }
private java.security.cert.Certificate readPEMCertificate(InputStream in) throws IOException, CertificateParsingException { ASN1Sequence seq = PEM_CERT_PARSER.readPEMObject(in); if (seq != null) { return new X509CertificateObject(Certificate.getInstance(seq)); } return null; }
private void checkConnectionClient(TlsClient client, int cipherSuite, byte[] encCert) throws Exception { client.notifySelectedCipherSuite(cipherSuite); TlsKeyExchange keyExchange = client.getKeyExchange(); keyExchange.processServerCertificate( new Certificate( new org.bouncycastle.asn1.x509.Certificate[] { org.bouncycastle.asn1.x509.Certificate.getInstance(encCert) })); }
private java.security.cert.Certificate getCertificate() throws CertificateParsingException { if (sData != null) { while (sDataObjectCount < sData.size()) { Object obj = sData.getObjectAt(sDataObjectCount++); if (obj instanceof ASN1Sequence) { return new X509CertificateObject(Certificate.getInstance(obj)); } } } return null; }
private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) throws CertificateEncodingException { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); try { return new X509CertificateObject(Certificate.getInstance(new DERSequence(v))); } catch (CertificateParsingException e) { throw new ExtCertificateEncodingException("exception producing certificate object", e); } }
public X509IssuerInfo( final List<String> caIssuerURLs, final List<String> ocspURLs, final List<String> crlURLs, final List<String> deltaCrlURLs, final byte[] certBytes) throws CertificateException { ParamChecker.assertNotNull("certBytes", certBytes); if (CollectionUtil.isEmpty(caIssuerURLs)) { this.caIssuerURLs = null; } else { Set<String> set = new HashSet<>(); set.addAll(caIssuerURLs); this.caIssuerURLs = Collections.unmodifiableSet(set); } if (CollectionUtil.isEmpty(ocspURLs)) { this.ocspURLs = null; } else { Set<String> set = new HashSet<>(); set.addAll(ocspURLs); this.ocspURLs = Collections.unmodifiableSet(set); } if (CollectionUtil.isEmpty(crlURLs)) { this.crlURLs = null; } else { Set<String> set = new HashSet<>(); set.addAll(crlURLs); this.crlURLs = Collections.unmodifiableSet(set); } if (CollectionUtil.isEmpty(deltaCrlURLs)) { this.deltaCrlURLs = null; } else { Set<String> set = new HashSet<>(); set.addAll(deltaCrlURLs); this.deltaCrlURLs = Collections.unmodifiableSet(set); } try { this.cert = X509Util.parseCert(certBytes); } catch (IOException e) { throw new CertificateException(e.getMessage(), e); } this.bcCert = Certificate.getInstance(certBytes); this.ski = X509Util.extractSKI(cert); }
/** * Checks whether the given certificate is on this CRL. * * @param cert the certificate to check for. * @return true if the given certificate is on this CRL, false otherwise. */ public boolean isRevoked(Certificate cert) { if (!cert.getType().equals("X.509")) { throw new RuntimeException("X.509 CRL used with non X.509 Cert"); } TBSCertList.CRLEntry[] certs = c.getRevokedCertificates(); X500Name caName = c.getIssuer(); if (certs != null) { BigInteger serial = ((X509Certificate) cert).getSerialNumber(); for (int i = 0; i < certs.length; i++) { if (isIndirect && certs[i].hasExtensions()) { Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { caName = X500Name.getInstance( GeneralNames.getInstance(currentCaName.getParsedValue()) .getNames()[0] .getName()); } } if (certs[i].getUserCertificate().getValue().equals(serial)) { X500Name issuer; try { issuer = org.bouncycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); } catch (CertificateEncodingException e) { throw new RuntimeException("Cannot process certificate"); } if (!caName.equals(issuer)) { return false; } return true; } } } return false; }
private java.security.cert.Certificate readDERCertificate(ASN1InputStream dIn) throws IOException, CertificateParsingException { ASN1Sequence seq = (ASN1Sequence) dIn.readObject(); if (seq.size() > 1 && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { sData = SignedData.getInstance( ASN1Sequence.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true)) .getCertificates(); return getCertificate(); } } return new X509CertificateObject(Certificate.getInstance(seq)); }
/** * Constructor with an indication of the timestamp type. The default constructor for {@code * TimestampToken}. * * @param timeStamp {@code TimeStampToken} * @param type {@code TimestampType} * @param certPool {@code CertificatePool} which is used to identify the signing certificate of * the timestamp */ public TimestampToken( final TimeStampToken timeStamp, final TimestampType type, final CertificatePool certPool) { this.timeStamp = timeStamp; this.timeStampType = type; this.extraInfo = new TokenValidationExtraInfo(); wrappedSource = new CAdESCertificateSource(timeStamp, certPool); final Collection<CertificateToken> certs = wrappedSource.getCertificates(); for (final CertificateToken certificateToken : certs) { final byte[] encoded = certificateToken.getEncoded(); final Certificate certificate = Certificate.getInstance(encoded); final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(certificate); if (timeStamp.getSID().match(x509CertificateHolder)) { boolean valid = isSignedBy(certificateToken); if (valid) { break; } } } }
@Override protected Object _doExecute() throws Exception { P10RequestGenerator p10Gen = new P10RequestGenerator(); hashAlgo = hashAlgo.trim().toUpperCase(); if (hashAlgo.indexOf('-') != -1) { hashAlgo = hashAlgo.replaceAll("-", ""); } if (needExtensionTypes == null) { needExtensionTypes = new LinkedList<>(); } // SubjectAltNames List<Extension> extensions = new LinkedList<>(); if (isNotEmpty(subjectAltNames)) { extensions.add(P10RequestGenerator.createExtensionSubjectAltName(subjectAltNames, false)); needExtensionTypes.add(Extension.subjectAlternativeName.getId()); } // SubjectInfoAccess if (isNotEmpty(subjectInfoAccesses)) { extensions.add( P10RequestGenerator.createExtensionSubjectInfoAccess(subjectInfoAccesses, false)); needExtensionTypes.add(Extension.subjectInfoAccess.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)) { Set<ASN1ObjectIdentifier> oids = new HashSet<>(SecurityUtil.textToASN1ObjectIdentifers(extkeyusages)); ExtendedKeyUsage extValue = X509Util.createExtendedUsage(oids); ASN1ObjectIdentifier extType = Extension.extendedKeyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // QcEuLimitValue if (isNotEmpty(qcEuLimits)) { ASN1EncodableVector v = 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 e) { 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); v.add(statment); } catch (Exception e) { throw new Exception("invalid qc-eu-limit '" + m + "'"); } } ASN1ObjectIdentifier extType = Extension.qCStatements; ASN1Sequence extValue = new DERSequence(v); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // biometricInfo if (biometricType != null && biometricHashAlgo != null && biometricFile != null) { TypeOfBiometricData _biometricType; if (StringUtil.isNumber(biometricType)) { _biometricType = new TypeOfBiometricData(Integer.parseInt(biometricType)); } else { _biometricType = new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType)); } ASN1ObjectIdentifier _biometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo); byte[] biometricBytes = IoUtil.read(biometricFile); MessageDigest md = MessageDigest.getInstance(_biometricHashAlgo.getId()); md.reset(); byte[] _biometricDataHash = md.digest(biometricBytes); DERIA5String _sourceDataUri = null; if (biometricUri != null) { _sourceDataUri = new DERIA5String(biometricUri); } BiometricData biometricData = new BiometricData( _biometricType, new AlgorithmIdentifier(_biometricHashAlgo), new DEROctetString(_biometricDataHash), _sourceDataUri); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(biometricData); ASN1ObjectIdentifier extType = Extension.biometricInfo; ASN1Sequence extValue = new DERSequence(v); 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"); } if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) { ExtensionExistence ee = new ExtensionExistence( SecurityUtil.textToASN1ObjectIdentifers(needExtensionTypes), SecurityUtil.textToASN1ObjectIdentifers(wantExtensionTypes)); extensions.add( new Extension( ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded())); } ConcurrentContentSigner identifiedSigner = getSigner(hashAlgo, new SignatureAlgoControl(rsaMgf1, dsaPlain)); Certificate cert = Certificate.getInstance(identifiedSigner.getCertificate().getEncoded()); X500Name subjectDN; if (subject != null) { subjectDN = getSubject(subject); } else { subjectDN = cert.getSubject(); } SubjectPublicKeyInfo subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo(); ContentSigner signer = identifiedSigner.borrowContentSigner(); PKCS10CertificationRequest p10Req; try { p10Req = p10Gen.generateRequest(signer, subjectPublicKeyInfo, subjectDN, extensions); } finally { identifiedSigner.returnContentSigner(signer); } File file = new File(outputFilename); saveVerbose("saved PKCS#10 request to file", file, p10Req.getEncoded()); return null; }
private int do_import_cert( final PreparedStatement ps_cert, final PreparedStatement ps_certhash, final PreparedStatement ps_rawcert, final String certsZipFile, final int minId, final File processLogFile, final ProcessLog processLog, final int numProcessedInLastProcess) throws Exception { ZipFile zipFile = new ZipFile(new File(certsZipFile)); ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml"); OcspCertsReader certs; try { certs = new OcspCertsReader(zipFile.getInputStream(certsXmlEntry)); } catch (Exception e) { try { zipFile.close(); } catch (Exception e2) { } throw e; } disableAutoCommit(); try { int numEntriesInBatch = 0; int lastSuccessfulCertId = 0; while (certs.hasNext()) { if (stopMe.get()) { throw new InterruptedException("interrupted by the user"); } OcspCertType cert = (OcspCertType) certs.next(); int id = cert.getId(); if (id < minId) { continue; } numEntriesInBatch++; String filename = cert.getFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); TBSCertificate c; try { Certificate cc = Certificate.getInstance(encodedCert); c = cc.getTBSCertificate(); } 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); } } // cert try { int idx = 1; ps_cert.setInt(idx++, id); ps_cert.setInt(idx++, cert.getIid()); ps_cert.setLong(idx++, c.getSerialNumber().getPositiveValue().longValue()); ps_cert.setLong(idx++, cert.getUpdate()); ps_cert.setLong(idx++, c.getStartDate().getDate().getTime() / 1000); ps_cert.setLong(idx++, c.getEndDate().getDate().getTime() / 1000); setBoolean(ps_cert, idx++, cert.getRev().booleanValue()); setInt(ps_cert, idx++, cert.getRr()); setLong(ps_cert, idx++, cert.getRt()); setLong(ps_cert, idx++, cert.getRit()); ps_cert.setString(idx++, cert.getProfile()); ps_cert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CERT, e); } // certhash try { int idx = 1; ps_certhash.setInt(idx++, cert.getId()); ps_certhash.setString(idx++, sha1(encodedCert)); ps_certhash.setString(idx++, sha224(encodedCert)); ps_certhash.setString(idx++, sha256(encodedCert)); ps_certhash.setString(idx++, sha384(encodedCert)); ps_certhash.setString(idx++, sha512(encodedCert)); ps_certhash.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CHASH, e); } // rawcert try { int idx = 1; ps_rawcert.setInt(idx++, cert.getId()); ps_rawcert.setString(idx++, X509Util.cutX500Name(c.getSubject(), maxX500nameLen)); ps_rawcert.setString(idx++, Base64.toBase64String(encodedCert)); ps_rawcert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CRAW, e); } boolean isLastBlock = !certs.hasNext(); if (numEntriesInBatch > 0 && (numEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) { if (evaulateOnly) { ps_cert.clearBatch(); ps_certhash.clearBatch(); ps_rawcert.clearBatch(); } else { String sql = null; try { sql = SQL_ADD_CERT; ps_cert.executeBatch(); sql = SQL_ADD_CHASH; ps_certhash.executeBatch(); sql = SQL_ADD_CRAW; ps_rawcert.executeBatch(); sql = null; commit("(commit import cert to OCSP)"); } catch (Throwable t) { rollback(); deleteCertGreatherThan(lastSuccessfulCertId, LOG); if (t instanceof SQLException) { throw translate(sql, (SQLException) t); } else if (t instanceof Exception) { throw (Exception) t; } else { throw new Exception(t); } } } lastSuccessfulCertId = id; processLog.addNumProcessed(numEntriesInBatch); numEntriesInBatch = 0; echoToFile( (numProcessedInLastProcess + processLog.getNumProcessed()) + ":" + lastSuccessfulCertId, processLogFile); processLog.printStatus(); } } // end for return lastSuccessfulCertId; } finally { try { recoverAutoCommit(); } catch (DataAccessException e) { } zipFile.close(); } } // method do_import_cert
private void import_issuer(final Issuers issuers) throws DataAccessException, CertificateException, IOException { System.out.println("importing table ISSUER"); PreparedStatement ps = prepareStatement(SQL_ADD_ISSUER); try { for (IssuerType issuer : issuers.getIssuer()) { try { String certFilename = issuer.getCertFile(); String b64Cert = new String(IoUtil.read(new File(baseDir, certFilename))); byte[] encodedCert = Base64.decode(b64Cert); Certificate c; byte[] encodedName; try { c = Certificate.getInstance(encodedCert); encodedName = c.getSubject().getEncoded("DER"); } catch (Exception e) { LOG.error("could not parse certificate of issuer {}", issuer.getId()); LOG.debug("could not parse certificate of issuer " + issuer.getId(), e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); int idx = 1; ps.setInt(idx++, issuer.getId()); ps.setString(idx++, X509Util.cutX500Name(c.getSubject(), maxX500nameLen)); ps.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); ps.setString(idx++, sha1(encodedName)); ps.setString(idx++, sha1(encodedKey)); ps.setString(idx++, sha224(encodedName)); ps.setString(idx++, sha224(encodedKey)); ps.setString(idx++, sha256(encodedName)); ps.setString(idx++, sha256(encodedKey)); ps.setString(idx++, sha384(encodedName)); ps.setString(idx++, sha384(encodedKey)); ps.setString(idx++, sha512(encodedName)); ps.setString(idx++, sha512(encodedKey)); ps.setString(idx++, sha1(encodedCert)); ps.setString(idx++, b64Cert); setBoolean(ps, idx++, issuer.isRevoked()); setInt(ps, idx++, issuer.getRevReason()); setLong(ps, idx++, issuer.getRevTime()); setLong(ps, idx++, issuer.getRevInvTime()); ps.execute(); } catch (SQLException e) { System.err.println("error while importing issuer with id=" + issuer.getId()); throw translate(SQL_ADD_ISSUER, e); } catch (CertificateException e) { System.err.println("error while importing issuer with id=" + issuer.getId()); throw e; } } } finally { releaseResources(ps, null); } System.out.println(" imported table ISSUER"); } // method import_issuer
public static CertificateModel fromASN1(ASN1InputStream stream) throws IOException { return CertificateModelFactory.from( new X509CertificateHolder(Certificate.getInstance(stream.readObject()))); }
public PKCS12SafeBagBuilder(Certificate certificate) throws IOException { this.bagType = PKCSObjectIdentifiers.certBag; this.bagValue = new CertBag( PKCSObjectIdentifiers.x509Certificate, new DEROctetString(certificate.getEncoded())); }