Java Code Examples for java.security.cert.X509Certificate#getSigAlgName()

The following examples show how to use java.security.cert.X509Certificate#getSigAlgName() . 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: DisabledAlgorithmConstraints.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkConstraints(Set<CryptoPrimitive> primitives,
        CertConstraintParameters cp) throws CertPathValidatorException {

    X509Certificate cert = cp.getCertificate();
    String algorithm = cert.getSigAlgName();

    // Check signature algorithm is not disabled
    if (!permits(primitives, algorithm, null)) {
        throw new CertPathValidatorException(
                "Algorithm constraints check failed on disabled "+
                        "signature algorithm: " + algorithm,
                null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
    }

    // Check key algorithm is not disabled
    if (!permits(primitives, cert.getPublicKey().getAlgorithm(), null)) {
        throw new CertPathValidatorException(
                "Algorithm constraints check failed on disabled "+
                        "public key algorithm: " + algorithm,
                null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
    }

    // Check the certificate and key constraints
    algorithmConstraints.permits(cp);

}
 
Example 2
Source File: X509CertUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * For a given X.509 certificate get the algorithm of its signature. Useful
 * as the JCE may return an unfriendly name. This method converts known
 * "unfriendly names" to friendly names.
 *
 * @param cert
 *            The certificate
 * @return The algorithm
 */
public static String getCertificateSignatureAlgorithm(X509Certificate cert) {
	// Unfriendly JCE sig names may be actual JCE names or OIDs
	String algorithm = cert.getSigAlgName();

	SignatureType type = SignatureType.resolveJce(algorithm);

	if (type != null) {
		algorithm = type.friendly();
	} else {
		type = SignatureType.resolveOid(algorithm);

		if (type != null) {
			algorithm = type.friendly();
		}
	}

	return algorithm;
}
 
Example 3
Source File: ExprUrlSSLAlgorithm.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        return new String[]{sc.getSigAlgName()};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 4
Source File: Keystores.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private static X509Certificate createSignedCertificate(final X509Certificate cetrificate, final X509Certificate issuerCertificate,
                                                       final PrivateKey issuerPrivateKey) {
    try {
        Principal issuer = issuerCertificate.getSubjectDN();
        String issuerSigAlg = issuerCertificate.getSigAlgName();

        byte[] inCertBytes = cetrificate.getTBSCertificate();
        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, (X500Name) issuer);

        //No need to add the BasicContraint for leaf cert
        if (!cetrificate.getSubjectDN().getName().equals("CN=TOP")) {
            CertificateExtensions exts = new CertificateExtensions();
            BasicConstraintsExtension bce = new BasicConstraintsExtension(true, -1);
            exts.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(false, bce.getExtensionValue()));
            info.set(X509CertInfo.EXTENSIONS, exts);
        }

        final X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);

        return outCert;
    } catch (final Exception ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 5
Source File: DefaultSignatureAlgorithm.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void run(String keyAlg, int keySize,
                String expectedSigAlg, String sigAlg) throws Exception {
    String alias = keyAlg + keySize + System.currentTimeMillis();
    String cmd = "-keystore ks -storepass changeit" +
            " -keypass changeit -alias " + alias +
            " -keyalg " + keyAlg + " -keysize " + keySize +
            " -genkeypair -dname CN=" + alias + " -debug";
    if (sigAlg != null) {
        cmd += " -sigalg " + sigAlg;
    }
    Main.main(cmd.split(" "));

    KeyStore ks = KeyStore.getInstance(
            new File("ks"), "changeit".toCharArray());
    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    String actualSigAlg = cert.getSigAlgName();
    if (!actualSigAlg.equals(expectedSigAlg)) {
        throw new Exception("Failure at " + alias + ": expected "
                + expectedSigAlg + ", actually " + actualSigAlg);
    }
}
 
Example 6
Source File: OxAuthCryptoProvider.java    From oxAuth with MIT License 6 votes vote down vote up
public SignatureAlgorithm getSignatureAlgorithm(String alias) throws KeyStoreException {
    Certificate[] chain = keyStore.getCertificateChain(alias);
    if ((chain == null) || chain.length == 0) {
        return null;
    }

    X509Certificate cert = (X509Certificate) chain[0];

    String sighAlgName = cert.getSigAlgName();

    for (SignatureAlgorithm sa : SignatureAlgorithm.values()) {
        if (sighAlgName.equalsIgnoreCase(sa.getAlgorithm())) {
            return sa;
        }
    }

    return null;
}
 
Example 7
Source File: Main.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void checkWeak(String label, Certificate cert)
        throws KeyStoreException {
    if (cert instanceof X509Certificate) {
        X509Certificate xc = (X509Certificate)cert;
        // No need to check the sigalg of a trust anchor
        String sigAlg = isTrustedCert(cert) ? null : xc.getSigAlgName();
        checkWeak(label, sigAlg, xc.getPublicKey());
    }
}
 
Example 8
Source File: Main.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void checkWeak(String label, Certificate cert)
        throws KeyStoreException {
    if (cert instanceof X509Certificate) {
        X509Certificate xc = (X509Certificate)cert;
        // No need to check the sigalg of a trust anchor
        String sigAlg = isTrustedCert(cert) ? null : xc.getSigAlgName();
        checkWeak(label, sigAlg, xc.getPublicKey());
    }
}
 
Example 9
Source File: XMLDSigVerifier.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private XMLDsigVerificationResult validateCertificateIssuer(XMLSignature signature, XMLDsigVerificationResult result) {
    try
    {
        KeyInfo xmlKeyInfo = signature.getKeyInfo();
        List<X509Certificate> certList = getCertificateChainFromXML(xmlKeyInfo.getContent());
        List<X509Certificate> orderedCerts = reorderCertificateChain(certList);
        X509Certificate signingCert = selectSigningKeyFromXML(xmlKeyInfo.getContent());
        //Throws if invalid
        validateCertificateChain(orderedCerts);
        result.issuerPrincipal = signingCert.getIssuerX500Principal().getName();
        result.subjectPrincipal = signingCert.getSubjectX500Principal().getName();
        result.keyType = signingCert.getSigAlgName();
        for (Object o : xmlKeyInfo.getContent())
        {
            XMLStructure xmlStructure = (XMLStructure) o;
            if (xmlStructure instanceof KeyName)
            {
                result.keyName = ((KeyName) xmlStructure).getName();
            }
        }
    }
    catch(Exception e)
    {
        result.isValid = false;
        result.failureReason = e.getMessage();
    }
    return result;
}
 
Example 10
Source File: Main.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert.with.weak"));
    PublicKey pkey = cert.getPublicKey();
    String sigName = cert.getSigAlgName();
    // No need to warn about sigalg of a trust anchor
    if (!isTrustedCert(cert)) {
        sigName = withWeak(sigName);
    }
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("SHA-1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    sigName,
                    withWeak(pkey),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 11
Source File: Main.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private void checkWeak(String label, Certificate cert)
        throws KeyStoreException {
    if (cert instanceof X509Certificate) {
        X509Certificate xc = (X509Certificate)cert;
        // No need to check the sigalg of a trust anchor
        String sigAlg = isTrustedCert(cert) ? null : xc.getSigAlgName();
        checkWeak(label, sigAlg, xc.getPublicKey());
    }
}
 
Example 12
Source File: X509CertificateShortInfo.java    From oxTrust with MIT License 5 votes vote down vote up
public X509CertificateShortInfo(String alias, X509Certificate cert) {
	this.alias = alias;

	if (cert.getIssuerDN() != null)
		issuer = cert.getIssuerDN().getName();
	if (cert.getSubjectDN() != null)
		subject = cert.getSubjectDN().getName();
	algorithm = cert.getSigAlgName();
	notBeforeDatetime = cert.getNotBefore();
	notAfterDatetime = cert.getNotAfter();

	updateViewStyle();
}
 
Example 13
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 14
Source File: Main.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 15
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 16
Source File: verifyFido2RegistrationPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void verifyCryptographyOptions(CryptographyPolicyOptions cryptoOp, JsonObject clientJson,
        FIDO2AttestationObject attObject, Integer version) throws SKFEException {
    ArrayList<String> allowedRSASignatures = cryptoOp.getAllowedRSASignatures();
    ArrayList<String> allowedECSignatures = cryptoOp.getAllowedECSignatures();
    ArrayList<String> supportedCurves = cryptoOp.getSupportedEllipticCurves();
    ArrayList<String> allowedAttestationFormats = cryptoOp.getAllowedAttestationFormats();
    ArrayList<String> allowedAttestationTypes = cryptoOp.getAllowedAttestationTypes();

    //Verify attestation key
    ArrayList certificateChain = attObject.getAttStmt().getX5c();
    if(certificateChain != null){
        X509Certificate attestationCert = cryptoCommon.generateX509FromBytes((byte[]) certificateChain.get(0));

        if(attestationCert == null){
            throw new SKFEException("Failed to parse X509Certificate. Check logs for details");
        }
        PublicKey attestationKey = attestationCert.getPublicKey();
        String attestationAlgType = attestationKey.getAlgorithm();
        if(!attestationAlgType.equalsIgnoreCase("RSA") && !attestationAlgType.equalsIgnoreCase("EC")){
            throw new SKFEException("Unknown key algorithm (Attestation)");
        }
        if((allowedRSASignatures == null
                || !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))
                && (allowedECSignatures == null
                || !allowedECSignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))){
            throw new SKFEException("Signature Algorithm not supported by policy (Attestation): " + attestationCert.getSigAlgName());
        }

        //Verify that the curve used by the attestation key is approved
        if(attestationAlgType.equalsIgnoreCase("EC")){
            byte[] enc = attestationKey.getEncoded();
            SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(enc));
            AlgorithmIdentifier algid = spki.getAlgorithm();
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) algid.getParameters();
            if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromOID(oid))){
                throw new SKFEException("EC Curve not supported by policy (Attestation)");
            }
        }
    }

    //Verify signing key
    PublicKey signingKey = attObject.getAuthData().getAttCredData().getPublicKey();
    String signingAlgType = signingKey.getAlgorithm();
    if(!signingAlgType.equalsIgnoreCase("RSA") && !signingAlgType.equalsIgnoreCase("EC")){
        throw new SKFEException("Unknown attestation key algorithm (Signing)");
    }
    if((allowedRSASignatures == null
            || !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))
            && (allowedECSignatures == null
            ||!allowedECSignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))){
        throw new SKFEException("Rejected key algorithm (Signing): " +
                skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg()));
    }
    if(signingAlgType.equalsIgnoreCase("EC")){
        ECKeyObject eckey = (ECKeyObject) attObject.getAuthData().getAttCredData().getFko();
        if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromFIDOECCCurveID(eckey.getCrv()))){
            throw new SKFEException("EC Curve not supported by policy (Signing)");
        }
    }

    //Verify allowed AttestationFormat
    if(!allowedAttestationFormats.contains(attObject.getAttFormat())){
        throw new SKFEException("Attestation format not supported by policy: " + attObject.getAttFormat());
    }

    //Verify allowed AttestationType
    if (!allowedAttestationTypes.contains(attObject.getAttStmt().getAttestationType())) {
        throw new SKFEException("Attestation type not supported by policy: " + attObject.getAttStmt().getAttestationType());
    }
}
 
Example 17
Source File: Main.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 18
Source File: CertificateValidatorImpl.java    From UAF with Apache License 2.0 4 votes vote down vote up
public boolean validate(byte[] certBytes, byte[] signedDataBytes,
		byte[] signatureBytes) throws NoSuchAlgorithmException,
		IOException, Exception {
	X509Certificate x509Certificate = X509.parseDer(certBytes);
	logger.info(" : Attestation Cert : " + x509Certificate);

	String sigAlgOID = x509Certificate.getSigAlgName();
	logger.info(" : Cert Alg : " + sigAlgOID);

	try {
		if (sigAlgOID.contains("RSA")) {
			if (!RSA.verify(x509Certificate, signedDataBytes,
					signatureBytes)) {
				logger.info(" : Not verified; Cert Alg : " + sigAlgOID);
				return false;
				// throw new Exception(
				// "Signature is RSA - Alg RAWRSASSA-PSS fail - Requested alg:"
				// + sigAlgOID);
			} else {
				return true;
			}
		}

		BigInteger[] rs = null;
		if (signatureBytes.length == 64) {
			rs = Asn1.transformRawSignature(signatureBytes);
		} else {
			rs = Asn1.decodeToBigIntegerArray(signatureBytes);
		}
		try {
			if (!NamedCurve.verify(KeyCodec
					.getKeyAsRawBytes((ECPublicKey) x509Certificate
							.getPublicKey()), SHA.sha(signedDataBytes,
					"SHA-256"), rs)) {
				logger.info(" : Not verified; Cert Alg : " + sigAlgOID);
				return false;
				// throw new Exception(
				// "Signature is 64 bytes - Alg SHA256withEC fail - Requested alg:"
				// + sigAlgOID);
			} else {
				return true;
			}
		} catch (Exception fromVerify) {
			if (!NamedCurve.verifyUsingSecp256k1(KeyCodec
					.getKeyAsRawBytes((ECPublicKey) x509Certificate
							.getPublicKey()), SHA.sha(signedDataBytes,
					"SHA-256"), rs)) {
				logger.info(" : Not verified; Cert Alg : " + sigAlgOID);
				return false;
				// throw new Exception(
				// "Signature is 64 bytes - Alg SHA256withEC fail - Requested alg:"
				// + sigAlgOID);
			} else {
				return true;
			}
		}

	} catch (Exception thrown) {
		logger.log(Level.INFO, "Exception in attest cert validation!",
				thrown);
		return false;
	}
}
 
Example 19
Source File: Main.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert.with.weak"));
    PublicKey pkey = cert.getPublicKey();
    String sigName = cert.getSigAlgName();
    // No need to warn about sigalg of a trust anchor
    if (!isTrustedCert(cert)) {
        sigName = withWeak(sigName);
    }
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    sigName,
                    withWeak(pkey),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 20
Source File: MetadataWriter.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static Document signMetaInfo(X509Certificate signingCert, Key signingKey,
                                     Document doc, String referenceID
) throws Exception {
    String signatureMethod = null;
    if ("SHA1withDSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.DSA_SHA1;
    } else if ("SHA1withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else if ("SHA256withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else {
        LOG.error("Unsupported signature method: " + signingCert.getSigAlgName());
        throw new RuntimeException("Unsupported signature method: " + signingCert.getSigAlgName());
    }

    List<Transform> transformList = new ArrayList<>();
    transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null));
    transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                                                                      (C14NMethodParameterSpec)null));

    // Create a Reference to the enveloped document (in this case,
    // you are signing the whole document, so a URI of "" signifies
    // that, and also specify the SHA1 digest algorithm and
    // the ENVELOPED Transform.
    Reference ref =
        XML_SIGNATURE_FACTORY.newReference("#" + referenceID,
                                           XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null),
                                           transformList,
                                           null, null);

    // Create the SignedInfo.
    SignedInfo si =
        XML_SIGNATURE_FACTORY.newSignedInfo(
            XML_SIGNATURE_FACTORY.newCanonicalizationMethod(
                CanonicalizationMethod.EXCLUSIVE,
                (C14NMethodParameterSpec)null),
                XML_SIGNATURE_FACTORY.newSignatureMethod(signatureMethod, null),
                 Collections.singletonList(ref));

    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<>();
    x509Content.add(signingCert.getSubjectX500Principal().getName());
    x509Content.add(signingCert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    //DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
    dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
    dsc.setNextSibling(doc.getDocumentElement().getFirstChild());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);

    // Marshal, generate, and sign the enveloped signature.
    signature.sign(dsc);

    // Output the resulting document.
    return doc;
}