Search in sources :

Example 11 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project jdk8u_jdk by JetBrains.

the class XMLCipher method encryptKey.

/**
     * Encrypts a key to an EncryptedKey structure
     *
     * @param doc the Context document that will be used to general DOM
     * @param key Key to encrypt (will use previously set KEK to
     * perform encryption
     * @param mgfAlgorithm The xenc11 MGF Algorithm to use
     * @param oaepParams The OAEPParams to use
     * @return the <code>EncryptedKey</code>
     * @throws XMLEncryptionException
     */
public EncryptedKey encryptKey(Document doc, Key key, String mgfAlgorithm, byte[] oaepParams) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting key ...");
    }
    if (null == key) {
        log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
    }
    if (cipherMode != WRAP_MODE) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    contextDocument = doc;
    byte[] encryptedBytes = null;
    Cipher c;
    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(algorithm, null);
    } else {
        c = contextCipher;
    }
    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        OAEPParameterSpec oaepParameters = constructOAEPParameters(algorithm, digestAlg, mgfAlgorithm, oaepParams);
        if (oaepParameters == null) {
            c.init(Cipher.WRAP_MODE, this.key);
        } else {
            c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
        }
        encryptedBytes = c.wrap(key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException("empty", e);
    }
    String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
        log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
    }
    CipherValue cv = ek.getCipherData().getCipherValue();
    cv.setValue(base64EncodedEncryptedOctets);
    try {
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        method.setDigestAlgorithm(digestAlg);
        method.setMGFAlgorithm(mgfAlgorithm);
        method.setOAEPparams(oaepParams);
        ek.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ek;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Cipher(javax.crypto.Cipher) URISyntaxException(java.net.URISyntaxException) InvalidKeyException(java.security.InvalidKeyException) URI(java.net.URI) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 12 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project jdk8u_jdk by JetBrains.

the class XMLCipher method constructOAEPParameters.

/**
     * Construct an OAEPParameterSpec object from the given parameters
     */
private OAEPParameterSpec constructOAEPParameters(String encryptionAlgorithm, String digestAlgorithm, String mgfAlgorithm, byte[] oaepParams) {
    if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm) || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
        String jceDigestAlgorithm = "SHA-1";
        if (digestAlgorithm != null) {
            jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm);
        }
        PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
        if (oaepParams != null) {
            pSource = new PSource.PSpecified(oaepParams);
        }
        MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
        if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
            if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) {
                mgfParameterSpec = new MGF1ParameterSpec("SHA-256");
            } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) {
                mgfParameterSpec = new MGF1ParameterSpec("SHA-384");
            } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) {
                mgfParameterSpec = new MGF1ParameterSpec("SHA-512");
            }
        }
        return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
    }
    return null;
}
Also used : PSource(javax.crypto.spec.PSource) MGF1ParameterSpec(java.security.spec.MGF1ParameterSpec) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 13 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project jdk8u_jdk by JetBrains.

the class XMLCipher method decryptKey.

/**
     * Decrypt a key from a passed in EncryptedKey structure
     *
     * @param encryptedKey Previously loaded EncryptedKey that needs
     * to be decrypted.
     * @param algorithm Algorithm for the decryption
     * @return a key corresponding to the given type
     * @throws XMLEncryptionException
     */
public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
    }
    if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm");
    }
    if (key == null) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
        }
        KeyInfo ki = encryptedKey.getKeyInfo();
        if (ki != null) {
            ki.setSecureValidation(secureValidation);
            try {
                String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
                String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
                if ("RSA".equals(keyType)) {
                    key = ki.getPrivateKey();
                } else {
                    key = ki.getSecretKey();
                }
            } catch (Exception e) {
                if (log.isLoggable(java.util.logging.Level.FINE)) {
                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
                }
            }
        }
        if (key == null) {
            log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve");
            throw new XMLEncryptionException("Unable to decrypt without a KEK");
        }
    }
    // Obtain the encrypted octets
    XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
    cipherInput.setSecureValidation(secureValidation);
    byte[] encryptedBytes = cipherInput.getBytes();
    String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "JCE Key Algorithm: " + jceKeyAlgorithm);
    }
    Cipher c;
    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(encryptedKey.getEncryptionMethod().getAlgorithm(), encryptedKey.getEncryptionMethod().getDigestAlgorithm());
    } else {
        c = contextCipher;
    }
    Key ret;
    try {
        EncryptionMethod encMethod = encryptedKey.getEncryptionMethod();
        OAEPParameterSpec oaepParameters = constructOAEPParameters(encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(), encMethod.getMGFAlgorithm(), encMethod.getOAEPparams());
        if (oaepParameters == null) {
            c.init(Cipher.UNWRAP_MODE, key);
        } else {
            c.init(Cipher.UNWRAP_MODE, key, oaepParameters);
        }
        ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (NoSuchAlgorithmException nsae) {
        throw new XMLEncryptionException("empty", nsae);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException("empty", e);
    }
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
    }
    return ret;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) URISyntaxException(java.net.URISyntaxException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Base64DecodingException(com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) InvalidCanonicalizerException(com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException) InvalidTransformException(com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException) XMLSignatureException(com.sun.org.apache.xml.internal.security.signature.XMLSignatureException) BadPaddingException(javax.crypto.BadPaddingException) KeyResolverException(com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) TransformationException(com.sun.org.apache.xml.internal.security.transforms.TransformationException) XMLSecurityException(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchProviderException(java.security.NoSuchProviderException) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec) KeyInfo(com.sun.org.apache.xml.internal.security.keys.KeyInfo) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 14 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project jdk8u_jdk by JetBrains.

the class TestOAEPWithParams method testEncryptDecrypt.

private static void testEncryptDecrypt(String hashAlg, int dataLength) throws Exception {
    System.out.println("Testing OAEP with hash " + hashAlg + ", " + dataLength + " bytes");
    Cipher c = Cipher.getInstance("RSA/ECB/OAEPwith" + hashAlg + "andMGF1Padding", cp);
    byte[] pSrc1 = { (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x02 };
    byte[] pSrc2 = { (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x02, (byte) 0x03, (byte) 0x04 };
    OAEPParameterSpec spec1 = new OAEPParameterSpec(hashAlg, "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(pSrc1));
    OAEPParameterSpec spec2 = new OAEPParameterSpec(hashAlg, "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(pSrc2));
    byte[] plainText = new byte[dataLength];
    byte[] cipherText, recovered;
    // do encryption with parameters#1
    System.out.println("Testing with user-supplied parameters...");
    c.init(Cipher.ENCRYPT_MODE, publicKey, spec1);
    cipherText = c.doFinal(plainText);
    // test#1: decrypt with parameters#1
    c.init(Cipher.DECRYPT_MODE, privateKey, spec1);
    recovered = c.doFinal(cipherText);
    if (Arrays.equals(plainText, recovered) == false) {
        throw new Exception("Decrypted data does not match");
    }
    // test#2: decrypt without parameters
    c.init(Cipher.DECRYPT_MODE, privateKey);
    try {
        recovered = c.doFinal(cipherText);
        throw new Exception("Should throw BadPaddingException");
    } catch (BadPaddingException bpe) {
    // expected
    }
    // test#3: decrypt with different parameters
    c.init(Cipher.DECRYPT_MODE, privateKey, spec2);
    try {
        recovered = c.doFinal(cipherText);
        throw new Exception("Should throw BadPaddingException");
    } catch (BadPaddingException bpe) {
    // expected
    }
    // do encryption without parameters
    System.out.println("Testing with cipher default parameters...");
    c.init(Cipher.ENCRYPT_MODE, publicKey);
    cipherText = c.doFinal(plainText);
    // test#1: decrypt with parameters got from cipher
    AlgorithmParameters params = c.getParameters();
    c.init(Cipher.DECRYPT_MODE, privateKey, params);
    recovered = c.doFinal(cipherText);
    if (Arrays.equals(plainText, recovered) == false) {
        throw new Exception("Decrypted data does not match");
    }
    // test#2: decrypt without parameters
    c.init(Cipher.DECRYPT_MODE, privateKey);
    recovered = c.doFinal(cipherText);
    if (Arrays.equals(plainText, recovered) == false) {
        throw new Exception("Decrypted data does not match");
    }
    // test#3: decrypt with different parameters
    c.init(Cipher.DECRYPT_MODE, privateKey, spec2);
    try {
        recovered = c.doFinal(cipherText);
        throw new Exception("Should throw BadPaddingException");
    } catch (BadPaddingException bpe) {
    // expected
    }
}
Also used : PSource(javax.crypto.spec.PSource) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 15 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project jdk8u_jdk by JetBrains.

the class TestOAEPPadding method main.

public static void main(String[] args) throws Exception {
    cp = Security.getProvider("SunJCE");
    System.out.println("Testing provider " + cp.getName() + "...");
    Provider kfp = Security.getProvider("SunRsaSign");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", kfp);
    kpg.initialize(2048);
    KeyPair kp = kpg.generateKeyPair();
    privateKey = (RSAPrivateKey) kp.getPrivate();
    publicKey = (RSAPublicKey) kp.getPublic();
    // Test using a spec with each digest algorithm case
    // MD5
    test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA1
    test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // For default OAEPParameterSpec case (SHA1)
    test(null);
    // SHA-224
    test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-256
    test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-384
    test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    // SHA-512
    test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT));
    test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT));
    if (failed) {
        throw new Exception("Test failed");
    }
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Provider(java.security.Provider) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Aggregations

OAEPParameterSpec (javax.crypto.spec.OAEPParameterSpec)15 PSource (javax.crypto.spec.PSource)9 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)6 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)4 InvalidKeyException (java.security.InvalidKeyException)4 MGF1ParameterSpec (java.security.spec.MGF1ParameterSpec)4 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)3 URISyntaxException (java.net.URISyntaxException)2 InvalidParameterException (java.security.InvalidParameterException)2 SecureRandom (java.security.SecureRandom)2 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)2 RSAPublicKey (java.security.interfaces.RSAPublicKey)2 InvalidParameterSpecException (java.security.spec.InvalidParameterSpecException)2 Cipher (javax.crypto.Cipher)2 CipherParameters (org.bouncycastle.crypto.CipherParameters)2 Digest (org.bouncycastle.crypto.Digest)2 OAEPEncoding (org.bouncycastle.crypto.encodings.OAEPEncoding)2 RSABlindedEngine (org.bouncycastle.crypto.engines.RSABlindedEngine)2 ParametersWithRandom (org.bouncycastle.crypto.params.ParametersWithRandom)2 InvalidCanonicalizerException (com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException)1