Search in sources :

Example 71 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project santuario-java by apache.

the class XMLEncryptedKeyInputHandler method handle.

public void handle(final InputProcessorChain inputProcessorChain, final EncryptedKeyType encryptedKeyType, final XMLSecEvent responsibleXMLSecStartXMLEvent, final XMLSecurityProperties securityProperties) throws XMLSecurityException {
    if (encryptedKeyType.getEncryptionMethod() == null) {
        throw new XMLSecurityException("stax.encryption.noEncAlgo");
    }
    if (encryptedKeyType.getId() == null) {
        encryptedKeyType.setId(IDGenerator.generateID(null));
    }
    final InboundSecurityContext inboundSecurityContext = inputProcessorChain.getSecurityContext();
    final SecurityTokenProvider<InboundSecurityToken> securityTokenProvider = new SecurityTokenProvider<InboundSecurityToken>() {

        private AbstractInboundSecurityToken securityToken;

        @Override
        public InboundSecurityToken getSecurityToken() throws XMLSecurityException {
            if (this.securityToken != null) {
                return this.securityToken;
            }
            this.securityToken = new AbstractInboundSecurityToken(inboundSecurityContext, encryptedKeyType.getId(), SecurityTokenConstants.KeyIdentifier_EncryptedKey, true) {

                private byte[] decryptedKey;

                @Override
                public Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage, String correlationID) throws XMLSecurityException {
                    Key key = getSecretKey().get(algorithmURI);
                    if (key != null) {
                        return key;
                    }
                    String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
                    key = new SecretKeySpec(getSecret(this, correlationID, algorithmURI), algoFamily);
                    setSecretKey(algorithmURI, key);
                    return key;
                }

                @Override
                public InboundSecurityToken getKeyWrappingToken() throws XMLSecurityException {
                    return getWrappingSecurityToken(this);
                }

                @Override
                public SecurityTokenConstants.TokenType getTokenType() {
                    return SecurityTokenConstants.EncryptedKeyToken;
                }

                private InboundSecurityToken wrappingSecurityToken;

                private InboundSecurityToken getWrappingSecurityToken(InboundSecurityToken wrappedSecurityToken) throws XMLSecurityException {
                    if (wrappingSecurityToken != null) {
                        return this.wrappingSecurityToken;
                    }
                    KeyInfoType keyInfoType = encryptedKeyType.getKeyInfo();
                    this.wrappingSecurityToken = SecurityTokenFactory.getInstance().getSecurityToken(keyInfoType, SecurityTokenConstants.KeyUsage_Decryption, securityProperties, inboundSecurityContext);
                    this.wrappingSecurityToken.addWrappedToken(wrappedSecurityToken);
                    return this.wrappingSecurityToken;
                }

                private byte[] getSecret(InboundSecurityToken wrappedSecurityToken, String correlationID, String symmetricAlgorithmURI) throws XMLSecurityException {
                    if (this.decryptedKey != null) {
                        return this.decryptedKey;
                    }
                    String algorithmURI = encryptedKeyType.getEncryptionMethod().getAlgorithm();
                    if (algorithmURI == null) {
                        throw new XMLSecurityException("stax.encryption.noEncAlgo");
                    }
                    String jceName = JCEAlgorithmMapper.translateURItoJCEID(algorithmURI);
                    String jceProvider = JCEAlgorithmMapper.getJCEProviderFromURI(algorithmURI);
                    if (jceName == null) {
                        throw new XMLSecurityException("algorithms.NoSuchMap", new Object[] { algorithmURI });
                    }
                    final InboundSecurityToken wrappingSecurityToken = getWrappingSecurityToken(wrappedSecurityToken);
                    Cipher cipher;
                    try {
                        XMLSecurityConstants.AlgorithmUsage algorithmUsage;
                        if (wrappingSecurityToken.isAsymmetric()) {
                            algorithmUsage = XMLSecurityConstants.Asym_Key_Wrap;
                        } else {
                            algorithmUsage = XMLSecurityConstants.Sym_Key_Wrap;
                        }
                        if (jceProvider == null) {
                            cipher = Cipher.getInstance(jceName);
                        } else {
                            cipher = Cipher.getInstance(jceName, jceProvider);
                        }
                        if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(algorithmURI) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(algorithmURI)) {
                            final DigestMethodType digestMethodType = XMLSecurityUtils.getQNameType(encryptedKeyType.getEncryptionMethod().getContent(), XMLSecurityConstants.TAG_dsig_DigestMethod);
                            String jceDigestAlgorithm = "SHA-1";
                            if (digestMethodType != null) {
                                AlgorithmSuiteSecurityEvent algorithmSuiteSecurityEvent = new AlgorithmSuiteSecurityEvent();
                                algorithmSuiteSecurityEvent.setAlgorithmURI(digestMethodType.getAlgorithm());
                                algorithmSuiteSecurityEvent.setAlgorithmUsage(XMLSecurityConstants.EncDig);
                                algorithmSuiteSecurityEvent.setCorrelationID(correlationID);
                                inboundSecurityContext.registerSecurityEvent(algorithmSuiteSecurityEvent);
                                jceDigestAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(digestMethodType.getAlgorithm());
                            }
                            PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
                            final byte[] oaepParams = XMLSecurityUtils.getQNameType(encryptedKeyType.getEncryptionMethod().getContent(), XMLSecurityConstants.TAG_xenc_OAEPparams);
                            if (oaepParams != null) {
                                pSource = new PSource.PSpecified(oaepParams);
                            }
                            MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
                            final MGFType mgfType = XMLSecurityUtils.getQNameType(encryptedKeyType.getEncryptionMethod().getContent(), XMLSecurityConstants.TAG_xenc11_MGF);
                            if (mgfType != null) {
                                String jceMGFAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(mgfType.getAlgorithm());
                                mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm);
                            }
                            OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
                            cipher.init(Cipher.UNWRAP_MODE, wrappingSecurityToken.getSecretKey(algorithmURI, algorithmUsage, correlationID), oaepParameterSpec);
                        } else {
                            cipher.init(Cipher.UNWRAP_MODE, wrappingSecurityToken.getSecretKey(algorithmURI, algorithmUsage, correlationID));
                        }
                        if (encryptedKeyType.getCipherData() == null || encryptedKeyType.getCipherData().getCipherValue() == null) {
                            throw new XMLSecurityException("stax.encryption.noCipherValue");
                        }
                    } catch (NoSuchPaddingException e) {
                        throw new XMLSecurityException(e);
                    } catch (NoSuchAlgorithmException e) {
                        throw new XMLSecurityException(e);
                    } catch (InvalidAlgorithmParameterException e) {
                        throw new XMLSecurityException(e);
                    } catch (InvalidKeyException e) {
                        throw new XMLSecurityException(e);
                    } catch (NoSuchProviderException e) {
                        throw new XMLSecurityException(e);
                    }
                    byte[] sha1Bytes = generateDigest(encryptedKeyType.getCipherData().getCipherValue());
                    String sha1Identifier = Base64.getMimeEncoder().encodeToString(sha1Bytes);
                    super.setSha1Identifier(sha1Identifier);
                    try {
                        Key key = cipher.unwrap(encryptedKeyType.getCipherData().getCipherValue(), jceName, Cipher.SECRET_KEY);
                        return this.decryptedKey = key.getEncoded();
                    } catch (IllegalStateException e) {
                        throw new XMLSecurityException(e);
                    } catch (Exception e) {
                        LOG.warn("Unwrapping of the encrypted key failed with error: " + e.getMessage() + ". " + "Generating a faked one to mitigate timing attacks.");
                        int keyLength = JCEAlgorithmMapper.getKeyLengthFromURI(symmetricAlgorithmURI);
                        this.decryptedKey = XMLSecurityConstants.generateBytes(keyLength / 8);
                        return this.decryptedKey;
                    }
                }
            };
            this.securityToken.setElementPath(responsibleXMLSecStartXMLEvent.getElementPath());
            this.securityToken.setXMLSecEvent(responsibleXMLSecStartXMLEvent);
            return this.securityToken;
        }

        @Override
        public String getId() {
            return encryptedKeyType.getId();
        }
    };
    // register the key token for decryption:
    inboundSecurityContext.registerSecurityTokenProvider(encryptedKeyType.getId(), securityTokenProvider);
    // fire a tokenSecurityEvent
    EncryptedKeyTokenSecurityEvent tokenSecurityEvent = new EncryptedKeyTokenSecurityEvent();
    tokenSecurityEvent.setSecurityToken(securityTokenProvider.getSecurityToken());
    tokenSecurityEvent.setCorrelationID(encryptedKeyType.getId());
    inboundSecurityContext.registerSecurityEvent(tokenSecurityEvent);
    // if this EncryptedKey structure contains a reference list, delegate it to a subclass
    if (encryptedKeyType.getReferenceList() != null) {
        handleReferenceList(inputProcessorChain, encryptedKeyType, securityProperties);
    }
}
Also used : AlgorithmSuiteSecurityEvent(org.apache.xml.security.stax.securityEvent.AlgorithmSuiteSecurityEvent) EncryptedKeyTokenSecurityEvent(org.apache.xml.security.stax.securityEvent.EncryptedKeyTokenSecurityEvent) SecretKeySpec(javax.crypto.spec.SecretKeySpec) AbstractInboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) DigestMethodType(org.apache.xml.security.binding.xmldsig.DigestMethodType) MGFType(org.apache.xml.security.binding.xmlenc11.MGFType) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) KeyInfoType(org.apache.xml.security.binding.xmldsig.KeyInfoType) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec) AbstractInboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken) InboundSecurityToken(org.apache.xml.security.stax.securityToken.InboundSecurityToken) Cipher(javax.crypto.Cipher) SecurityTokenProvider(org.apache.xml.security.stax.securityToken.SecurityTokenProvider) MGF1ParameterSpec(java.security.spec.MGF1ParameterSpec)

Example 72 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project santuario-java by apache.

the class KeyResolverTest method testResolvePrivateKey.

/**
 * Encrypt some data, embedded the data encryption key
 * in the message using the key transport algorithm rsa-1_5.
 * Decrypt the data by resolving the Key Encryption Key.
 * This test verifies if a KeyResolver can return a PrivateKey.
 */
@org.junit.Test
public void testResolvePrivateKey() throws Exception {
    // See if AES-128 is available...
    String algorithmId = JCEMapper.translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
    boolean haveAES = false;
    if (algorithmId != null) {
        try {
            if (Cipher.getInstance(algorithmId) != null) {
                haveAES = true;
            }
        } catch (NoSuchAlgorithmException nsae) {
        // 
        } catch (NoSuchPaddingException nspe) {
        // 
        }
    }
    if (!haveAES) {
        return;
    }
    // Create a sample XML document
    Document document = XMLUtils.createDocumentBuilder(false).newDocument();
    Element rootElement = document.createElement("root");
    document.appendChild(rootElement);
    Element elem = document.createElement("elem");
    Text text = document.createTextNode("text");
    elem.appendChild(text);
    rootElement.appendChild(elem);
    // Create a data encryption key
    byte[] keyBytes = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 };
    SecretKeySpec dataEncryptKey = new SecretKeySpec(keyBytes, "AES");
    // Create public and private keys
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("8710a2bcb2f3fdac177f0ae0461c2dd0ebf72e0d88a5400583a7d8bdabd6" + "ae009d30cfdf6acb5b6a64cdc730bc630a39d946d08babffe62ea20a87e37c93b3b0e8a8e576045b" + "bddfbde83ca9bfa180fe6a5f5eee60661936d728314e809201ef52cd71d9fa3c8ce83f9d30ab5e08" + "1539219e7e45dd6a60be65ac95d2049b8f21", 16), new BigInteger("10001", 16));
    RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger("8710a2bcb2f3fdac177f0ae0461c2dd0ebf72e0d88a5400583a7d8bdabd" + "6ae009d30cfdf6acb5b6a64cdc730bc630a39d946d08babffe62ea20a87e37c93b3b0e8a8e576045" + "bbddfbde83ca9bfa180fe6a5f5eee60661936d728314e809201ef52cd71d9fa3c8ce83f9d30ab5e0" + "81539219e7e45dd6a60be65ac95d2049b8f21", 16), new BigInteger("20c39e569c2aa80cc91e5e6b0d56e49e5bbf78827bf56a546c1d996c597" + "5187cb9a50fa828e5efe51d52f5d112c20bc700b836facadca6e0051afcdfe866841e37d207c0295" + "36ff8674b301e2198b2c56abb0a0313f8ff84c1fcd6fa541aa6e5d9c018fab4784d2940def5dc709" + "ddc714d73b6c23b5d178eaa5933577b8e8ae9", 16));
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);
    // Encrypt the data encryption key with the key encryption key
    XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
    keyCipher.init(XMLCipher.WRAP_MODE, pubKey);
    EncryptedKey encryptedKey = keyCipher.encryptKey(document, dataEncryptKey);
    String keyName = "testResolvePrivateKey";
    KeyInfo kekInfo = new KeyInfo(document);
    kekInfo.addKeyName(keyName);
    encryptedKey.setKeyInfo(kekInfo);
    // Encrypt the data
    XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
    xmlCipher.init(XMLCipher.ENCRYPT_MODE, dataEncryptKey);
    EncryptedData encryptedData = xmlCipher.getEncryptedData();
    KeyInfo keyInfo = new KeyInfo(document);
    keyInfo.add(encryptedKey);
    encryptedData.setKeyInfo(keyInfo);
    xmlCipher.doFinal(document, rootElement, true);
    Element encryptedDataElement = (Element) rootElement.getFirstChild();
    assertEquals("EncryptedData", encryptedDataElement.getLocalName());
    // Decrypt the data by resolving the private key used as the KEK
    // First test with an internal KeyResolver
    MyPrivateKeyResolver.pk = privKey;
    MyPrivateKeyResolver.pkName = keyName;
    decryptDocument(document, new MyPrivateKeyResolver());
    // Now test with a static KeyResolver
    KeyResolver.registerAtStart(MyPrivateKeyResolver.class.getName(), false);
    KeyResolverSpi resolver = KeyResolver.iterator().next();
    assertEquals(MyPrivateKeyResolver.class.getName(), resolver.getClass().getName());
    decryptDocument(document, null);
}
Also used : EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Text(org.w3c.dom.Text) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) Document(org.w3c.dom.Document) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) RSAPublicKey(java.security.interfaces.RSAPublicKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeyResolverSpi(org.apache.xml.security.keys.keyresolver.KeyResolverSpi) BigInteger(java.math.BigInteger) EncryptedData(org.apache.xml.security.encryption.EncryptedData) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) KeyFactory(java.security.KeyFactory)

Example 73 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project toshi-android-client by toshiapp.

the class Aes method initWithPassword.

private void initWithPassword(final String password) {
    try {
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(password.getBytes("UTF-8"));
        byte[] keyBytes = new byte[32];
        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        key = new SecretKeySpec(keyBytes, "AES");
        spec = getIV();
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 74 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project toshi-android-client by toshiapp.

the class KeystoreHandler23 method encrypt.

@Override
public String encrypt(final String textToEncrypt) throws KeyStoreException {
    try {
        final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(), spec);
        final byte[] encryptedData = cipher.doFinal(textToEncrypt.getBytes(UTF_8));
        return Base64.encodeToString(encryptedData, Base64.DEFAULT);
    } catch (NoSuchAlgorithmException | BadPaddingException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | UnsupportedEncodingException | InvalidAlgorithmParameterException | java.security.KeyStoreException | UnrecoverableEntryException e) {
        throw new KeyStoreException(new Throwable(e.getMessage()));
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) KeyStoreException(com.toshi.exception.KeyStoreException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) Cipher(javax.crypto.Cipher)

Example 75 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project core-ng-project by neowu.

the class RSA method encrypt.

public byte[] encrypt(byte[] plainMessage) {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(plainMessage);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
        throw new Error(e);
    }
}
Also used : NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException)

Aggregations

NoSuchPaddingException (javax.crypto.NoSuchPaddingException)259 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)237 InvalidKeyException (java.security.InvalidKeyException)216 Cipher (javax.crypto.Cipher)187 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)181 BadPaddingException (javax.crypto.BadPaddingException)180 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)119 SecretKeySpec (javax.crypto.spec.SecretKeySpec)91 IOException (java.io.IOException)83 IvParameterSpec (javax.crypto.spec.IvParameterSpec)66 SecretKey (javax.crypto.SecretKey)45 KeyStoreException (java.security.KeyStoreException)40 CertificateException (java.security.cert.CertificateException)40 UnrecoverableKeyException (java.security.UnrecoverableKeyException)35 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)27 NoSuchProviderException (java.security.NoSuchProviderException)27 GCMParameterSpec (javax.crypto.spec.GCMParameterSpec)18 FileNotFoundException (java.io.FileNotFoundException)16 SecureRandom (java.security.SecureRandom)16