Example usage for javax.crypto Cipher wrap

List of usage examples for javax.crypto Cipher wrap

Introduction

In this page you can find the example usage for javax.crypto Cipher wrap.

Prototype

public final byte[] wrap(Key key) throws IllegalBlockSizeException, InvalidKeyException 

Source Link

Document

Wrap a key.

Usage

From source file:org.apache.accumulo.core.security.crypto.CachingHDFSSecretKeyEncryptionStrategy.java

private void doKeyEncryptionOperation(int encryptionMode, CryptoModuleParameters params) throws IOException {
    Cipher cipher = DefaultCryptoModuleUtils
            .getCipher(params.getAllOptions().get(Property.CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE.getKey()));

    try {//from w ww. j a va  2  s  . c om
        cipher.init(encryptionMode,
                new SecretKeySpec(secretKeyCache.getKeyEncryptionKey(), params.getAlgorithmName()));
    } catch (InvalidKeyException e) {
        log.error("{}", e.getMessage(), e);
        throw new RuntimeException(e);
    }

    if (Cipher.UNWRAP_MODE == encryptionMode) {
        try {
            Key plaintextKey = cipher.unwrap(params.getEncryptedKey(), params.getAlgorithmName(),
                    Cipher.SECRET_KEY);
            params.setPlaintextKey(plaintextKey.getEncoded());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    } else {
        Key plaintextKey = new SecretKeySpec(params.getPlaintextKey(), params.getAlgorithmName());
        try {
            byte[] encryptedSecretKey = cipher.wrap(plaintextKey);
            params.setEncryptedKey(encryptedSecretKey);
            params.setOpaqueKeyEncryptionKeyID(secretKeyCache.getPathToKeyName());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

/**
 * 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/*ww w . j  ava2 s  .  c o m*/
 * @return the <code>EncryptedKey</code>
 * @throws XMLEncryptionException
 */
public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException {
    if (log.isDebugEnabled()) {
        log.debug("Encrypting key ...");
    }

    if (null == key) {
        log.error("Key unexpectedly null...");
    }
    if (cipherMode != WRAP_MODE) {
        log.debug("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

        String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
        if (log.isDebugEnabled()) {
            log.debug("alg = " + jceAlgorithm);
        }

        try {
            if (requestedJCEProvider == null) {
                c = Cipher.getInstance(jceAlgorithm);
            } else {
                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
            }
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLEncryptionException("empty", nsae);
        } catch (NoSuchProviderException nspre) {
            throw new XMLEncryptionException("empty", nspre);
        } catch (NoSuchPaddingException nspae) {
            throw new XMLEncryptionException("empty", nspae);
        }
    } else {
        c = contextCipher;
    }
    // Now perform the encryption

    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        c.init(Cipher.WRAP_MODE, this.key);
        encryptedBytes = c.wrap(key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    }

    String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
    if (log.isDebugEnabled()) {
        log.debug("Encrypted key octets:\n" + base64EncodedEncryptedOctets);
        log.debug("Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
    }

    CipherValue cv = ek.getCipherData().getCipherValue();
    cv.setValue(base64EncodedEncryptedOctets);

    try {
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        ek.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ek;
}

From source file:org.apache.xml.security.stax.impl.processor.output.XMLEncryptOutputProcessor.java

/**
 * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance
 * which will write out the KeyInfo contents in the EncryptedData.
 *///from   www .j av a  2 s.  com
protected AbstractInternalEncryptionOutputProcessor createInternalEncryptionOutputProcessor(
        EncryptionPartDef encryptionPartDef, XMLSecStartElement startElement, String encoding,
        final OutboundSecurityToken keyWrappingToken) throws XMLStreamException, XMLSecurityException {

    final AbstractInternalEncryptionOutputProcessor processor = new AbstractInternalEncryptionOutputProcessor(
            encryptionPartDef, startElement, encoding) {

        @Override
        protected void createKeyInfoStructure(OutputProcessorChain outputProcessorChain)
                throws XMLStreamException, XMLSecurityException {
            if (keyWrappingToken == null) {
                // Do not write out a KeyInfo element
                return;
            }

            final String encryptionKeyTransportAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportAlgorithm();

            PublicKey pubKey = keyWrappingToken.getPublicKey();
            Key secretKey = keyWrappingToken.getSecretKey(encryptionKeyTransportAlgorithm);
            if (pubKey == null && secretKey == null) {
                // Do not write out a KeyInfo element
                return;
            }

            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo,
                    true, null);

            List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
            String keyId = IDGenerator.generateID("EK");
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, keyId));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey,
                    true, attributes);

            attributes = new ArrayList<XMLSecAttribute>(1);
            attributes.add(
                    createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportAlgorithm));
            createStartElementAndOutputAsEvent(outputProcessorChain,
                    XMLSecurityConstants.TAG_xenc_EncryptionMethod, false, attributes);

            final String encryptionKeyTransportDigestAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportDigestAlgorithm();
            final String encryptionKeyTransportMGFAlgorithm = getSecurityProperties()
                    .getEncryptionKeyTransportMGFAlgorithm();

            if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm)
                    || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {

                byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                if (oaepParams != null) {
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc_OAEPparams, false, null);
                    createCharactersAndOutputAsEvent(outputProcessorChain,
                            Base64.encodeBase64String(oaepParams));
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc_OAEPparams);
                }

                if (encryptionKeyTransportDigestAlgorithm != null) {
                    attributes = new ArrayList<XMLSecAttribute>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm,
                            encryptionKeyTransportDigestAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_DigestMethod, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_DigestMethod);
                }

                if (encryptionKeyTransportMGFAlgorithm != null) {
                    attributes = new ArrayList<XMLSecAttribute>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm,
                            encryptionKeyTransportMGFAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc11_MGF, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF);
                }
            }

            createEndElementAndOutputAsEvent(outputProcessorChain,
                    XMLSecurityConstants.TAG_xenc_EncryptionMethod);

            createKeyInfoStructureForEncryptedKey(outputProcessorChain, keyWrappingToken);

            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData,
                    false, null);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue,
                    false, null);

            //encrypt the symmetric session key with the public key from the receiver:
            String jceid = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportAlgorithm);
            if (jceid == null) {
                throw new XMLSecurityException("algorithms.NoSuchMap",
                        new Object[] { encryptionKeyTransportAlgorithm });
            }

            try {
                Cipher cipher = Cipher.getInstance(jceid);

                AlgorithmParameterSpec algorithmParameterSpec = null;
                if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm)
                        || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {

                    String jceDigestAlgorithm = "SHA-1";
                    if (encryptionKeyTransportDigestAlgorithm != null) {
                        jceDigestAlgorithm = JCEAlgorithmMapper
                                .translateURItoJCEID(encryptionKeyTransportDigestAlgorithm);
                    }

                    PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
                    byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                    if (oaepParams != null) {
                        pSource = new PSource.PSpecified(oaepParams);
                    }

                    MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
                    if (encryptionKeyTransportMGFAlgorithm != null) {
                        String jceMGFAlgorithm = JCEAlgorithmMapper
                                .translateURItoJCEID(encryptionKeyTransportMGFAlgorithm);
                        mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm);
                    }
                    algorithmParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec,
                            pSource);
                }

                if (pubKey != null) {
                    cipher.init(Cipher.WRAP_MODE, pubKey, algorithmParameterSpec);
                } else {
                    cipher.init(Cipher.WRAP_MODE, secretKey, algorithmParameterSpec);
                }

                String tokenId = outputProcessorChain.getSecurityContext()
                        .get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
                SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = outputProcessorChain
                        .getSecurityContext().getSecurityTokenProvider(tokenId);

                final OutboundSecurityToken securityToken = securityTokenProvider.getSecurityToken();
                Key sessionKey = securityToken
                        .getSecretKey(getSecurityProperties().getEncryptionSymAlgorithm());
                if (pubKey != null) {
                    int blockSize = cipher.getBlockSize();
                    if (blockSize > 0 && blockSize < sessionKey.getEncoded().length) {
                        throw new XMLSecurityException("stax.unsupportedKeyTransp");
                    }
                }
                byte[] encryptedEphemeralKey = cipher.wrap(sessionKey);

                createCharactersAndOutputAsEvent(outputProcessorChain,
                        new Base64(76, new byte[] { '\n' }).encodeToString(encryptedEphemeralKey));

            } catch (NoSuchPaddingException e) {
                throw new XMLSecurityException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidKeyException e) {
                throw new XMLSecurityException(e);
            } catch (IllegalBlockSizeException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new XMLSecurityException(e);
            }

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData);

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey);

            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
        }

        protected void createKeyInfoStructureForEncryptedKey(OutputProcessorChain outputProcessorChain,
                OutboundSecurityToken securityToken) throws XMLStreamException, XMLSecurityException {
            SecurityTokenConstants.KeyIdentifier keyIdentifier = getSecurityProperties()
                    .getEncryptionKeyIdentifier();

            X509Certificate[] x509Certificates = securityToken.getX509Certificates();
            if (x509Certificates == null) {
                if (securityToken.getPublicKey() != null
                        && SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    createStartElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);

                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain,
                            securityToken.getPublicKey());
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_dsig_KeyInfo);
                }
                return;
            }

            if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(keyIdentifier)) {
                createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo,
                        true, null);

                if (keyIdentifier == null
                        || SecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509IssuerSerialStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectKeyIdentifierStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509CertificateStructure(this, outputProcessorChain,
                            x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509SubjectName.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectNameStructure(this, outputProcessorChain,
                            x509Certificates);
                } else {
                    throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier });
                }

                createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
            }
        }
    };
    processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
    return processor;
}

From source file:org.cesecore.keys.token.SoftCryptoToken.java

@Override
public void generateKey(final String algorithm, final int keysize, final String alias)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException,
        CryptoTokenOfflineException, InvalidKeyException, InvalidAlgorithmParameterException,
        SignatureException, CertificateException, IOException, NoSuchPaddingException,
        IllegalBlockSizeException {
    if (StringUtils.isNotEmpty(alias)) {
        // Soft crypto tokens must do very special things for secret keys, since PKCS#12 keystores are ot designed to hold
        // symmetric keys, we wrap the symmetric key with an RSA key and store it in properties

        // Generate the key
        KeyGenerator generator = KeyGenerator.getInstance(algorithm, getEncProviderName());
        generator.init(keysize);//  ww w.  j  a v  a  2  s. com
        Key key = generator.generateKey();
        // Wrap it
        // Find wrapping key
        PublicKey pubK = null;
        try {
            pubK = getPublicKey("symwrap");
        } catch (CryptoTokenOfflineException e) {
            // No such key, generate it
            generateKeyPair("2048", "symwrap");
            pubK = getPublicKey("symwrap");
        }

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", getEncProviderName());
        cipher.init(Cipher.WRAP_MODE, pubK);
        byte[] out = cipher.wrap(key);

        String str = new String(Hex.encode(out));
        Properties prop = getProperties();
        prop.setProperty(alias, str);
        setProperties(prop);
    } else {
        log.debug("Trying to generate keys with empty alias.");
    }
}

From source file:org.latticesoft.util.common.CryptoHelper.java

public String convertKeyToString() {
    StringBuffer sb = new StringBuffer();
    Cipher cipher = null;
    byte[] priKeyByte = null;
    byte[] pubKeyByte = null;
    String priKeyString = null;/*  w  w w .ja  v  a2s . c  om*/
    String pubKeyString = null;
    try {
        cipher = Cipher.getInstance(this.getInstanceAlgorithm(), this.providerName);
        priKeyByte = cipher.wrap(this.keyPair.getPrivate());
        pubKeyByte = cipher.wrap(this.keyPair.getPublic());
        priKeyString = NumeralUtil.toHexString(priKeyByte);
        pubKeyString = NumeralUtil.toHexString(pubKeyByte);
        sb.append("algor=").append(this.getInstanceAlgorithm()).append("|");
        sb.append("strength=").append(this.strength).append("|");
        sb.append("priKey=").append(priKeyString).append("|");
        sb.append("pubKey=").append(pubKeyString).append("|");
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error storing key");
        }
    }
    return sb.toString();
}

From source file:org.tolven.security.password.PasswordHolder.java

private void generateSecretKey(File secretKeyFile) {
    if (getSecretKeyFile().exists()) {
        throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath());
    }/*  ww  w.j  av  a 2s. co m*/
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(112);
        secretKey = keyGenerator.generateKey();
        String alias = getKeyStore().aliases().nextElement();
        Certificate adminCert = getKeyStore().getCertificate(alias);
        PublicKey publicKey = adminCert.getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] encryptedSecretKey = cipher.wrap(secretKey);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(secretKeyFile);
            out.write(Base64.encodeBase64(encryptedSecretKey));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSoftwareRSAKeyWrapping() throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    final SecretKey secretKey = keyGenerator.generateKey();
    LOG.debug("secret key algo: " + secretKey.getAlgorithm());

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
    LOG.debug("cipher security provider: " + cipher.getProvider().getName());
    LOG.debug("cipher type: " + cipher.getClass().getName());
    final byte[] wrappedKey = cipher.wrap(secretKey);

    cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
    final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

    assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded());

}