2012-02-23 16 views
10

Tengo un problema al intentar descifrar la aserción cifrada con SAML 2.0. La biblioteca que estoy usando es OpenSAML Java libraries 2.5.2.Desencriptar la aserción cifrada utilizando SAML 2.0 en Java con OpenSAML

La afirmación de cifrado es el siguiente:

<EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> 
<enc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" 
    xmlns:enc="http://www.w3.org/2001/04/xmlenc#"> 
    <enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" /> 
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> 
    <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
     <e:EncryptionMethod 
     Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"> 
     <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> 
     </e:EncryptionMethod> 
     <KeyInfo> 
     <o:SecurityTokenReference 
      xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext- 
        1.0.xsd"> 
      <o:KeyIdentifier 
      ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security- 
         1.1#ThumbprintSHA1" 
      EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap- 
         message-security-1.0#Base64Binary"> 
      1H3mV/pJAlVZAst/Dt0rqbBd67g= 
      </o:KeyIdentifier> 
     </o:SecurityTokenReference> 
     </KeyInfo> 
     <e:CipherData> 
     <e:CipherValue> 
    ... ENCRYPTED KEY HERE ... 
     </e:CipherValue> 
     </e:CipherData> 
    </e:EncryptedKey> 
    </KeyInfo> 
    <enc:CipherData> 
    <enc:CipherValue> 
    ... ENCRYPTED ASSERTIONS HERE ... 
    </enc:CipherValue> 
    </enc:CipherData> 
</enc:EncryptedData> 
</EncryptedAssertion> 

hice convertir mi clave privada que está en formato PEM a PKCS8 formato mediante el siguiente comando openssl:

openssl pkcs8 -topk8 -nocrypt -inform PEM -in rsa_private_key.key -outform DER -out rsa_private_key.pk8 

Estoy listo para Intenta descifrar la afirmación encriptada. Aquí está mi código Java:

... 
// Load the XML file and parse it. 
File xmlFile = new File("data\\token.xml"); 
InputStream inputStream = new FileInputStream(xmlFile); 
Document document = parserPoolManager.parse(inputStream); 
Element metadataRoot = document.getDocumentElement(); 

// Unmarshall 
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); 
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); 
EncryptedAssertion encryptedAssertion = (EncryptedAssertion)unmarshaller.unmarshall(metadataRoot); 

// Load the private key file. 
File privateKeyFile = new File("data\\rsa_private_key.pk8"); 
FileInputStream inputStreamPrivateKey = new FileInputStream(privateKeyFile); 
byte[] encodedPrivateKey = new byte[(int)privateKeyFile.length()]; 
inputStreamPrivateKey.read(encodedPrivateKey); 
inputStreamPrivateKey.close(); 

// Create the private key. 
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); 
RSAPrivateKey privateKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec); 

// Create the credentials. 
BasicX509Credential decryptionCredential = new BasicX509Credential(); 
decryptionCredential.setPrivateKey(privateKey); 

// Create a decrypter. 
Decrypter decrypter = new Decrypter(null, new StaticKeyInfoCredentialResolver(decryptionCredential), new InlineEncryptedKeyResolver()); 

// Decrypt the assertion. 
Assertion decryptedAssertion; 

try 
{ 
    decryptedAssertion = decrypter.decrypt(encryptedAssertion); 
} 
... 

La ejecución de este código siempre resulta ser incapaz de descifrar la afirmación. Obtengo los siguientes errores:

5473 [main] ERROR org.opensaml.xml.encryption.Decrypter - Error decrypting encrypted key 
org.apache.xml.security.encryption.XMLEncryptionException: Key is too long for unwrapping 
Original Exception was java.security.InvalidKeyException: Key is too long for unwrapping 
    at org.apache.xml.security.encryption.XMLCipher.decryptKey(Unknown Source) 
    at org.opensaml.xml.encryption.Decrypter.decryptKey(Decrypter.java:681) 
    at org.opensaml.xml.encryption.Decrypter.decryptKey(Decrypter.java:612) 
    at org.opensaml.xml.encryption.Decrypter.decryptUsingResolvedEncryptedKey(Decrypter.java:762) 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToDOM(Decrypter.java:513) 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToList(Decrypter.java:440) 
    at org.opensaml.xml.encryption.Decrypter.decryptData(Decrypter.java:401) 
    at org.opensaml.saml2.encryption.Decrypter.decryptData(Decrypter.java:141) 
    at org.opensaml.saml2.encryption.Decrypter.decrypt(Decrypter.java:69) 
    at DecrypterTool.main(DecrypterTool.java:121) 
java.security.InvalidKeyException: Key is too long for unwrapping 
    at com.sun.crypto.provider.RSACipher.engineUnwrap(DashoA13*..) 
    at javax.crypto.Cipher.unwrap(DashoA13*..) 
    at org.apache.xml.security.encryption.XMLCipher.decryptKey(Unknown Source) 
    at org.opensaml.xml.encryption.Decrypter.decryptKey(Decrypter.java:681) 
    at org.opensaml.xml.encryption.Decrypter.decryptKey(Decrypter.java:612) 
    at org.opensaml.xml.encryption.Decrypter.decryptUsingResolvedEncryptedKey(Decrypter.java:762) 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToDOM(Decrypter.java:513) 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToList(Decrypter.java:440) 
    at org.opensaml.xml.encryption.Decrypter.decryptData(Decrypter.java:401) 
    at org.opensaml.saml2.encryption.Decrypter.decryptData(Decrypter.java:141) 
    at org.opensaml.saml2.encryption.Decrypter.decrypt(Decrypter.java:69) 
    at DecrypterTool.main(DecrypterTool.java:121) 
5477 [main] ERROR org.opensaml.xml.encryption.Decrypter - Failed to decrypt EncryptedKey, valid decryption key could not be resolved 
5477 [main] ERROR org.opensaml.xml.encryption.Decrypter - Failed to decrypt EncryptedData using either EncryptedData KeyInfoCredentialResolver or EncryptedKeyResolver + EncryptedKey KeyInfoCredentialResolver 
5478 [main] ERROR org.opensaml.saml2.encryption.Decrypter - SAML Decrypter encountered an error decrypting element content 
org.opensaml.xml.encryption.DecryptionException: Failed to decrypt EncryptedData 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToDOM(Decrypter.java:524) 
    at org.opensaml.xml.encryption.Decrypter.decryptDataToList(Decrypter.java:440) 
    at org.opensaml.xml.encryption.Decrypter.decryptData(Decrypter.java:401) 
    at org.opensaml.saml2.encryption.Decrypter.decryptData(Decrypter.java:141) 
    at org.opensaml.saml2.encryption.Decrypter.decrypt(Decrypter.java:69) 
    at DecrypterTool.main(DecrypterTool.java:121) 

Realmente no sé lo que estoy haciendo mal en este caso. Convertí mi clave privada en pkcs8, cargué mis datos de SAML XML y los desregulé en el tipo válido (EncryptedAssertion) y creé un descifrado basado en mi clave privada.

¿Es posible que esté relacionado con el formato oaep para RSA? Estoy usando la biblioteca de criptografía Java predeterminada.

Gracias!

+0

No sé su problema exacto, pero tuve golpear mi cabeza mientras que trata de [tag: saml] me encontré con gran facilidad mediante el uso de 'camel' Apache. – Shahzeb

+0

@Shahzeb Me encantaría usar algo más, pero mi cliente está usando saml y realmente no puedo cambiar eso.:( – thewalrusnp

Respuesta

17

Para aquellos de ustedes que obtendrán este problema, se relacionó con el hecho de que la extensión de criptografía Java (JCE) archivos de política de jurisdicción de fuerza ilimitada no estaba instalada y no me permitía usar el cifrado mejor que AES-128. Al reemplazar los archivos de políticas con los archivos de políticas de JCE, pude descifrar mi afirmación encriptada.

+1

¿Te molesta compartir cómo llegaste a este hallazgo? – Zoomzoom

2

De acuerdo con @thwalrusnp. Solo quería agregar la ubicación exacta desde la que puede descargar los jar de política.

encontró en la answer a Error while decrypting assertion sent from IDP

Esto sucede debido a la limitación de la fuerza de criptografía en la distribución predeterminada de Java Runtime Environment.

  1. Descargar Java Cryptography Extension (JCE) Ilimitado Fuerza Política de Competencia Archivos (for Java 7) (for Java 8)

  2. Extracto archivo zip y encontrar allí local_policy.jar y US_export_policy.jar.

  3. Reemplace su versión de JRE de estos archivos en $ JAVA_HOME/jre {version_number}/lib/security/con los descargados.

  4. Reinicia el proceso de JRE, si hay alguno en ejecución. Ahora puedes usar teclas más largas.

+0

Agregando a esto, parece que los archivos de política de fuerza ilimitada se envían por defecto con Java 9. –

Cuestiones relacionadas