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

The following examples show how to use java.security.cert.X509Certificate#getEncoded() . 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: BlacklistedCertsConverter.java    From jdk8u60 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 2
Source File: CertificateParser.java    From ApkToolPlus with Apache License 2.0 6 votes vote down vote up
/**
 * get certificate info
 *
 * @throws IOException
 * @throws CertificateEncodingException
 */
public void parse() throws IOException, CertificateException {

    PKCS7 pkcs7 = new PKCS7(Utils.toByteArray(in));
    X509Certificate[] certificates = pkcs7.getCertificates();
    certificateMetas = new ArrayList<>();
    for (X509Certificate certificate : certificates) {
        CertificateMeta certificateMeta = new CertificateMeta();
        certificateMetas.add(certificateMeta);

        byte[] bytes = certificate.getEncoded();
        String certMd5 = md5Digest(bytes);
        String publicKeyString = byteToHexString(bytes);
        String certBase64Md5 = md5Digest(publicKeyString);
        certificateMeta.setData(bytes);
        certificateMeta.setCertBase64Md5(certBase64Md5);
        certificateMeta.setCertMd5(certMd5);
        certificateMeta.setStartDate(certificate.getNotBefore());
        certificateMeta.setEndDate(certificate.getNotAfter());
        certificateMeta.setSignAlgorithm(certificate.getSigAlgName());
        certificateMeta.setSignAlgorithmOID(certificate.getSigAlgOID());
    }
}
 
Example 3
Source File: BlacklistedCertsConverter.java    From jdk8u_jdk 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 4
Source File: JCECrypter.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] getCertificateEncoded(String alias) throws CryptologistException{
	X509Certificate cert = getCertificate(alias);
	if (cert != null) {
		try {
			return cert.getEncoded();
		} catch (CertificateEncodingException ce) {
			throw new CryptologistException("Could not encode certificate",
				CryptologistException.ERR_CERTIFICATE_ENCODING);
		}
	}
	return null;
}
 
Example 5
Source File: CertificateMessage.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
T13CertificateMessage(HandshakeContext context,
        byte[] requestContext, X509Certificate[] certificates)
        throws SSLException, CertificateException  {
    super(context);

    this.requestContext = requestContext.clone();
    this.certEntries = new LinkedList<>();
    for (X509Certificate cert : certificates) {
        byte[] encoded = cert.getEncoded();
        SSLExtensions extensions = new SSLExtensions(this);
        certEntries.add(new CertificateEntry(encoded, extensions));
    }
}
 
Example 6
Source File: WindowsIT.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
private static String getThumbPrint(final X509Certificate cert) throws NoSuchAlgorithmException,
    CertificateEncodingException {
  final MessageDigest md = MessageDigest.getInstance("SHA-1");
  final byte[] der = cert.getEncoded();
  md.update(der);
  final byte[] digest = md.digest();
  return hexify(digest);
}
 
Example 7
Source File: Application.java    From chrome-native-messaging-java with MIT License 5 votes vote down vote up
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);
}
 
Example 8
Source File: FileKeyManagerService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String getSha1Fingerprint(X509Certificate cert, String algo) throws Exception {
    MessageDigest md = MessageDigest.getInstance(algo);
    byte[] der = cert.getEncoded();
    md.update(der);
    byte[] digest = md.digest();
    return hexify(digest);

}
 
Example 9
Source File: PKIXCertPath.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return a DERObject containing the encoded certificate.
 *
 * @param cert the X509Certificate object to be encoded
 *
 * @return the DERObject
 **/
   private DERObject getEncodedX509Certificate( X509Certificate cert )
throws CertificateEncodingException
   {
try {
    ByteArrayInputStream inStream = new ByteArrayInputStream( cert.getEncoded() );
    DERInputStream derInStream = new DERInputStream( inStream );
    return derInStream.readObject();
} catch ( IOException ex ) {
    throw new CertificateEncodingException( "IOException caught while encoding certificate\n" + ex.toString() );
}
   }
 
Example 10
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
	cert.checkValidity(); 
	String signature = getSignature(key);
	document.setSello(signature);
	byte[] bytes = cert.getEncoded();
	Base64 b64 = new Base64(-1);
	String certStr = b64.encodeToString(bytes);
	document.setCertificado(certStr);
	BigInteger bi = cert.getSerialNumber();
	document.setNoCertificado(new String(bi.toByteArray()));
}
 
Example 11
Source File: PKITest.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private VaultResponseData generateKeyPair(Date startDate, long valid) throws Exception {
    CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA");
    certGen.generate(2048);

    X500Name x500Name = new X500Name("CN=Test");
    X509Certificate cert = certGen.getSelfCertificate(x500Name, startDate, valid);


    byte[] encodedPrivateKey = certGen.getPrivateKey().getEncoded();
    byte[] encodedPublicKey = cert.getEncoded();

    String privateKeySb = "-----BEGIN PRIVATE KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPrivateKey) +
            "\n-----END PRIVATE KEY-----";
    String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPublicKey) +
            "\n-----END PUBLIC KEY-----";

    privateKeySb = privateKeySb.replaceAll("\\n", "\\\\n");
    privateKeySb = privateKeySb.replaceAll("\\r", "");

    publicKey = publicKey.replaceAll("\\n", "\\\\n");
    publicKey = publicKey.replaceAll("\\r", "");

    VaultResponseData vaultResponseData = new VaultResponseData();
    vaultResponseData.setPrivate_key(privateKeySb);
    vaultResponseData.setCertificate(publicKey);
    return vaultResponseData;
}
 
Example 12
Source File: CertificateManager.java    From jadx with Apache License 2.0 5 votes vote down vote up
public static String getThumbPrint(X509Certificate cert, String type)
		throws NoSuchAlgorithmException, CertificateEncodingException {
	MessageDigest md = MessageDigest.getInstance(type);
	byte[] der = cert.getEncoded();
	md.update(der);
	byte[] digest = md.digest();
	return hexify(digest);
}
 
Example 13
Source File: ClientSelfSignedAuthProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private static String getThumbprint(X509Certificate cert, String algorithm)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest md = MessageDigest.getInstance(algorithm);
    byte[] der = cert.getEncoded();
    md.update(der);
    byte[] digest = md.digest();
    return Base64URL.encode(digest).toString();
}
 
Example 14
Source File: X509CertPath.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 15
Source File: SecurityFixture.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
@BeforeTest
public void setUp() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    keyStore.load(getClass().getClassLoader().getResourceAsStream("test-keystore.pfx"), PASSWORD);

    Key clientPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
    if (clientPrivateKey instanceof PrivateKey) {
        clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS);
        clientCertificateBytes = clientCertificate.getEncoded();

        PublicKey clientPublicKey = clientCertificate.getPublicKey();
        clientKeyPair = new KeyPair(clientPublicKey, (PrivateKey) clientPrivateKey);
    }

    Key serverPrivateKey = keyStore.getKey(SERVER_ALIAS, PASSWORD);
    if (serverPrivateKey instanceof PrivateKey) {
        serverCertificate = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS);
        serverCertificateBytes = serverCertificate.getEncoded();

        PublicKey serverPublicKey = serverCertificate.getPublicKey();
        serverKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
    }

    serverCertificateManager = new TestCertificateManager(
            serverKeyPair,
            serverCertificate
    );

    serverCertificateValidator = new TestCertificateValidator(clientCertificate);
}
 
Example 16
Source File: Signature.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Bounce the given {@link Signature} through a decode/encode cycle.
 *
 * @throws CertificateException if the before/after length differs
 *             substantially, usually a signal of something fishy going on.
 * @hide
 */
public static Signature bounce(CertificateFactory cf, Signature s) throws CertificateException {
    final InputStream is = new ByteArrayInputStream(s.mSignature);
    final X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
    final Signature sPrime = new Signature(cert.getEncoded());

    if (Math.abs(sPrime.mSignature.length - s.mSignature.length) > 2) {
        throw new CertificateException("Bounced cert length looks fishy; before "
                + s.mSignature.length + ", after " + sPrime.mSignature.length);
    }

    return sPrime;
}
 
Example 17
Source File: LogItem.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint({"StringFormatMatches", "StringFormatInvalid"})
private String getMobileInfoString(Context c) {
    c.getPackageManager();
    String apksign = "error getting package signature";
    String version = "error getting version";
    try {
        @SuppressLint("PackageManagerGetSignatures") Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();
        if (Arrays.equals(digest, VpnStatus.officalkey)) apksign = c.getString(R.string.official_build);
        else if (Arrays.equals(digest, VpnStatus.officaldebugkey)) apksign = c.getString(R.string.debug_build);
        else if (Arrays.equals(digest, VpnStatus.amazonkey)) apksign = "amazon version";
        else if (Arrays.equals(digest, VpnStatus.fdroidkey)) apksign = "F-Droid built and signed version";
        else apksign = c.getString(R.string.built_by, cert.getSubjectX500Principal().getName());
        PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
        version = packageinfo.versionName;
    } catch (PackageManager.NameNotFoundException | CertificateException |
            NoSuchAlgorithmException ignored) {
    }
    Object[] argsext = Arrays.copyOf(mArgs, mArgs.length);
    argsext[argsext.length - 1] = apksign;
    argsext[argsext.length - 2] = version;
    return c.getString(R.string.mobile_info, argsext);
}
 
Example 18
Source File: X509CertPath.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 19
Source File: VpnStatus.java    From android with GNU General Public License v3.0 4 votes vote down vote up
@SuppressLint("StringFormatMatches")
private String getMobileInfoString(Context c) {
    c.getPackageManager();
    String apksign = "error getting package signature";

    String version = "error getting version";
    try {
        @SuppressLint("PackageManagerGetSignatures")
        Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();

        if (Arrays.equals(digest, officalkey))
            apksign = c.getString(R.string.official_build);
        else if (Arrays.equals(digest, officaldebugkey))
            apksign = c.getString(R.string.debug_build);
        else if (Arrays.equals(digest, amazonkey))
            apksign = "amazon version";
        else if (Arrays.equals(digest, fdroidkey))
            apksign = "F-Droid built and signed version";
        else
            apksign = c.getString(R.string.built_by, cert.getSubjectX500Principal().getName());

        PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
        version = packageinfo.versionName;

    } catch (NameNotFoundException | CertificateException |
            NoSuchAlgorithmException ignored) {
    }

    Object[] argsext = Arrays.copyOf(mArgs, mArgs.length + 2);
    argsext[argsext.length - 1] = apksign;
    argsext[argsext.length - 2] = version;

    return c.getString(R.string.mobile_info_extended, argsext);

}
 
Example 20
Source File: CertPin.java    From java-pinning with Apache License 2.0 4 votes vote down vote up
@Override
public boolean pinsCertificate(X509Certificate x509certificate) throws CertificateEncodingException {
	byte[] pubkey = x509certificate.getEncoded();
	return pinsCertificate(pubkey);
}