下面列出了怎么用java.security.cert.CertificateEncodingException的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
}
/**
* 根据单个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;
}
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;
}
@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
}
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;
}
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());
}
}
@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);
}
@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);
}
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);
}
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);
}
@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);
}
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);
}
/**
* 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;
}
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;
}
}
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;
}
@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);
}
@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());
}
}
/**
* 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;
}
/**
* 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;
}
private byte[] toDEREncoded(ASN1Encodable obj)
throws CertificateEncodingException
{
try
{
return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
throw new CertificateEncodingException("Exception thrown: " + e);
}
}
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;
}
/**
* @param cert
* @param formatter
* @return
* @throws CertificateEncodingException
*/
private static CertData fillCertData(X509Certificate cert, Format formatter)
throws CertificateEncodingException {
CertData certData = new CertData();
certData.setSubjectDN(cert.getSubjectDN().getName());
certData.setIssuerDN(cert.getIssuerDN().getName());
certData.setSerialNumber(cert.getSerialNumber());
certData.setVersion(cert.getVersion());
certData.setNotAfter(formatter.format(cert.getNotAfter()));
certData.setNotBefore(formatter.format(cert.getNotBefore()));
certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));
return certData;
}
protected static void printCert(String prefix, X509Cert cert)
throws CertificateEncodingException {
System.out.println(prefix);
System.out.print("Subject: ");
System.out.println(cert.getSubjectRfc4519Text());
System.out.print(" Issuer: ");
System.out.println(cert.getIssuerRfc4519Text());
System.out.print(" Serial: " + cert.getSerialNumberHex());
System.out.println("NotBefore: " + cert.getNotBefore());
System.out.println(" NotAfter: " + cert.getNotAfter());
String pemCert = toPEM("CERTIFICATE", cert.getEncoded());
System.out.println(pemCert);
}
private static List<String> getCommonNames(X509Certificate certificate) {
List<String> domains = new ArrayList<>();
try {
X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
RDN[] rdns = x500name.getRDNs(BCStyle.CN);
for (int i = 0; i < rdns.length; ++i) {
domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue()));
}
return domains;
} catch (CertificateEncodingException e) {
return domains;
}
}
/**
* Returns the encoded form of this certification path, using
* the default encoding.
*
* @return the encoded bytes
* @exception CertificateEncodingException if an encoding error occurs
**/
public byte[] getEncoded()
throws CertificateEncodingException
{
Iterator iter = getEncodings();
if ( iter.hasNext() )
{
Object enc = iter.next();
if ( enc instanceof String )
{
return getEncoded((String)enc);
}
}
return null;
}
public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
List<String> emails = new ArrayList<>();
if (alternativeNames != null) {
for (List<?> san : alternativeNames) {
Integer type = (Integer) san.get(0);
if (type == 1) {
emails.add((String) san.get(1));
}
}
}
X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
}
String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
if (emails.size() >= 1) {
return new Pair<>(Jid.of(emails.get(0)), name);
} else if (name != null) {
try {
Jid jid = Jid.of(name);
if (jid.isBareJid() && jid.getLocal() != null) {
return new Pair<>(jid, null);
}
} catch (IllegalArgumentException e) {
return null;
}
}
return null;
}
public static String getThumbPrint(X509Certificate cert)
throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
static Security toSecurity(InternalChannelz.Security security) {
Preconditions.checkNotNull(security);
Preconditions.checkState(
security.tls != null ^ security.other != null,
"one of tls or othersecurity must be non null");
if (security.tls != null) {
Tls.Builder tlsBuilder
= Tls.newBuilder().setStandardName(security.tls.cipherSuiteStandardName);
try {
if (security.tls.localCert != null) {
tlsBuilder.setLocalCertificate(ByteString.copyFrom(
security.tls.localCert.getEncoded()));
}
if (security.tls.remoteCert != null) {
tlsBuilder.setRemoteCertificate(ByteString.copyFrom(
security.tls.remoteCert.getEncoded()));
}
} catch (CertificateEncodingException e) {
logger.log(Level.FINE, "Caught exception", e);
}
return Security.newBuilder().setTls(tlsBuilder).build();
} else {
OtherSecurity.Builder builder = OtherSecurity.newBuilder().setName(security.other.name);
if (security.other.any != null) {
builder.setValue((Any) security.other.any);
}
return Security.newBuilder().setOther(builder).build();
}
}
private JWSHeader buildJWSHeader() throws KeyResolverException, CertificateEncodingException,
NoSuchAlgorithmException {
String certThumbPrint = null;
certThumbPrint = CertificateUtils.getThumbPrint(CertificateUtils.getKeyResolver().getCertificate());
headerBuilder.keyID(certThumbPrint);
headerBuilder.x509CertThumbprint(new Base64URL(certThumbPrint));
return headerBuilder.build();
}
public static KeyInfoType getKeyInfo(X509Certificate cert) throws CertificateEncodingException {
KeyInfoType keyInfo = new KeyInfoType();
JAXBElement<byte[]> certificate = new ObjectFactory().createX509DataTypeX509Certificate(cert.getEncoded());
X509DataType x509DataType = new X509DataType();
List<Object> x509DataContent = x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName();
x509DataContent.add(certificate);
JAXBElement<X509DataType> x509Data = new ObjectFactory().createX509Data(x509DataType);
List<Object> keyInfoContent = keyInfo.getContent();
keyInfoContent.add(x509Data);
return keyInfo;
}