Encrypt a XML file with XmlCipher (RSA)

2020-06-06 05:08发布

问题:

I just need to encrypt some XML elements with a public key. I successfully can use this code with a simetric algorithm (XMLCipher.AES_128), but failed when try use XMLCipher.RSA_v1dot5.

That is the code:

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.xml.security.encryption.XMLCipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlEncryption {

private static final String MENSAGEM_ENTIDADE_1 = "mensagem1";
private static final String MENSAGEM_ENTIDADE_2 = "mensagem2";

public static void main(String[] args) throws Exception {
    /*
     * Encrypt a file with 2 diferent assimetric keys
     */

    // parse file into document
    // Document document = EncryptToolExtended.parseFile("teste.xml");
    Document document = EncryptToolExtended.parseFile("teste.xml");

    // generate the keys
    KeyPair entity1KeyPair = EncryptToolExtended.GenerateAssymmetricKey();
    //KeyPair entity2KeyPair = EncryptToolExtended.GenerateAssymmetricKey();

    // specify the element to encrypt
    Element rootElement = document.getDocumentElement();
    Element mensagem1ToEncrypt = rootElement;
    Element mensagem2ToEncrypt = rootElement;

    mensagem1ToEncrypt = (Element) rootElement.getElementsByTagName(
            MENSAGEM_ENTIDADE_1).item(0);

    mensagem2ToEncrypt = (Element) rootElement.getElementsByTagName(
            MENSAGEM_ENTIDADE_2).item(0);

    if (mensagem1ToEncrypt == null || mensagem2ToEncrypt == null) {
        System.err.println("Unable to find element: " + MENSAGEM_ENTIDADE_1
                + " or " + MENSAGEM_ENTIDADE_2);
        System.exit(1);
    }

    // initialize cipher
    Security.addProvider(new BouncyCastleProvider());
    XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
    xmlCipher.init(XMLCipher.ENCRYPT_MODE, entity1KeyPair.getPublic());

    // add key info to encrypted data element
    // EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
    // KeyInfo keyInfo = new KeyInfo(document);
    // keyInfo.add(entity1KeyPair.getPublic());
    // encryptedDataElement.setKeyInfo(keyInfo);

    // do the actual encryption
    boolean encryptContentsOnly = true;
    xmlCipher.doFinal(document, mensagem1ToEncrypt);
    xmlCipher.doFinal(document, mensagem1ToEncrypt, encryptContentsOnly);

    // write the results to a file
    // EncryptToolExtended.writeEncryptedDocToFile(document, "encc.xml");

}

public static Document parseFile(String fileName) throws Exception {
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory
            .newInstance();
    dbf.setNamespaceAware(true);
    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(fileName);

    return document;
}

public static KeyPair GenerateAssymmetricKey() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    return keyGen.genKeyPair();
}
}

Exception:

java.lang.IllegalArgumentException: unknown parameter type.
at org.bouncycastle.jce.provider.JCERSACipher.engineInit(Unknown Source)
at javax.crypto.Cipher.init(Cipher.java:1346)
at javax.crypto.Cipher.init(Cipher.java:1282)
at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1184)
at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1136)
at org.apache.xml.security.encryption.XMLCipher.encryptElement(XMLCipher.java:869)
at org.apache.xml.security.encryption.XMLCipher.doFinal(XMLCipher.java:987)
at XmlEncryption.main(XmlEncryption.java:84)

Any tips?

Thanks