Search in sources :

Example 1 with PublicKey

use of java.security.PublicKey in project OpenAttestation by OpenAttestation.

the class X509Util method decodeDerPublicKey.

public static PublicKey decodeDerPublicKey(byte[] publicKeyBytes) throws CryptographyException {
    try {
        // throws NoSuchAlgorithmException
        KeyFactory factory = KeyFactory.getInstance("RSA");
        // throws InvalidKeySpecException
        PublicKey publicKey = factory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        return publicKey;
    } catch (Exception e) {
        throw new CryptographyException(e);
    }
}
Also used : PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 2 with PublicKey

use of java.security.PublicKey in project OpenAttestation by OpenAttestation.

the class CitrixHostAgent method getAik.

@Override
public PublicKey getAik() {
    PublicKey pk = null;
    try {
        String crt = client.getAIKCertificate();
        log.debug(" crt == " + crt);
        pk = X509Util.decodePemPublicKey(crt);
    //client.getAIKCertificate().replace(X509Util.BEGIN_PUBLIC_KEY, "").replace(X509Util.END_PUBLIC_KEY, "").replaceAll("\n","").replaceAll("\r","");  
    } catch (Exception ex) {
        log.debug("getAik caught: " + ex.getMessage());
    }
    return pk;
}
Also used : PublicKey(java.security.PublicKey) XmlRpcException(org.apache.xmlrpc.XmlRpcException) XMLStreamException(javax.xml.stream.XMLStreamException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 3 with PublicKey

use of java.security.PublicKey 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 4 with PublicKey

use of java.security.PublicKey in project Openfire by igniterealtime.

the class CertificateManager method validateReply.

/**
     * Validates chain in certification reply, and returns the ordered
     * elements of the chain (with user certificate first, and root
     * certificate last in the array).
     *
     * @param alias the alias name
     * @param userCert the user certificate of the alias
     * @param certs the chain provided in the reply
     */
private static List<X509Certificate> validateReply(KeyStore keyStore, KeyStore trustStore, String alias, X509Certificate userCert, Collection<X509Certificate> certs) throws Exception {
    List<X509Certificate> replyCerts = new ArrayList<>(certs);
    // order the certs in the reply (bottom-up).
    int i;
    X509Certificate tmpCert;
    if (userCert != null) {
        PublicKey userPubKey = userCert.getPublicKey();
        for (i = 0; i < replyCerts.size(); i++) {
            if (userPubKey.equals(replyCerts.get(i).getPublicKey())) {
                break;
            }
        }
        if (i == replyCerts.size()) {
            throw new Exception("Certificate reply does not contain public key for <alias>: " + alias);
        }
        tmpCert = replyCerts.get(0);
        replyCerts.set(0, replyCerts.get(i));
        replyCerts.set(i, tmpCert);
    }
    Principal issuer = replyCerts.get(0).getIssuerDN();
    for (i = 1; i < replyCerts.size() - 1; i++) {
        // find a cert in the reply whose "subject" is the same as the
        // given "issuer"
        int j;
        for (j = i; j < replyCerts.size(); j++) {
            Principal subject = replyCerts.get(j).getSubjectDN();
            if (subject.equals(issuer)) {
                tmpCert = replyCerts.get(i);
                replyCerts.set(i, replyCerts.get(j));
                replyCerts.set(j, tmpCert);
                issuer = replyCerts.get(i).getIssuerDN();
                break;
            }
        }
        if (j == replyCerts.size()) {
            throw new Exception("Incomplete certificate chain in reply");
        }
    }
    // now verify each cert in the ordered chain
    for (i = 0; i < replyCerts.size() - 1; i++) {
        PublicKey pubKey = replyCerts.get(i + 1).getPublicKey();
        try {
            replyCerts.get(i).verify(pubKey);
        } catch (Exception e) {
            throw new Exception("Certificate chain in reply does not verify: " + e.getMessage());
        }
    }
    // do we trust the (root) cert at the top?
    X509Certificate topCert = replyCerts.get(replyCerts.size() - 1);
    boolean foundInKeyStore = keyStore.getCertificateAlias(topCert) != null;
    boolean foundInCAStore = trustStore.getCertificateAlias(topCert) != null;
    if (!foundInKeyStore && !foundInCAStore) {
        boolean verified = false;
        X509Certificate rootCert = null;
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String name = aliases.nextElement();
            rootCert = (X509Certificate) trustStore.getCertificate(name);
            if (rootCert != null) {
                try {
                    topCert.verify(rootCert.getPublicKey());
                    verified = true;
                    break;
                } catch (Exception e) {
                // Ignore
                }
            }
        }
        if (!verified) {
            return null;
        } else {
            // Check if the cert is a self-signed cert
            if (!topCert.getSubjectDN().equals(topCert.getIssuerDN())) {
                // append the (self-signed) root CA cert to the chain
                replyCerts.add(rootCert);
            }
        }
    }
    return replyCerts;
}
Also used : PublicKey(java.security.PublicKey) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) Principal(java.security.Principal)

Example 5 with PublicKey

use of java.security.PublicKey in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Aggregations

PublicKey (java.security.PublicKey)1113 PrivateKey (java.security.PrivateKey)278 KeyFactory (java.security.KeyFactory)184 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)170 KeyPair (java.security.KeyPair)167 X509Certificate (java.security.cert.X509Certificate)165 IOException (java.io.IOException)151 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)134 RSAPublicKey (java.security.interfaces.RSAPublicKey)123 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)110 Signature (java.security.Signature)108 InvalidKeyException (java.security.InvalidKeyException)96 ArraySet (android.util.ArraySet)94 Test (org.junit.Test)92 ByteArrayInputStream (java.io.ByteArrayInputStream)77 BigInteger (java.math.BigInteger)75 CertificateException (java.security.cert.CertificateException)71 Cipher (javax.crypto.Cipher)68 KeyPairGenerator (java.security.KeyPairGenerator)65 SignatureException (java.security.SignatureException)65