Search in sources :

Example 46 with X509Certificate

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

the class X509CertificatePemProvider method readFrom.

@Override
public X509Certificate readFrom(Class<X509Certificate> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    try {
        String pem = IOUtils.toString(entityStream);
        X509Certificate cert = X509Util.decodePemCertificate(pem);
        return cert;
    } catch (CertificateException e) {
        throw new IOException(e);
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 47 with X509Certificate

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

the class CreateIdentity method createIdentity.

/**
	 * Entry point into the program. See class description for required properties file elements.
	 * 
	 */
public static void createIdentity() throws Exception {
    //Properties file
    // Define properties file strings
    final String OWNER_AUTH = "TpmOwnerAuth";
    final String HIS_IDENTITY_LABEL = "HisIdentityLabel";
    final String HIS_IDENTITY_INDEX = "HisIdentityIndex";
    final String HIS_IDENTITY_AUTH = "HisIdentityAuth";
    final String PRIVACY_CA_CERT = "PrivacyCaCertFile";
    final String PRIVACY_CA_URL = "PrivacyCaUrl";
    final String TRUST_STORE = "TrustStore";
    final String CLIENT_PATH = "ClientPath";
    final String EC_STORAGE = "ecStorage";
    final String EC_LOCATION = "ecLocation";
    // Instantiate variables to be set by properties file
    byte[] TpmOwnerAuth = null;
    String HisIdentityLabel = "";
    int HisIdentityIndex = 0;
    byte[] HisIdentityAuth = null;
    String PrivacyCaCertFile = "";
    String PrivacyCaUrl = "";
    String TrustStore = "";
    String ClientPath = "";
    String ecStorageFileName = "";
    String ecStorage = "";
    // Set properties file name
    String homeFolder = "";
    String tpmOwnerAuth = "";
    // Read the properties file, setting any defaults where it makes sense
    FileInputStream PropertyFile = null;
    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);
        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));
        HisIdentityLabel = HisProvisionerProperties.getProperty(HIS_IDENTITY_LABEL, "");
        HisIdentityIndex = Integer.parseInt(HisProvisionerProperties.getProperty(HIS_IDENTITY_INDEX, "0"));
        HisIdentityAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(HIS_IDENTITY_AUTH, ""));
        PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, "");
        PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, "");
        //			TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks");
        ClientPath = HisProvisionerProperties.getProperty(CLIENT_PATH, "");
        ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM");
        ecStorageFileName = HisProvisionerProperties.getProperty(EC_LOCATION, ".") + System.getProperty("file.separator") + "EC.cer";
    } catch (FileNotFoundException e) {
        // If the properties file is not found, display error
        throw new PrivacyCAException("Error finding HIS Provisioner properties file (HISprovisionier.properties); using defaults.", e);
    } catch (IOException e) {
        // If propertied file cannot be read, display error
        throw new PrivacyCAException("Error loading HIS Provisioner properties file (HISprovisionier.properties); using defaults.");
    } catch (NumberFormatException e) {
        throw new PrivacyCAException(e);
    } finally {
        if (PropertyFile != null)
            try {
                PropertyFile.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Error while closing the property file ", e);
            }
    }
    // Check to see if any of the values were not populated with acceptable values
    String errorString = "Properties file \"" + homeFolder + "hisprovisioner.properties contains errors:\n";
    boolean hasErrors = false;
    if (TpmOwnerAuth == null) {
        // ||  TpmOwnerAuth.length != 20){
        errorString += " - \"TpmOwnerAuth\" value must be set representing the TPM owner authentication\n";
        hasErrors = true;
    }
    if (HisIdentityLabel.length() == 0) {
        errorString += " - \"HisIdentityLabel\" value must be the subject name for the AIK certificate\n";
        hasErrors = true;
    }
    if (HisIdentityIndex == 0) {
        errorString += " - \"HisIdentityIndex\" value must be the index for AIK storage\n";
        hasErrors = true;
    }
    if (HisIdentityAuth == null || HisIdentityAuth.length != 20) {
        errorString += " - \"HisIdentityAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the AIK authentication\n";
        hasErrors = true;
    }
    if (PrivacyCaCertFile.length() == 0) {
        errorString += " - \"PrivacyCaCertFile\" value must be the name of the Privacy CA certificate file\n";
        hasErrors = true;
    }
    if (PrivacyCaUrl.length() == 0) {
        errorString += " - \"PrivacyCaUrl\" value must be the name of the URL of the Privacy CA web service\n";
        hasErrors = true;
    }
    //		}
    if (ClientPath.length() == 0) {
        errorString += " - \"ClientPath\" value must be the path that will be used for installing the HIS Client\n";
        hasErrors = true;
    }
    // If there were errors that prevent the rest of the class from running, display the error specifics and exit with an error code.
    if (hasErrors) {
        //			System.out.println(errorString);
        throw new PrivacyCAException(errorString);
    }
    //System.out.println("Trust store to use :" + System.getProperty("javax.net.ssl.trustStore"));
    //System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore);
    /*
                // looks like this is already being done somewhere else:
                // check if an identity already exists; if so, do not attempt to create it. if administrator wants to create a new identity, the existing identity must first be deleted from disk.  this version of trust agent supports only a single identity.
		File aikcertFile = new File(homeFolder + ClientPath + File.separator+"aikcert.cer");
                if( aikcertFile.exists() && aikcertFile.isFile() && aikcertFile.canRead() ) {
                    log.info("Identity already exists");
                    return;
                }
                */
    //Provision an identity for HIS
    log.info("Performing HIS identity provisioning...");
    FileOutputStream pcaFileOut = null;
    try {
        byte[] srkAuth = TpmUtils.hexStringToByteArray("0000000000000000000000000000000000000000");
        boolean requiresAuthSha = false;
        byte[] ownerAuthRaw = TpmOwnerAuth;
        byte[] keyAuthRaw = HisIdentityAuth;
        byte[] srkAuthRaw = srkAuth;
        if (requiresAuthSha) {
            ownerAuthRaw = TpmUtils.sha1hash(TpmOwnerAuth);
            keyAuthRaw = TpmUtils.sha1hash(HisIdentityAuth);
            srkAuthRaw = TpmUtils.sha1hash(srkAuth);
        }
        X509Certificate pcaCert = TpmUtils.certFromFile(homeFolder + PrivacyCaCertFile);
        boolean shortcut = true;
        byte[] ekCert = null;
        if (ecStorage.equalsIgnoreCase("file")) {
            File ecFile = new File(ecStorageFileName);
            FileInputStream ecFileIn = new FileInputStream(ecFile);
            ekCert = new byte[ecFileIn.available()];
            ecFileIn.read(ekCert);
            log.info("--read EC from file--");
            ecFileIn.close();
        } else {
            ekCert = TpmModule.getCredential(TpmOwnerAuth, "EC");
        }
        TpmIdentityRequest encryptedEkCert = new TpmIdentityRequest(ekCert, (RSAPublicKey) pcaCert.getPublicKey(), false);
        TpmIdentity newId = TpmModule.collateIdentityRequest(TpmOwnerAuth, HisIdentityAuth, HisIdentityLabel, new TpmPubKey((RSAPublicKey) pcaCert.getPublicKey(), 3, 1).toByteArray(), HisIdentityIndex, (X509Certificate) null, !shortcut);
        //                        HttpsURLConnection.setDefaultHostnameVerifier(new NopX509HostnameVerifier()); // XXX TODO Bug #497 need to allow caller to specify a TlsPolicy // disabled for testing issue #541
        IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl);
        byte[] encrypted1 = hisPrivacyCAWebService2.identityRequestGetChallenge(newId.getIdentityRequest(), encryptedEkCert.toByteArray());
        if (encrypted1.length == 1) {
            throw new PrivacyCAException("Identity request was rejected by Privacy CA in phase 1 of process");
        }
        //TpmKey aik = new TpmKey(newId.getAikBlob());
        //return os type. win:0; linux:1; other:-1
        int os = IdentityOS.osType();
        byte[] asym1 = new byte[256];
        System.arraycopy(encrypted1, 0, asym1, 0, asym1.length);
        byte[] sym1 = new byte[encrypted1.length - 256];
        System.arraycopy(encrypted1, 256, sym1, 0, sym1.length);
        byte[] decrypted1;
        if (os == 1) {
            //linux
            decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex);
        } else
            //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); //Comments  temporarily due to TSSCoreService.jar compiling issue 
            decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex);
        TpmIdentityRequest encryptedChallenge = new TpmIdentityRequest(decrypted1, (RSAPublicKey) pcaCert.getPublicKey(), false);
        byte[] encrypted2 = hisPrivacyCAWebService2.identityRequestSubmitResponse(encryptedChallenge.toByteArray());
        if (encrypted2.length == 1) {
            log.warning("Identity request was rejected by Privacy CA in phase 2 of process");
            throw new Exception("Identity request was rejected by Privacy CA in phase 2 of process");
        }
        byte[] asym2 = new byte[256];
        System.arraycopy(encrypted2, 0, asym2, 0, asym2.length);
        byte[] sym2 = new byte[encrypted2.length - 256];
        System.arraycopy(encrypted2, 256, sym2, 0, sym2.length);
        byte[] decrypted2;
        byte[] aikblob;
        if (os == 1) {
            //linux
            decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex);
            aikblob = newId.getAikBlob();
            writecert(homeFolder + ClientPath, decrypted2, "/aikcert.cer");
            writeFile(homeFolder + ClientPath, aikblob, "/aikblob.dat");
        } else {
            //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); 
            //decrypted2 = TpmModuleJava.ActivateIdentity(asym2, sym2, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw);//Comments  temporarily due to TSSCoreService.jar compiling issue 
            decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex);
            writecert(homeFolder + ClientPath, decrypted2, "/aikcert.cer");
        }
    } catch (Exception e) {
        throw new PrivacyCAException("FAILED", e);
    } finally {
        if (pcaFileOut != null)
            try {
                pcaFileOut.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Error while closing pcaFileOut", e);
            }
    }
    log.info("DONE");
}
Also used : IHisPrivacyCAWebService2(gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2) InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) CertificateException(javax.security.cert.CertificateException) TpmPubKey(gov.niarl.his.privacyca.TpmPubKey) FileOutputStream(java.io.FileOutputStream) File(java.io.File) TpmIdentityRequest(gov.niarl.his.privacyca.TpmIdentityRequest) TpmIdentity(gov.niarl.his.privacyca.TpmIdentity)

Example 48 with X509Certificate

use of java.security.cert.X509Certificate 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 49 with X509Certificate

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

the class HisIdentityProvisioner method main.

/**
	 * Entry point into the program. See class description for required properties file elements.
	 * 
	 */
public static void main(String[] args) {
    //Properties file
    // Define properties file strings
    final String OWNER_AUTH = "TpmOwnerAuth";
    final String HIS_IDENTITY_LABEL = "HisIdentityLabel";
    final String HIS_IDENTITY_INDEX = "HisIdentityIndex";
    final String HIS_IDENTITY_AUTH = "HisIdentityAuth";
    final String PRIVACY_CA_CERT = "PrivacyCaCertFile";
    final String PRIVACY_CA_URL = "PrivacyCaUrl";
    final String TRUST_STORE = "TrustStore";
    final String CLIENT_PATH = "ClientPath";
    // Instantiate variables to be set by properties file
    byte[] TpmOwnerAuth = null;
    String HisIdentityLabel = "";
    int HisIdentityIndex = 0;
    byte[] HisIdentityAuth = null;
    String PrivacyCaCertFile = "";
    String PrivacyCaUrl = "";
    String TrustStore = "";
    String ClientPath = "";
    // Set properties file name
    String propertiesFileName = "./OATprovisioner.properties";
    // Read the properties file, setting any defaults where it makes sense
    FileInputStream PropertyFile = null;
    try {
        PropertyFile = new FileInputStream(propertiesFileName);
        Properties HisProvisionerProperties = new Properties();
        HisProvisionerProperties.load(PropertyFile);
        TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH));
        HisIdentityLabel = HisProvisionerProperties.getProperty(HIS_IDENTITY_LABEL, "");
        HisIdentityIndex = Integer.parseInt(HisProvisionerProperties.getProperty(HIS_IDENTITY_INDEX, "0"));
        HisIdentityAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(HIS_IDENTITY_AUTH, ""));
        PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, "");
        PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, "");
        TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks");
        ClientPath = HisProvisionerProperties.getProperty(CLIENT_PATH, "");
    } catch (FileNotFoundException e) {
        // If the properties file is not found, display error
        System.out.println("Error finding HIS Provisioner properties file (HISprovisionier.properties); using defaults.");
    } catch (IOException e) {
        // If propertied file cannot be read, display error
        System.out.println("Error loading HIS Provisioner properties file (HISprovisionier.properties); using defaults.");
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } finally {
        if (PropertyFile != null)
            try {
                PropertyFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    // Check to see if any of the values were not populated with acceptable values
    String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n";
    boolean hasErrors = false;
    if (TpmOwnerAuth == null || TpmOwnerAuth.length != 20) {
        errorString += " - \"TpmOwnerAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the TPM owner authentication\n";
        hasErrors = true;
    }
    if (HisIdentityLabel.length() == 0) {
        errorString += " - \"HisIdentityLabel\" value must be the subject name for the AIK certificate\n";
        hasErrors = true;
    }
    if (HisIdentityIndex == 0) {
        errorString += " - \"HisIdentityIndex\" value must be the index for AIK storage\n";
        hasErrors = true;
    }
    if (HisIdentityAuth == null || HisIdentityAuth.length != 20) {
        errorString += " - \"HisIdentityAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the AIK authentication\n";
        hasErrors = true;
    }
    if (PrivacyCaCertFile.length() == 0) {
        errorString += " - \"PrivacyCaCertFile\" value must be the name of the Privacy CA certificate file\n";
        hasErrors = true;
    }
    if (PrivacyCaUrl.length() == 0) {
        errorString += " - \"PrivacyCaUrl\" value must be the name of the URL of the Privacy CA web service\n";
        hasErrors = true;
    }
    if (TrustStore.length() == 0) {
        errorString += " - \"TrustStore\" value must be the name of the trust store for using the registration web service\n";
        hasErrors = true;
    }
    if (ClientPath.length() == 0) {
        errorString += " - \"ClientPath\" value must be the path that will be used for installing the HIS Client\n";
        hasErrors = true;
    }
    // If there were errors that prevent the rest of the class from running, display the error specifics and exit with an error code.
    if (hasErrors) {
        System.out.println(errorString);
        System.exit(99);
        return;
    }
    System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore);
    //Provision an identity for HIS
    System.out.print("Performing HIS identity provisioning...");
    FileOutputStream pcaFileOut = null;
    try {
        byte[] srkAuth = TpmUtils.hexStringToByteArray("0000000000000000000000000000000000000000");
        boolean requiresAuthSha = false;
        byte[] ownerAuthRaw = TpmOwnerAuth;
        byte[] keyAuthRaw = HisIdentityAuth;
        byte[] srkAuthRaw = srkAuth;
        if (requiresAuthSha) {
            ownerAuthRaw = TpmUtils.sha1hash(TpmOwnerAuth);
            keyAuthRaw = TpmUtils.sha1hash(HisIdentityAuth);
            srkAuthRaw = TpmUtils.sha1hash(srkAuth);
        }
        X509Certificate pcaCert = TpmUtils.certFromFile(PrivacyCaCertFile);
        boolean shortcut = true;
        if (TpmOwnerAuth == null) {
            System.exit(99);
            return;
        }
        byte[] ekCert = TpmModule.getCredential(TpmOwnerAuth, "EC");
        TpmIdentityRequest encryptedEkCert = new TpmIdentityRequest(ekCert, (RSAPublicKey) pcaCert.getPublicKey(), false);
        if (HisIdentityAuth == null) {
            System.exit(99);
            return;
        }
        TpmIdentity newId = TpmModule.collateIdentityRequest(TpmOwnerAuth, HisIdentityAuth, HisIdentityLabel, new TpmPubKey((RSAPublicKey) pcaCert.getPublicKey(), 3, 1).toByteArray(), HisIdentityIndex, (X509Certificate) null, !shortcut);
        IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl);
        byte[] encrypted1 = hisPrivacyCAWebService2.identityRequestGetChallenge(newId.getIdentityRequest(), encryptedEkCert.toByteArray());
        if (encrypted1.length == 1) {
            System.out.println("Identity request was rejected by Privacy CA in phase 1 of process");
            System.exit(1);
            return;
        }
        TpmKey aik = new TpmKey(newId.getAikBlob());
        //return os type. win:0; linux:1; other:-1
        int os = IdentityOS.osType();
        byte[] asym1 = new byte[256];
        System.arraycopy(encrypted1, 0, asym1, 0, asym1.length);
        byte[] sym1 = new byte[encrypted1.length - 256];
        System.arraycopy(encrypted1, 256, sym1, 0, sym1.length);
        byte[] decrypted1;
        if (//linux
        os == 1)
            decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex);
        else
            //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); //Comments  temporarily due to TSSCoreService.jar compiling issue 
            decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex);
        TpmIdentityRequest encryptedChallenge = new TpmIdentityRequest(decrypted1, (RSAPublicKey) pcaCert.getPublicKey(), false);
        byte[] encrypted2 = hisPrivacyCAWebService2.identityRequestSubmitResponse(encryptedChallenge.toByteArray());
        if (encrypted2.length == 1) {
            System.out.println("Identity request was rejected by Privacy CA in phase 2 of process");
            System.exit(2);
            return;
        }
        byte[] asym2 = new byte[256];
        System.arraycopy(encrypted2, 0, asym2, 0, asym2.length);
        byte[] sym2 = new byte[encrypted2.length - 256];
        System.arraycopy(encrypted2, 256, sym2, 0, sym2.length);
        byte[] decrypted2;
        if (//linux
        os == 1)
            decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex);
        else
            //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); 
            //decrypted2 = TpmModuleJava.ActivateIdentity(asym2, sym2, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw);//Comments  temporarily due to TSSCoreService.jar compiling issue 
            decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex);
        File outPath = new File(ClientPath);
        File outFile = new File(ClientPath + "/aik.cer");
        if (!outPath.isDirectory()) {
            if (!outPath.mkdirs()) {
                System.out.println("Failed to create client installation path!");
                System.exit(5);
            }
        }
        pcaFileOut = new FileOutputStream(outFile);
        pcaFileOut.write(decrypted2);
        pcaFileOut.flush();
        pcaFileOut.close();
    } catch (Exception e) {
        System.out.println("FAILED");
        e.printStackTrace();
        System.exit(1);
    } finally {
        if (pcaFileOut != null)
            try {
                pcaFileOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    System.out.println("DONE");
    System.exit(0);
    return;
}
Also used : IHisPrivacyCAWebService2(gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 50 with X509Certificate

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

the class HisTpmProvisioner 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 EC_P12_FILE = "TpmEndorsmentP12";
    final String EC_P12_PASSWORD = "EndorsementP12Pass";
    final String EC_VALIDITY = "EcValidityDays";
    final String OWNER_AUTH = "TpmOwnerAuth";
    final String EC_STORAGE = "ecStorage";
    String TpmEndorsmentP12 = "";
    String EndorsementP12Pass = "";
    String ecStorage = "";
    String ecStorageFileName = "./EC.cer";
    int EcValidityDays = 0;
    byte[] TpmOwnerAuth = null;
    //This is for logging purpose
    String propertiesFileName = ResourceFinder.getLocation("hisprovisioner.properties");
    FileInputStream PropertyFile = null;
    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);
        TpmEndorsmentP12 = HisProvisionerProperties.getProperty(EC_P12_FILE, "");
        EndorsementP12Pass = HisProvisionerProperties.getProperty(EC_P12_PASSWORD, "");
        EcValidityDays = Integer.parseInt(HisProvisionerProperties.getProperty(EC_VALIDITY, ""));
        TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH, ""));
        ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM");
    } 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 (TpmEndorsmentP12.length() == 0) {
        errorString += " - \"TpmEndorsmentP12\" value must be the name of a valid PKCS#12 file\n";
        hasErrors = true;
    }
    if (EndorsementP12Pass.length() == 0) {
        errorString += " - \"EndorsementP12Pass\" value must be the password for the TpmEndorsementP12 file\n";
        hasErrors = true;
    }
    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 a 40 hexidecimal digit (20 byte) value representing the TPM owner auth\n";
        hasErrors = true;
    }
    if (hasErrors) {
        throw new PrivacyCAException(errorString);
    }
    //Provision the TPM
    log.info("Performing TPM provisioning...");
    try {
        //opening the keystore and getting cert
        X509Certificate cert = TpmUtils.certFromP12(homeFolder + TpmEndorsmentP12, EndorsementP12Pass);
        if (cert != null)
            TpmClient.provisionTpm(TpmOwnerAuth, TpmUtils.privKeyFromP12(homeFolder + TpmEndorsmentP12, EndorsementP12Pass), cert, EcValidityDays, ecStorage, ecStorageFileName);
        else
            log.warning("Certificate was null. Skipping provisioning of TPM. ");
    } catch (TpmModule.TpmModuleException e) {
        throw new PrivacyCAException("Caught a TPM Module exception: " + e.toString());
    } catch (Exception e) {
        throw new PrivacyCAException("FAILED", e);
    }
    log.info("DONE");
}
Also used : InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TpmModule(gov.niarl.his.privacyca.TpmModule) File(java.io.File)

Aggregations

X509Certificate (java.security.cert.X509Certificate)1706 IOException (java.io.IOException)336 CertificateException (java.security.cert.CertificateException)272 ByteArrayInputStream (java.io.ByteArrayInputStream)260 CertificateFactory (java.security.cert.CertificateFactory)251 ArrayList (java.util.ArrayList)232 Certificate (java.security.cert.Certificate)227 KeyStore (java.security.KeyStore)177 PrivateKey (java.security.PrivateKey)150 InputStream (java.io.InputStream)134 File (java.io.File)112 KeyStoreException (java.security.KeyStoreException)112 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 GeneralSecurityException (java.security.GeneralSecurityException)100 Test (org.junit.Test)90 List (java.util.List)89 PublicKey (java.security.PublicKey)88 X509TrustManager (javax.net.ssl.X509TrustManager)80 X500Principal (javax.security.auth.x500.X500Principal)76 HashSet (java.util.HashSet)64