Search in sources :

Example 51 with Key

use of java.security.Key in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method testKeyStore_GetKey_NoPassword_Unencrypted_Success.

public void testKeyStore_GetKey_NoPassword_Unencrypted_Success() throws Exception {
    mKeyStore.load(null, null);
    assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1, FAKE_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
    assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_USER_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
    assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
    Key key = mKeyStore.getKey(TEST_ALIAS_1, null);
    assertNotNull("Key should exist", key);
    assertTrue("Should be a RSAPrivateKey", key instanceof RSAPrivateKey);
    RSAPrivateKey actualKey = (RSAPrivateKey) key;
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
    assertEquals("Inserted key should be same as retrieved key", ((RSAPrivateKey) expectedKey).getModulus(), actualKey.getModulus());
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) KeyFactory(java.security.KeyFactory)

Example 52 with Key

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

the class AMEncryptionProvider method decryptAndReplace.

/**
     * Decrypts an XML Document that contains encrypted data.
     * @param encryptedDoc XML Document with encrypted data.
     * @param privKey Key Encryption Key used for encryption.
     * @return org.w3c.dom.Document Decrypted XML Document.
     */
public Document decryptAndReplace(Document encryptedDoc, java.security.Key privKey) throws EncryptionException {
    EncryptionUtils.debug.message("************IN DECRYPT *************");
    if (encryptedDoc == null) {
        throw new EncryptionException(EncryptionUtils.bundle.getString("null encrypted doc"));
    }
    if (EncryptionUtils.debug.messageEnabled()) {
        EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: input encrypted DOC = " + XMLUtils.print(encryptedDoc));
    }
    Key encryptionKey = null;
    Document decryptedDoc = null;
    EncryptedKey encryptedKey = null;
    Element encryptedElementNext = null;
    XMLCipher cipher = null;
    NodeList nodes = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.ENC_XML_NS, "EncryptedData");
    int length = nodes.getLength();
    if (nodes == null || length == 0) {
        return encryptedDoc;
    }
    /**
         * Check for the encrypted key after the encrypted data.
         * if found, use that symmetric key for the decryption., otherwise
         * check if there's one in the encrypted data.
         */
    Element encryptedElem = (Element) encryptedDoc.getElementsByTagNameNS(EncryptionConstants.ENC_XML_NS, "EncryptedKey").item(0);
    try {
        cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, null);
    } catch (Exception xe) {
        EncryptionUtils.debug.error("AMEncryptionProvider.decrypt" + "AndReplace: XML Decryption error for XMLCipher init :", xe);
        throw new EncryptionException(xe);
    }
    int i = 0;
    Element encryptedElement = (Element) nodes.item(i);
    while (i < length) {
        try {
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: encrypted element (" + i + ") = " + XMLUtils.print(encryptedElement));
            }
            EncryptedData encryptedData = cipher.loadEncryptedData(encryptedDoc, encryptedElement);
            if (encryptedKey == null) {
                encryptedKey = cipher.loadEncryptedKey(encryptedDoc, encryptedElem);
                if (encryptedKey == null) {
                    encryptedKey = encryptedData.getKeyInfo().itemEncryptedKey(0);
                }
            }
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: Encrypted key = " + toString(cipher.martial(encryptedDoc, encryptedKey)));
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: Encrypted Data (" + i + ") = " + toString(cipher.martial(encryptedDoc, encryptedData)));
            }
            if (encryptedKey != null) {
                XMLCipher keyCipher = XMLCipher.getInstance();
                if (privKey == null) {
                    privKey = getPrivateKey(encryptedKey.getKeyInfo());
                }
                keyCipher.init(XMLCipher.UNWRAP_MODE, privKey);
                encryptionKey = keyCipher.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
            }
            cipher = XMLCipher.getInstance();
            cipher.init(XMLCipher.DECRYPT_MODE, encryptionKey);
            i = i + 1;
            if (i < length) {
                encryptedElementNext = (Element) nodes.item(i);
            }
            decryptedDoc = cipher.doFinal(encryptedDoc, encryptedElement);
            encryptedElement = encryptedElementNext;
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: decryptedDoc (" + (i - 1) + ") = " + XMLUtils.print(decryptedDoc));
            }
        } catch (Exception xe) {
            EncryptionUtils.debug.error("AMEncryptionProvider.decrypt" + "AndReplace: XML Decryption error.", xe);
            throw new EncryptionException(xe);
        }
    }
    if (EncryptionUtils.debug.messageEnabled()) {
        EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: FINAL decryptedDoc = " + XMLUtils.print(decryptedDoc));
    }
    return decryptedDoc;
}
Also used : EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 53 with Key

use of java.security.Key in project XobotOS by xamarin.

the class JDKKeyStore method loadStore.

protected void loadStore(InputStream in) throws IOException {
    DataInputStream dIn = new DataInputStream(in);
    int type = dIn.read();
    while (type > NULL) {
        String alias = dIn.readUTF();
        Date date = new Date(dIn.readLong());
        int chainLength = dIn.readInt();
        Certificate[] chain = null;
        if (chainLength != 0) {
            chain = new Certificate[chainLength];
            for (int i = 0; i != chainLength; i++) {
                chain[i] = decodeCertificate(dIn);
            }
        }
        switch(type) {
            case CERTIFICATE:
                Certificate cert = decodeCertificate(dIn);
                table.put(alias, new StoreEntry(alias, date, CERTIFICATE, cert));
                break;
            case KEY:
                Key key = decodeKey(dIn);
                table.put(alias, new StoreEntry(alias, date, KEY, key, chain));
                break;
            case SECRET:
            case SEALED:
                byte[] b = new byte[dIn.readInt()];
                dIn.readFully(b);
                table.put(alias, new StoreEntry(alias, date, type, b, chain));
                break;
            default:
                throw new RuntimeException("Unknown object type in store.");
        }
        type = dIn.read();
    }
}
Also used : DataInputStream(java.io.DataInputStream) Date(java.util.Date) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Certificate(java.security.cert.Certificate)

Example 54 with Key

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

the class FMEncProvider method decrypt.

@Override
public Element decrypt(String xmlString, Set<PrivateKey> privateKeys) throws SAML2Exception {
    String classMethod = "FMEncProvider.decrypt: ";
    if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message(classMethod + "Entering ...");
    }
    if (StringUtils.isEmpty(xmlString) || CollectionUtils.isEmpty(privateKeys)) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
    if (doc == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
    }
    Element rootElement = doc.getDocumentElement();
    if (rootElement == null) {
        SAML2SDKUtils.debug.error(classMethod + "Empty document.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("emptyDoc"));
    }
    Element firstChild = getNextElementNode(rootElement.getFirstChild());
    if (firstChild == null) {
        SAML2SDKUtils.debug.error(classMethod + "Missing the EncryptedData element.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementEncryptedData"));
    }
    Element secondChild = getNextElementNode(firstChild.getNextSibling());
    if (secondChild == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message(classMethod + "looking for encrytion key inside first child.");
        }
        NodeList nl = firstChild.getElementsByTagNameNS(SAML2Constants.NS_XMLENC, "EncryptedKey");
        if ((nl == null) || (nl.getLength() == 0)) {
            SAML2SDKUtils.debug.error(classMethod + "Missing the EncryptedKey element.");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementEncryptedKey"));
        } else {
            // use the first EncryptedKey found
            secondChild = (Element) nl.item(0);
        }
    }
    XMLCipher cipher = null;
    try {
        cipher = XMLCipher.getInstance();
    } catch (XMLEncryptionException xe1) {
        SAML2SDKUtils.debug.error(classMethod + "Unable to get a cipher instance.", xe1);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
    }
    try {
        cipher.init(XMLCipher.DECRYPT_MODE, null);
    } catch (XMLEncryptionException xe2) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to initialize cipher for decryption mode", xe2);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedInitCipherForDecrypt"));
    }
    EncryptedData encryptedData = null;
    try {
        encryptedData = cipher.loadEncryptedData(doc, firstChild);
    } catch (XMLEncryptionException xe3) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to load encrypted data", xe3);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedLoadingEncryptedData"));
    }
    EncryptedKey encryptedKey = null;
    try {
        encryptedKey = cipher.loadEncryptedKey(doc, secondChild);
    } catch (XMLEncryptionException xe4) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to load encrypted key", xe4);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedLoadingEncryptedKey"));
    }
    Document decryptedDoc = null;
    if (encryptedKey != null && encryptedData != null) {
        XMLCipher keyCipher = null;
        try {
            keyCipher = XMLCipher.getInstance();
        } catch (XMLEncryptionException xe5) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to get a cipher instance " + "for decrypting secret key.", xe5);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
        }
        Key encryptionKey = getEncryptionKey(keyCipher, privateKeys, encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
        cipher = null;
        try {
            cipher = XMLCipher.getInstance();
        } catch (XMLEncryptionException xe8) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to get cipher instance for " + "final data decryption.", xe8);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
        }
        try {
            cipher.init(XMLCipher.DECRYPT_MODE, encryptionKey);
        } catch (XMLEncryptionException xe9) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to initialize cipher with secret key.", xe9);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedInitCipherForDecrypt"));
        }
        try {
            decryptedDoc = cipher.doFinal(doc, firstChild);
        } catch (Exception e) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to decrypt data.", e);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedDecryptingData"));
        }
    }
    Element root = decryptedDoc.getDocumentElement();
    Element child = getNextElementNode(root.getFirstChild());
    if (child == null) {
        SAML2SDKUtils.debug.error(classMethod + "decrypted document contains empty element.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedDecryptingData"));
    }
    root.removeChild(child);
    decryptedDoc.replaceChild(child, root);
    return decryptedDoc.getDocumentElement();
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException)

Example 55 with Key

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

the class FMEncProvider method getEncryptionKey.

private Key getEncryptionKey(XMLCipher cipher, Set<PrivateKey> privateKeys, EncryptedKey encryptedKey, String algorithm) throws SAML2Exception {
    final String classMethod = "FMEncProvider.getEncryptionKey";
    String firstErrorCode = null;
    for (Key privateKey : privateKeys) {
        try {
            cipher.init(XMLCipher.UNWRAP_MODE, privateKey);
        } catch (XMLEncryptionException xee) {
            SAML2SDKUtils.debug.warning(classMethod + "Failed to initialize cipher in unwrap mode with private key", xee);
            if (firstErrorCode == null) {
                firstErrorCode = "noCipherForUnwrap";
            }
            continue;
        }
        try {
            return cipher.decryptKey(encryptedKey, algorithm);
        } catch (XMLEncryptionException xee) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to decrypt the secret key", xee);
            if (firstErrorCode == null) {
                firstErrorCode = "failedDecryptingSecretKey";
            }
        }
    }
    throw new SAML2Exception(SAML2SDKUtils.bundle.getString(firstErrorCode));
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21