java.security.cert.CertificateEncodingException Java Examples

The following examples show how to use java.security.cert.CertificateEncodingException. 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: CertService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * 根据单个crt的内容,找父证书,
 * @param sonCert
 * @return String crt's address
 */
public String findFatherCert(X509Certificate sonCert) throws CertificateEncodingException {
    log.debug("start findFatherCert. son cert: {}", NodeMgrTools.getCertFingerPrint(sonCert.getEncoded()));
    List<X509Certificate> x509CertList = loadAllX509Certs();
    String result = "";
    for(int i = 0; i < x509CertList.size(); i++) {
        X509Certificate temp = x509CertList.get(i);
        try{
            sonCert.verify(temp.getPublicKey());
        }catch (Exception e) {
            // 签名不匹配则继续
            continue;
        }
        // 返回指纹
        result = NodeMgrTools.getCertFingerPrint(temp.getEncoded());
    }
    log.debug("end findFatherCert. find one FatherCert's finerPrint:{}", result);
    return result;
}
 
Example #2
Source File: DatabaseBackend.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
    SQLiteDatabase db = this.getWritableDatabase();
    String[] selectionArgs = {
            account.getUuid(),
            fingerprint
    };
    try {
        ContentValues values = new ContentValues();
        values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
        return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
                selectionArgs) == 1;
    } catch (CertificateEncodingException e) {
        Log.d(Config.LOGTAG, "could not encode certificate");
        return false;
    }
}
 
Example #3
Source File: SigningCertificateLineage.java    From Xpatch with Apache License 2.0 6 votes vote down vote up
public SigningCertificateLineage build()
        throws CertificateEncodingException, InvalidKeyException, NoSuchAlgorithmException,
        SignatureException {
    if (mMinSdkVersion < AndroidSdkVersion.P) {
        mMinSdkVersion = AndroidSdkVersion.P;
    }

    if (mOriginalCapabilities == null) {
        mOriginalCapabilities = new SignerCapabilities.Builder().build();
    }

    if (mNewCapabilities == null) {
        mNewCapabilities = new SignerCapabilities.Builder().build();
    }

    return createSigningLineage(
            mMinSdkVersion, mOriginalSignerConfig, mOriginalCapabilities,
            mNewSignerConfig, mNewCapabilities);
}
 
Example #4
Source File: ProviderApiManagerTest.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void test_handleIntentSetupProvider_happyPath_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException {
    Provider provider = getConfiguredProvider();

    mockFingerprintForCertificate(" a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494");
    mockProviderApiConnector(NO_ERROR);
    providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback());
    Bundle expectedResult = mockBundle();

    expectedResult.putBoolean(BROADCAST_RESULT_KEY, true);
    expectedResult.putParcelable(PROVIDER_KEY, provider);

    Intent providerApiCommand = mockIntent();

    providerApiCommand.putExtra(PROVIDER_KEY, provider);
    providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER);
    providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult));

    providerApiManager.handleIntent(providerApiCommand);
}
 
Example #5
Source File: TrustStoreMessageSource.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private InternalMessage createMessage()
{
    List<Object> messageList = new ArrayList<>();
    for (Certificate cert : _certCache.get())
    {
        try
        {
            messageList.add(cert.getEncoded());
        }
        catch (CertificateEncodingException e)
        {
            LOGGER.error("Could not encode certificate of type " + cert.getType(), e);
        }
    }
    InternalMessageHeader header = new InternalMessageHeader(Collections.<String,Object>emptyMap(),
                                                             null, 0L, null, null, UUID.randomUUID().toString(),
                                                             null, null, (byte)4, System.currentTimeMillis(),
                                                             0L, null, null, System.currentTimeMillis());
    return InternalMessage.createListMessage(_virtualHost.getMessageStore(), header, messageList);
}
 
Example #6
Source File: Certificate.java    From statelearner with Apache License 2.0 6 votes vote down vote up
public Certificate(X509Certificate[] certs) throws CertificateEncodingException, IOException {
	super(TLS.HANDSHAKE_MSG_TYPE_CERTIFICATE, 0, new byte[] {});
	
	ByteArrayOutputStream chainStream = new ByteArrayOutputStream();
	
	for(int i = 0; i < certs.length; i++) {
		// Add 3 byte size
		chainStream.write(Utils.getbytes24(certs[i].getEncoded().length));
		// Add certificate
		chainStream.write(certs[i].getEncoded());
	}
	
	byte[] chain = chainStream.toByteArray();
	
	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	outStream.write(Utils.getbytes24(chain.length));
	outStream.write(chain);
	
	payload = outStream.toByteArray();
	length = payload.length;
}
 
Example #7
Source File: IqGenerator.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
    final Element item = new Element("item");
    item.setAttribute("id", "current");
    final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
    final Element chain = verification.addChild("chain");
    for (int i = 0; i < certificates.length; ++i) {
        try {
            Element certificate = chain.addChild("certificate");
            certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.NO_WRAP));
            certificate.setAttribute("index", i);
        } catch (CertificateEncodingException e) {
            Log.d(Config.LOGTAG, "could not encode certificate");
        }
    }
    verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.NO_WRAP));
    return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
}
 
Example #8
Source File: RequestInfoController.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@GetMapping(
    value = "",
    produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ApiOperation(
    value = "Returns all base information about request",
    notes = "Data contains sign information, headers and content")
@ApiResponses( value = {
    @ApiResponse(code = 200, message = "Information from request", response = RequestInfo.class),
    @ApiResponse(code = 500, message = "Error in parsing of request ")
})
@ResponseBody
public RequestInfo getRequestInfo(HttpServletRequest httpServletRequest) throws CertificateEncodingException, IOException {
    RequestInfo out = new RequestInfo();

    setCerts(httpServletRequest, out);
    setHeaders(httpServletRequest, out);
    setCookie(httpServletRequest, out);
    setContent(httpServletRequest, out);

    return out; // NOSONAR
}
 
Example #9
Source File: BlacklistedCertsConverter.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the requested finger print of the certificate.
 */
private static String getCertificateFingerPrint(String mdAlg,
                                                X509Certificate cert) {
    String fingerPrint = "";
    try {
        byte[] encCertInfo = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance(mdAlg);
        byte[] digest = md.digest(encCertInfo);
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            byte2hex(digest[i], buf);
        }
        fingerPrint = buf.toString();
    } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
        // ignored
    }
    return fingerPrint;
}
 
Example #10
Source File: X509Util.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static X509Cert getCaCertOf(X509Cert cert, Collection<X509Cert> caCerts)
    throws CertificateEncodingException {
  Args.notNull(cert, "cert");
  if (cert.isSelfSigned()) {
    return null;
  }

  for (X509Cert caCert : caCerts) {
    if (!issues(caCert, cert)) {
      continue;
    }

    try {
      cert.verify(caCert.getPublicKey());
      return caCert;
    } catch (Exception ex) {
      LOG.warn("could not verify certificate: {}", ex.getMessage());
    }
  }

  return null;
}
 
Example #11
Source File: ProviderApiManagerTest.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void test_handleIntentSetupProvider_happyPath_storedProviderAndCAFromPreviousSetup() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException {
    Provider provider = new Provider("https://riseup.net");
    mockPreferenceHelper(getConfiguredProvider());
    mockConfigHelper("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494");
    mockProviderApiConnector(NO_ERROR);
    mockPreferences.edit().putString(Provider.KEY + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"))).apply();
    mockPreferences.edit().putString(Provider.CA_CERT + ".riseup.net", getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"))).apply();
    providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback());

    Bundle expectedResult = mockBundle();
    expectedResult.putBoolean(BROADCAST_RESULT_KEY, true);
    expectedResult.putParcelable(PROVIDER_KEY, provider);

    Intent providerApiCommand = mockIntent();
    providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER);
    providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult));

    providerApiCommand.putExtra(PROVIDER_KEY, provider);

    providerApiManager.handleIntent(providerApiCommand);
}
 
Example #12
Source File: IssuerEntry.java    From xipki with Apache License 2.0 6 votes vote down vote up
public IssuerEntry(X509Cert cert) throws IOException, CertificateEncodingException {
  this.cert = Args.notNull(cert, "cert");
  byte[] encodedName = cert.getSubject().getEncoded("DER");
  byte[] encodedKey = cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

  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);
  }
  this.issuerHashMap = hashes;
}
 
Example #13
Source File: HttpResponseCache.java    From reader with MIT License 6 votes vote down vote up
private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
  if (certificates == null) {
    writer.write("-1\n");
    return;
  }
  try {
    writer.write(Integer.toString(certificates.length) + '\n');
    for (Certificate certificate : certificates) {
      byte[] bytes = certificate.getEncoded();
      String line = Base64.encode(bytes);
      writer.write(line + '\n');
    }
  } catch (CertificateEncodingException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #14
Source File: BlacklistedCertsConverter.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the requested finger print of the certificate.
 */
private static String getCertificateFingerPrint(String mdAlg,
                                                X509Certificate cert) {
    String fingerPrint = "";
    try {
        byte[] encCertInfo = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance(mdAlg);
        byte[] digest = md.digest(encCertInfo);
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            byte2hex(digest[i], buf);
        }
        fingerPrint = buf.toString();
    } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
        // ignored
    }
    return fingerPrint;
}
 
Example #15
Source File: X509CertificateObject.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private int calculateHashCode()
{
    try
    {
        int hashCode = 0;
        byte[] certData = this.getEncoded();
        for (int i = 1; i < certData.length; i++)
        {
             hashCode += certData[i] * i;
        }
        return hashCode;
    }
    catch (CertificateEncodingException e)
    {
        return 0;
    }
}
 
Example #16
Source File: SigningCertificateV2.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
	public Attribute getValue() throws SignerException {
		try {
			X509Certificate cert = (X509Certificate) certificates[0];
			X509Certificate issuerCert = (X509Certificate) certificates[1];
			Digest digest = DigestFactory.getInstance().factoryDefault();
			digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
			byte[] certHash = digest.digest(cert.getEncoded());
			X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName());
			GeneralName name = new GeneralName(dirName);
			GeneralNames issuer = new GeneralNames(name);
			ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
			IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
			AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);// SHA-256
			ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial);
//			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(essCertIDv2)));
			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(
					new ASN1Encodable[] { new DERSequence(essCertIDv2) })));
		} catch (CertificateEncodingException ex) {
			throw new SignerException(ex.getMessage());
		}
	}
 
Example #17
Source File: SAML2TokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        String value = Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
    } catch (CertificateEncodingException e) {
        log.error("Failed to get encoded certificate", e);
        throw new IdentityProviderException("Error while getting encoded certificate");
    }

    assertion.setSignature(signature);
    signatureList.add(signature);
}
 
Example #18
Source File: SecurityUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
/**
 * Returns the intermediate certificates (sub CAs) from a given certificate chain.
 * 
 * @param certChain The certificate chain given as an array of Certificate instances
 * @return The sub certificates given as a list of byte arrays contained in a SubCertiticatesType instance
 */
public static SubCertificatesType getSubCertificates(Certificate[] certChain) {
	SubCertificatesType subCertificates = new SubCertificatesType();
	
	for (Certificate cert : certChain) {
		X509Certificate x509Cert = (X509Certificate) cert;
		// Check whether the pathLen constraint is set which indicates if this certificate is a CA
		if (x509Cert.getBasicConstraints() != -1)
			try {
				subCertificates.getCertificate().add(x509Cert.getEncoded());
			} catch (CertificateEncodingException e) {
				X500Principal subject = x509Cert.getIssuerX500Principal();
				getLogger().error("A CertificateEncodingException occurred while trying to get certificate " +
								  "with distinguished name '" + subject.getName().toString() + "'", e);
			}
	}
	
	if (subCertificates.getCertificate().size() == 0) {
		getLogger().warn("No intermediate CAs found in given certificate array");
	}
	
	return subCertificates;
}
 
Example #19
Source File: ProviderApiManagerTest.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void test_handleIntentSetupProvider_happyPath_no_preseededProviderAndCA() throws IOException, CertificateEncodingException, NoSuchAlgorithmException, JSONException {
    Provider provider = new Provider("https://riseup.net");

    mockFingerprintForCertificate("a5244308a1374709a9afce95e3ae47c1b44bc2398c0a70ccbf8b3a8a97f29494");
    mockProviderApiConnector(NO_ERROR);
    providerApiManager = new ProviderApiManager(mockPreferences, mockResources, mockClientGenerator(), new TestProviderApiServiceCallback());
    Bundle expectedResult = mockBundle();

    expectedResult.putBoolean(BROADCAST_RESULT_KEY, true);
    expectedResult.putParcelable(PROVIDER_KEY, provider);

    Intent providerApiCommand = mockIntent();

    providerApiCommand.setAction(ProviderAPI.SET_UP_PROVIDER);
    providerApiCommand.putExtra(ProviderAPI.RECEIVER_KEY, mockResultReceiver(PROVIDER_OK, expectedResult));
    providerApiCommand.putExtra(PROVIDER_KEY, provider);

    providerApiManager.handleIntent(providerApiCommand);
}
 
Example #20
Source File: mySSLSession.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public mySSLSession(Certificate[] xc) throws CertificateEncodingException, CertificateException {
    certs = xc;
    xCerts = new X509Certificate[xc.length];
    int i = 0;
    for (Certificate cert : xc) {
        xCerts[i++] = X509Certificate.getInstance(cert.getEncoded());
    }
}
 
Example #21
Source File: X509CertPath.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKCS#7 format.
 *
 * @return a byte array containing the binary encoding of the PKCS#7 object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #22
Source File: V3SigningCertificateLineage.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
public static byte[] encodeSignedData(X509Certificate certificate, int flags) {
    try {
        byte[] prefixedCertificate = encodeAsLengthPrefixedElement(certificate.getEncoded());
        int payloadSize = 4 + prefixedCertificate.length;
        ByteBuffer result = ByteBuffer.allocate(payloadSize);
        result.order(ByteOrder.LITTLE_ENDIAN);
        result.put(prefixedCertificate);
        result.putInt(flags);
        return encodeAsLengthPrefixedElement(result.array());
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(
                "Failed to encode V3SigningCertificateLineage certificate", e);
    }
}
 
Example #23
Source File: HadoopCMConfigurator.java    From components with Apache License 2.0 5 votes vote down vote up
private void buildCaCerts(StringBuffer caCerts, X509TrustManager xtm) throws CertificateEncodingException {
    if (xtm != null && xtm.getAcceptedIssuers().length > 0) {
        for (Certificate ca : xtm.getAcceptedIssuers()) {
            caCerts.append(CERT_BEGIN);
            caCerts.append(SEPARATOR);
            caCerts.append(Base64.getEncoder().encodeToString(ca.getEncoded()));
            caCerts.append(SEPARATOR);
            caCerts.append(CERT_END);
            caCerts.append(SEPARATOR);
        }
    }
}
 
Example #24
Source File: PrivateKeyResolver.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private PrivateKey resolveX509Certificate(
    XMLX509Certificate x509Cert
) throws XMLSecurityException, KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?");
    byte[] x509CertBytes = x509Cert.getCertificateBytes();

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                byte[] certBytes = null;

                try {
                    certBytes = cert.getEncoded();
                } catch (CertificateEncodingException e1) {
                }

                if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    }
                    catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
 
Example #25
Source File: CmpClientImpl.java    From xipki with Apache License 2.0 5 votes vote down vote up
/**
 * Configure the CAs automatically.
 *
 * @return names of CAs which may not been configured.
 */
private Set<String> autoConfCas(Set<String> caNames) {
  if (caNames.isEmpty()) {
    return Collections.emptySet();
  }

  Set<String> caNamesWithError = new HashSet<>();

  Set<String> errorCaNames = new HashSet<>();
  for (String name : caNames) {
    CaConf ca = casMap.get(name);

    try {
      CaConf.CaInfo caInfo = ca.getAgent().retrieveCaInfo(name, null);
      if (ca.isCertAutoconf()) {
        ca.setCertchain(caInfo.getCertchain());
      }
      if (ca.isCertprofilesAutoconf()) {
        ca.setCertprofiles(caInfo.getCertprofiles());
      }
      if (ca.isCmpControlAutoconf()) {
        ca.setCmpControl(caInfo.getCmpControl());
      }
      if (ca.isDhpocAutoconf()) {
        ca.setDhpocs(caInfo.getDhpocs());
      }
      LOG.info("retrieved CAInfo for CA " + name);
    } catch (CmpClientException | PkiErrorException | CertificateEncodingException
          | RuntimeException ex) {
      errorCaNames.add(name);
      caNamesWithError.add(name);
      LogUtil.error(LOG, ex, "could not retrieve CAInfo for CA " + name);
    }
  }

  return caNamesWithError;
}
 
Example #26
Source File: KeycloakOauthPolicyTest.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSucceedWithValidHeaderAuthToken() throws CertificateEncodingException, IOException {
    String token = generateAndSerializeToken();

    apiRequest.getHeaders().put("Authorization", "Bearer " + token);
    keycloakOauthPolicy.apply(apiRequest, mContext, config, mChain);

    verify(mChain, times(1)).doApply(apiRequest);
    verify(mChain, never()).doFailure(any(PolicyFailure.class));
}
 
Example #27
Source File: X509CertificatePair.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the DER encoded form of the certificate pair.
 *
 * @return The encoded form of the certificate pair.
 * @throws CerticateEncodingException If an encoding exception occurs.
 */
public byte[] getEncoded() throws CertificateEncodingException {
    try {
        if (encoded == null) {
            DerOutputStream tmp = new DerOutputStream();
            emit(tmp);
            encoded = tmp.toByteArray();
        }
    } catch (IOException ex) {
        throw new CertificateEncodingException(ex.toString());
    }
    return encoded;
}
 
Example #28
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static void printKeyAndCert(String prefix, KeyAndCert keyAndCert)
    throws CertificateEncodingException, IOException {
  printCert(prefix, keyAndCert.getCert());
  System.out.println("-----BEGIN PRIVATE KEY-----");
  System.out.println(Base64.encodeToString(keyAndCert.getKey().getEncoded(), true));
  System.out.println("-----END PRIVATE KEY-----");
}
 
Example #29
Source File: RecoverySnapshotStorage.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the latest {@code snapshot} for the recovery agent {@code uid}.
 */
public synchronized void put(int uid, KeyChainSnapshot snapshot) {
    mSnapshotByUid.put(uid, snapshot);

    try {
        writeToDisk(uid, snapshot);
    } catch (IOException | CertificateEncodingException e) {
        Log.e(TAG,
                String.format(Locale.US, "Error persisting snapshot for %d to disk", uid),
                e);
    }
}
 
Example #30
Source File: SSLUtilsTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private static String getSha1Fingerprint(Certificate cert) {
	if (cert == null) {
		return null;
	}
	try {
		MessageDigest digest = MessageDigest.getInstance("SHA1");
		return toHexadecimalString(digest.digest(cert.getEncoded()));
	} catch (NoSuchAlgorithmException | CertificateEncodingException e) {
		// ignore
	}
	return null;
}