Search in sources :

Example 21 with PublicKey

use of java.security.PublicKey in project android_frameworks_base by ResurrectionRemix.

the class AndroidKeyStoreCipherSpiBase method engineWrap.

@Override
protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
    if (mKey == null) {
        throw new IllegalStateException("Not initilized");
    }
    if (!isEncrypting()) {
        throw new IllegalStateException("Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
    }
    if (key == null) {
        throw new NullPointerException("key == null");
    }
    byte[] encoded = null;
    if (key instanceof SecretKey) {
        if ("RAW".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key.getAlgorithm());
                SecretKeySpec spec = (SecretKeySpec) keyFactory.getKeySpec((SecretKey) key, SecretKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PrivateKey) {
        if ("PKCS8".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PublicKey) {
        if ("X.509".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else {
        throw new InvalidKeyException("Unsupported key type: " + key.getClass().getName());
    }
    if (encoded == null) {
        throw new InvalidKeyException("Failed to wrap key because it does not export its key material");
    }
    try {
        return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
        throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 22 with PublicKey

use of java.security.PublicKey in project OpenAM by OpenRock.

the class LibSecurityTokenProvider method createKeyInfo.

/**
     * Returns the <code>KeyInfo</code> object as a Document Element.
     */
private Element createKeyInfo() throws SecurityTokenException {
    X509Certificate cert = getX509Certificate();
    Document doc = null;
    try {
        doc = XMLUtils.newDocument();
    } catch (Exception e) {
        debug.error("createKeyInfo: ", e);
        throw new SecurityTokenException(e.getMessage());
    }
    String keyNameTextString = null;
    String base64CertString = null;
    PublicKey pk = null;
    try {
        pk = cert.getPublicKey();
        keyNameTextString = cert.getSubjectDN().getName();
        base64CertString = Base64.encode(cert.getEncoded());
    } catch (Exception e) {
        debug.error("createKeyInfo: ", e);
        throw new SecurityTokenException(e.getMessage());
    }
    Element keyInfo = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, SAMLConstants.TAG_KEYINFO);
    keyInfo.setAttribute("xmlns", SAMLConstants.XMLSIG_NAMESPACE_URI);
    if ((keyInfoType != null) && (keyInfoType.equalsIgnoreCase("certificate"))) {
        //put Certificate in KeyInfo
        Element x509Data = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, SAMLConstants.TAG_X509DATA);
        Element x509Certificate = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, SAMLConstants.TAG_X509CERTIFICATE);
        Text certText = doc.createTextNode(base64CertString);
        x509Certificate.appendChild(certText);
        keyInfo.appendChild(x509Data).appendChild(x509Certificate);
    } else {
        //put public key in keyinfo
        Element keyName = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, SAMLConstants.TAG_KEYNAME);
        Text keyNameText = doc.createTextNode(keyNameTextString);
        Element keyvalue = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, SAMLConstants.TAG_KEYVALUE);
        if (pk.getAlgorithm().equals("DSA")) {
            DSAPublicKey dsakey = (DSAPublicKey) pk;
            DSAParams dsaParams = dsakey.getParams();
            BigInteger _p = dsaParams.getP();
            BigInteger _q = dsaParams.getQ();
            BigInteger _g = dsaParams.getG();
            BigInteger _y = dsakey.getY();
            Element DSAKeyValue = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "DSAKeyValue");
            Element p = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "P");
            Text value_p = doc.createTextNode(Base64.encode(_p.toByteArray()));
            p.appendChild(value_p);
            DSAKeyValue.appendChild(p);
            Element q = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "Q");
            Text value_q = doc.createTextNode(Base64.encode(_q.toByteArray()));
            q.appendChild(value_q);
            DSAKeyValue.appendChild(q);
            Element g = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "G");
            Text value_g = doc.createTextNode(Base64.encode(_g.toByteArray()));
            g.appendChild(value_g);
            DSAKeyValue.appendChild(g);
            Element y = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "Y");
            Text value_y = doc.createTextNode(Base64.encode(_y.toByteArray()));
            y.appendChild(value_y);
            DSAKeyValue.appendChild(y);
            keyvalue.appendChild(DSAKeyValue);
        } else {
            // It is RSA
            RSAPublicKey rsakey = (RSAPublicKey) pk;
            BigInteger exponent = rsakey.getPublicExponent();
            BigInteger modulus = rsakey.getModulus();
            Element RSAKeyValue = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "RSAKeyValue");
            Element modulusNode = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "Modulus");
            Element exponentNode = doc.createElementNS(SAMLConstants.XMLSIG_NAMESPACE_URI, "Exponent");
            RSAKeyValue.appendChild(modulusNode);
            RSAKeyValue.appendChild(exponentNode);
            Text modulusValue = doc.createTextNode(Base64.encode(modulus.toByteArray()));
            modulusNode.appendChild(modulusValue);
            Text exponentValue = doc.createTextNode(Base64.encode(exponent.toByteArray()));
            exponentNode.appendChild(exponentValue);
            keyvalue.appendChild(RSAKeyValue);
        }
        keyInfo.appendChild(keyName).appendChild(keyNameText);
        keyInfo.appendChild(keyvalue);
    }
    return keyInfo;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) Element(org.w3c.dom.Element) BigInteger(java.math.BigInteger) Text(org.w3c.dom.Text) DSAParams(java.security.interfaces.DSAParams) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) DSAPublicKey(java.security.interfaces.DSAPublicKey)

Example 23 with PublicKey

use of java.security.PublicKey in project OpenAM by OpenRock.

the class SecureLogHelperJSSImpl method verifySignature.

/**
     * Verifies the given signature
     * @param signedObject the signature to be verified
     * @param mac mac entry for the signature
     * @return true if signature for mac is valid
     * @throws Exception if it fails to verify signature value for mac entry
     */
public boolean verifySignature(byte[] signedObject, byte[] mac) throws Exception {
    try {
        PublicKey loggerPubKey = null;
        X509Certificate cert = cryptoMgr.findCertByNickname(loggerKey);
        loggerPubKey = cert.getPublicKey();
        Signature verifySign = Signature.getInstance(signingAlgorithm);
        verifySign.initVerify(loggerPubKey);
        verifySign.update(mac);
        return verifySign.verify(signedObject);
    } catch (Exception e) {
        Debug.error("SecureLogHelper.verifySignature() : " + " Exception : ", e);
        throw new Exception(e.getMessage());
    }
}
Also used : PublicKey(java.security.PublicKey) Signature(java.security.Signature) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

Example 24 with PublicKey

use of java.security.PublicKey in project OpenAM by OpenRock.

the class KeyUtil method getEncInfo.

/**
     * Returns the encryption information which will be used in
     * encrypting messages intended for the partner entity.
     * @param providerDescriptor <code>ProviderDescriptorType</code> for
     *     the partner entity
     * @param entityID partner entity's ID
     * @param isIDP whether partner entity's role is IDP or SP 
     * @return <code>EncInfo</code> which includes partner entity's
     * public key for wrapping the secret key, data encryption algorithm,
     * and data encryption strength 
     */
public static EncInfo getEncInfo(ProviderDescriptorType providerDescriptor, String entityID, boolean isIDP) {
    String role = (isIDP) ? "idp" : "sp";
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("KeyUtil.getEncInfo: " + "Entering... \nEntityID=" + entityID + "\nRole=" + role);
    }
    // first try to get it from cache
    String index = entityID.trim() + "|" + role;
    EncInfo encInfo = (EncInfo) encHash.get(index);
    if (encInfo != null) {
        return encInfo;
    }
    // else get it from meta
    if (providerDescriptor == null) {
        FSUtils.debug.error("KeyUtil.getEncInfo: " + "Null ProviderDescriptorType input for entityID=" + entityID + " in " + role + " role.");
        return null;
    }
    KeyDescriptorType kd = getKeyDescriptor(providerDescriptor, "encryption");
    if (kd == null) {
        FSUtils.debug.error("KeyUtil.getEncInfo: " + "No encryption KeyDescriptor for entityID=" + entityID + " in " + role + " role.");
        return null;
    }
    X509Certificate cert = getCert(kd);
    if (cert == null) {
        FSUtils.debug.error("KeyUtil.getEncInfo: " + "No encryption cert for entityID=" + entityID + " in " + role + " role.");
        return null;
    }
    String algorithm = kd.getEncryptionMethod();
    int keySize = kd.getKeySize().intValue();
    if ((algorithm == null) || (algorithm.length() == 0)) {
        algorithm = XMLCipher.AES_128;
        keySize = 128;
    }
    PublicKey pk = cert.getPublicKey();
    if (pk != null) {
        encInfo = new EncInfo(pk, algorithm, keySize);
    }
    if (encInfo != null) {
        encHash.put(index, encInfo);
    }
    return encInfo;
}
Also used : PublicKey(java.security.PublicKey) KeyDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.KeyDescriptorType) X509Certificate(java.security.cert.X509Certificate)

Example 25 with PublicKey

use of java.security.PublicKey in project OpenAM by OpenRock.

the class SAMLConfigValidator method loadKeyTable.

private Map loadKeyTable(KeyStore kStore) {
    Map<String, Object> keyTable = new HashMap<String, Object>();
    try {
        // create key to Certificate mapping
        for (Enumeration e = kStore.aliases(); e.hasMoreElements(); ) {
            String alias = (String) e.nextElement();
            Certificate cert = getCertificate(kStore, alias);
            PublicKey pk = getPublicKey(kStore, alias);
            String key = Base64.encode(pk.getEncoded());
            keyTable.put(key, cert);
        }
    } catch (Exception e) {
        Debug.getInstance(DEBUG_NAME).error("SAMLConfigValidator.loadKeyTable: " + "Exception in loading keystore", e);
    }
    return keyTable;
}
Also used : Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) PublicKey(java.security.PublicKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

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