Search in sources :

Example 1 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project OpenAttestation by OpenAttestation.

the class X509CertificateArrayPemProvider method writeTo.

@Override
public void writeTo(X509Certificate[] t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    try {
        String[] pems = new String[t.length];
        for (int i = 0; i < pems.length; i++) {
            pems[i] = X509Util.encodePemCertificate(t[i]);
        }
        String out = StringUtils.join(pems, "\n");
        IOUtils.write(out, entityStream);
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException)

Example 2 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project OpenAttestation by OpenAttestation.

the class ProvisionTPM method takeOwnership.

/**
	 * Entry point into the program
	 * @throws Exception 
	 */
public static void takeOwnership() throws Exception {
    // throws InvalidKeyException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, NoSuchProviderException, KeyStoreException, CertificateException, IOException, javax.security.cert.CertificateException {
    //get properties file info
    final String OWNER_AUTH = "TpmOwnerAuth";
    final String EC_VALIDITY = "EcValidityDays";
    final String EC_STORAGE = "ecStorage";
    final String PRIVACY_CA_URL = "PrivacyCaUrl";
    final String TRUST_STORE = "TrustStore";
    final String PRIVACY_CA_CERT = "PrivacyCaCertFile";
    final String EC_LOCATION = "ecLocation";
    String ecStorage = "";
    String ecStorageFileName = "";
    String PrivacyCaUrl = "";
    int EcValidityDays = 0;
    String PrivacyCaCertFile = "";
    byte[] TpmOwnerAuth = null;
    byte[] encryptCert = null;
    byte[] pubEkMod = null;
    X509Certificate pcaCert = null;
    PublicKey publicKey = null;
    //This is for logging purpose
    String propertiesFileName = ResourceFinder.getLocation("hisprovisioner.properties");
    FileInputStream PropertyFile = null;
    String tpmOwnerAuth = "";
    String homeFolder = "";
    try {
        File propFile = ResourceFinder.getFile("hisprovisioner.properties");
        PropertyFile = new FileInputStream(propFile);
        Properties HisProvisionerProperties = new Properties();
        HisProvisionerProperties.load(new InputStreamReader(PropertyFile, "UTF-8"));
        homeFolder = propFile.getAbsolutePath();
        homeFolder = homeFolder.substring(0, homeFolder.indexOf("hisprovisioner.properties"));
        log.info("Home folder : " + homeFolder);
        EcValidityDays = Integer.parseInt(HisProvisionerProperties.getProperty(EC_VALIDITY, ""));
        tpmOwnerAuth = HisProvisionerProperties.getProperty(OWNER_AUTH, "");
        if (tpmOwnerAuth != null) {
            TpmOwnerAuth = Hex.decodeHex(tpmOwnerAuth.toCharArray());
        }
        //else if (tpmOwnerAuth.length() == 40) {
        //    log.info("owner authentication is hex code formatted");
        //    TpmOwnerAuth = TpmUtils.hexStringToByteArray(tpmOwnerAuth);
        //} else {
        //    log.info("illegal owner authentication detected! accepted owner authentication is 20 or 40 long characters");
        //}
        //TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH, ""));
        PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, "");
        PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, "");
        ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM");
        ecStorageFileName = HisProvisionerProperties.getProperty(EC_LOCATION, ".") + System.getProperty("file.separator") + "EC.cer";
        log.info("ecStorageFileName:" + ecStorageFileName);
    } catch (FileNotFoundException e) {
        throw new PrivacyCAException("Error finding HIS Provisioner properties file (HISprovisionier.properties)", e);
    } catch (IOException e) {
        throw new PrivacyCAException("Error loading HIS Provisioner properties file (HISprovisionier.properties)", e);
    } catch (NumberFormatException e) {
        throw new PrivacyCAException("Error while reading EcValidityDays", e);
    } finally {
        if (PropertyFile != null) {
            try {
                PropertyFile.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Error while closing the property file ", e);
            }
        }
    }
    String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n";
    boolean hasErrors = false;
    if (EcValidityDays == 0) {
        errorString += " - \"EcValidityDays\" value must be the number of validity days for the Endorsement Credential\n";
        hasErrors = true;
    }
    if (TpmOwnerAuth == null) {
        // || TpmOwnerAuth.length != 20){
        errorString += " - \"TpmOwnerAuth\" value must be set representing the TPM owner auth\n";
        hasErrors = true;
    }
    if (hasErrors) {
        throw new PrivacyCAException(errorString);
    }
    //Provision the TPM
    log.info("Performing TPM provisioning...");
    Security.addProvider(new BouncyCastleProvider());
    SecretKey deskey = TpmUtils.generateSecretKey();
    // Take Ownership
    byte[] nonce = null;
    try {
        nonce = TpmUtils.createRandomBytes(20);
        TpmModule.takeOwnership(TpmOwnerAuth, nonce);
    } catch (TpmModuleException e) {
        if (e.toString().contains(".takeOwnership returned nonzero error: 4")) {
            Logger.getLogger(ProvisionTPM.class.getName()).info("Ownership is already taken : ");
            if (!System.getProperty("forceCreateEk", "false").equals("true")) {
                // feature to help with bug #554 and allow admin to force creating an ek (in case it failed the first time due to a non-tpm error such as java missing classes exception
                return;
            }
        } else
            throw e;
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Create Endorsement Certificate
    try {
        nonce = TpmUtils.createRandomBytes(20);
        pubEkMod = TpmModule.getEndorsementKeyModulus(TpmOwnerAuth, nonce);
    } catch (TpmModuleException e) {
        System.out.println("Error getting PubEK: " + e.toString());
    } catch (Exception e) {
        System.out.println("Error getting PubEK: " + e.toString());
    }
    try {
        pcaCert = TpmUtils.certFromFile(homeFolder + PrivacyCaCertFile);
        if (pcaCert != null) {
            publicKey = (RSAPublicKey) pcaCert.getPublicKey();
        }
    } catch (Exception e) {
        System.out.println("print out error message: " + e.toString());
        e.printStackTrace();
    }
    try {
        IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl);
        encryptCert = hisPrivacyCAWebService2.requestGetEC(TpmUtils.encryptDES(pubEkMod, deskey), TpmUtils.encryptRSA(deskey.getEncoded(), publicKey), EcValidityDays);
    } catch (Exception e) {
        System.out.println("FAILED");
        e.printStackTrace();
        System.exit(1);
    }
    //Decrypt and generate endorsement certificate 
    X509Certificate ekCert = null;
    try {
        if (encryptCert != null) {
            ekCert = TpmUtils.certFromBytes(TpmUtils.decryptDES(encryptCert, deskey));
        }
    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Store the new EC in NV-RAM or in the file
    try {
        if (ecStorage.equalsIgnoreCase("file")) {
            File ecFile = new File(ecStorageFileName);
            FileOutputStream ecFileOut = new FileOutputStream(ecFile);
            ecFileOut.write(ekCert.getEncoded());
            ecFileOut.flush();
            ecFileOut.close();
        } else {
            TpmModule.setCredential(TpmOwnerAuth, "EC", ekCert.getEncoded());
        }
        System.out.println(ekCert.getEncoded().length);
    } catch (TpmModuleException e) {
        System.out.println("Error getting PubEK: " + e.toString());
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("DONE");
    //System.exit(0);
    return;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) CertificateException(javax.security.cert.CertificateException) Properties(java.util.Properties) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) IHisPrivacyCAWebService2(gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2) InputStreamReader(java.io.InputStreamReader) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) TpmModuleException(gov.niarl.his.privacyca.TpmModule.TpmModuleException) FileNotFoundException(java.io.FileNotFoundException) CertificateException(javax.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException) SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) TpmModuleException(gov.niarl.his.privacyca.TpmModule.TpmModuleException) File(java.io.File)

Example 3 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ParanoidAndroid.

the class PackageParser method collectCertificates.

public boolean collectCertificates(Package pkg, int flags) {
    pkg.mSignatures = null;
    WeakReference<byte[]> readBufferRef;
    byte[] readBuffer = null;
    synchronized (mSync) {
        readBufferRef = mReadBuffer;
        if (readBufferRef != null) {
            mReadBuffer = null;
            readBuffer = readBufferRef.get();
        }
        if (readBuffer == null) {
            readBuffer = new byte[8192];
            readBufferRef = new WeakReference<byte[]>(readBuffer);
        }
    }
    try {
        JarFile jarFile = new JarFile(mArchiveSourcePath);
        Certificate[] certs = null;
        if ((flags & PARSE_IS_SYSTEM) != 0) {
            // If this package comes from the system image, then we
            // can trust it...  we'll just use the AndroidManifest.xml
            // to retrieve its signatures, not validating all of the
            // files.
            JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILENAME);
            certs = loadCertificates(jarFile, jarEntry, readBuffer);
            if (certs == null) {
                Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + jarEntry.getName() + "; ignoring!");
                jarFile.close();
                mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                return false;
            }
            if (DEBUG_JAR) {
                Slog.i(TAG, "File " + mArchiveSourcePath + ": entry=" + jarEntry + " certs=" + (certs != null ? certs.length : 0));
                if (certs != null) {
                    final int N = certs.length;
                    for (int i = 0; i < N; i++) {
                        Slog.i(TAG, "  Public key: " + certs[i].getPublicKey().getEncoded() + " " + certs[i].getPublicKey());
                    }
                }
            }
        } else {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                final JarEntry je = entries.nextElement();
                if (je.isDirectory())
                    continue;
                final String name = je.getName();
                if (name.startsWith("META-INF/"))
                    continue;
                if (ANDROID_MANIFEST_FILENAME.equals(name)) {
                    pkg.manifestDigest = ManifestDigest.fromInputStream(jarFile.getInputStream(je));
                }
                final Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
                if (DEBUG_JAR) {
                    Slog.i(TAG, "File " + mArchiveSourcePath + " entry " + je.getName() + ": certs=" + certs + " (" + (certs != null ? certs.length : 0) + ")");
                }
                if (localCerts == null) {
                    Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + je.getName() + "; ignoring!");
                    jarFile.close();
                    mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                    return false;
                } else if (certs == null) {
                    certs = localCerts;
                } else {
                    // Ensure all certificates match.
                    for (int i = 0; i < certs.length; i++) {
                        boolean found = false;
                        for (int j = 0; j < localCerts.length; j++) {
                            if (certs[i] != null && certs[i].equals(localCerts[j])) {
                                found = true;
                                break;
                            }
                        }
                        if (!found || certs.length != localCerts.length) {
                            Slog.e(TAG, "Package " + pkg.packageName + " has mismatched certificates at entry " + je.getName() + "; ignoring!");
                            jarFile.close();
                            mParseError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
                            return false;
                        }
                    }
                }
            }
        }
        jarFile.close();
        synchronized (mSync) {
            mReadBuffer = readBufferRef;
        }
        if (certs != null && certs.length > 0) {
            final int N = certs.length;
            pkg.mSignatures = new Signature[certs.length];
            for (int i = 0; i < N; i++) {
                pkg.mSignatures[i] = new Signature(certs[i].getEncoded());
            }
        } else {
            Slog.e(TAG, "Package " + pkg.packageName + " has no certificates; ignoring!");
            mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
            return false;
        }
    } catch (CertificateEncodingException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (IOException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (RuntimeException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
        return false;
    }
    return true;
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Certificate(java.security.cert.Certificate)

Example 4 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ParanoidAndroid.

the class SslCertificate method getDigest.

/**
     * Convenience for UI presentation, not intended as public API.
     */
private static String getDigest(X509Certificate x509Certificate, String algorithm) {
    if (x509Certificate == null) {
        return "";
    }
    try {
        byte[] bytes = x509Certificate.getEncoded();
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(bytes);
        return fingerprint(digest);
    } catch (CertificateEncodingException ignored) {
        return "";
    } catch (NoSuchAlgorithmException ignored) {
        return "";
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 5 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStore method setPrivateKeyEntry.

private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain, KeyStoreParameter params) throws KeyStoreException {
    byte[] keyBytes = null;
    final String pkeyAlias;
    if (key instanceof OpenSSLKeyHolder) {
        pkeyAlias = ((OpenSSLKeyHolder) key).getOpenSSLKey().getAlias();
    } else {
        pkeyAlias = null;
    }
    final boolean shouldReplacePrivateKey;
    if (pkeyAlias != null && pkeyAlias.startsWith(Credentials.USER_PRIVATE_KEY)) {
        final String keySubalias = pkeyAlias.substring(Credentials.USER_PRIVATE_KEY.length());
        if (!alias.equals(keySubalias)) {
            throw new KeyStoreException("Can only replace keys with same alias: " + alias + " != " + keySubalias);
        }
        shouldReplacePrivateKey = false;
    } else {
        // Make sure the PrivateKey format is the one we support.
        final String keyFormat = key.getFormat();
        if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) {
            throw new KeyStoreException("Only PrivateKeys that can be encoded into PKCS#8 are supported");
        }
        // Make sure we can actually encode the key.
        keyBytes = key.getEncoded();
        if (keyBytes == null) {
            throw new KeyStoreException("PrivateKey has no encoding");
        }
        shouldReplacePrivateKey = true;
    }
    // Make sure the chain exists since this is a PrivateKey
    if ((chain == null) || (chain.length == 0)) {
        throw new KeyStoreException("Must supply at least one Certificate with PrivateKey");
    }
    // Do chain type checking.
    X509Certificate[] x509chain = new X509Certificate[chain.length];
    for (int i = 0; i < chain.length; i++) {
        if (!"X.509".equals(chain[i].getType())) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        if (!(chain[i] instanceof X509Certificate)) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        x509chain[i] = (X509Certificate) chain[i];
    }
    final byte[] userCertBytes;
    try {
        userCertBytes = x509chain[0].getEncoded();
    } catch (CertificateEncodingException e) {
        throw new KeyStoreException("Couldn't encode certificate #1", e);
    }
    /*
         * If we have a chain, store it in the CA certificate slot for this
         * alias as concatenated DER-encoded certificates. These can be
         * deserialized by {@link CertificateFactory#generateCertificates}.
         */
    final byte[] chainBytes;
    if (chain.length > 1) {
        /*
             * The chain is passed in as {user_cert, ca_cert_1, ca_cert_2, ...}
             * so we only need the certificates starting at index 1.
             */
        final byte[][] certsBytes = new byte[x509chain.length - 1][];
        int totalCertLength = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            try {
                certsBytes[i] = x509chain[i + 1].getEncoded();
                totalCertLength += certsBytes[i].length;
            } catch (CertificateEncodingException e) {
                throw new KeyStoreException("Can't encode Certificate #" + i, e);
            }
        }
        /*
             * Serialize this into one byte array so we can later call
             * CertificateFactory#generateCertificates to recover them.
             */
        chainBytes = new byte[totalCertLength];
        int outputOffset = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            final int certLength = certsBytes[i].length;
            System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength);
            outputOffset += certLength;
            certsBytes[i] = null;
        }
    } else {
        chainBytes = null;
    }
    /*
         * Make sure we clear out all the appropriate types before trying to
         * write.
         */
    if (shouldReplacePrivateKey) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
    } else {
        Credentials.deleteCertificateTypesForAlias(mKeyStore, alias);
    }
    final int flags = (params == null) ? 0 : params.getFlags();
    if (shouldReplacePrivateKey && !mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, keyBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put private key in keystore");
    } else if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate #1 in keystore");
    } else if (chainBytes != null && !mKeyStore.put(Credentials.CA_CERTIFICATE + alias, chainBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate chain in keystore");
    }
}
Also used : OpenSSLKeyHolder(org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate)

Aggregations

CertificateEncodingException (java.security.cert.CertificateEncodingException)210 X509Certificate (java.security.cert.X509Certificate)94 IOException (java.io.IOException)76 Certificate (java.security.cert.Certificate)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)27 KeyStoreException (java.security.KeyStoreException)19 MessageDigest (java.security.MessageDigest)19 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateException (java.security.cert.CertificateException)14 BigInteger (java.math.BigInteger)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 Bundle (android.os.Bundle)9 PublicKey (java.security.PublicKey)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 File (java.io.File)8 PrivateKey (java.security.PrivateKey)8 DEROctetString (org.bouncycastle.asn1.DEROctetString)8