Example usage for javax.crypto Cipher UNWRAP_MODE

List of usage examples for javax.crypto Cipher UNWRAP_MODE

Introduction

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

Prototype

int UNWRAP_MODE

To view the source code for javax.crypto Cipher UNWRAP_MODE.

Click Source Link

Document

Constant used to initialize cipher to key-unwrapping mode.

Usage

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

@Override
public CryptoModuleParameters decryptSecretKey(CryptoModuleParameters context) {
    try {/*from   w  w  w. j av  a  2 s  .c o m*/
        secretKeyCache.ensureSecretKeyCacheInitialized(context);
        doKeyEncryptionOperation(Cipher.UNWRAP_MODE, context);
    } catch (IOException e) {
        log.error("{}", e.getMessage(), e);
        throw new RuntimeException(e);
    }
    return context;
}

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 {// w  w w  .j a va  2s .  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

/**
 * Decrypt a key from a passed in EncryptedKey structure
 *
 * @param encryptedKey Previously loaded EncryptedKey that needs
 * to be decrypted.//from   w  ww  .j a  va 2 s . c om
 * @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.isDebugEnabled()) {
        log.debug("Decrypting key from previously loaded EncryptedKey...");
    }

    if (cipherMode != UNWRAP_MODE && log.isDebugEnabled()) {
        log.debug("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.isDebugEnabled()) {
            log.debug("Trying to find a KEK via key resolvers");
        }

        KeyInfo ki = encryptedKey.getKeyInfo();
        if (ki != null) {
            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.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }
        if (key == null) {
            log.error("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);
    byte[] encryptedBytes = cipherInput.getBytes();

    String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
    if (log.isDebugEnabled()) {
        log.debug("JCE Key Algorithm: " + jceKeyAlgorithm);
    }

    Cipher c;
    if (contextCipher == null) {
        // Now create the working cipher

        String jceAlgorithm = JCEMapper.translateURItoJCEID(encryptedKey.getEncryptionMethod().getAlgorithm());
        if (log.isDebugEnabled()) {
            log.debug("JCE Algorithm = " + 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;
    }

    Key ret;

    try {
        c.init(Cipher.UNWRAP_MODE, key);
        ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (NoSuchAlgorithmException nsae) {
        throw new XMLEncryptionException("empty", nsae);
    }
    if (log.isDebugEnabled()) {
        log.debug("Decryption of key type " + algorithm + " OK");
    }

    return ret;
}

From source file:org.auscope.portal.server.web.controllers.GridLoginController.java

/**
 * Extracts and decrypts the XML response received from the SLCS server
 *//*ww w. j  av  a2  s.  co  m*/
private String extractSlcsResponse(HttpServletRequest request) throws GeneralSecurityException, IOException {
    String responseXML = null;
    String certReqDataHex = request.getParameter("CertificateRequestData");
    String sessionKeyHex = request.getParameter("SessionKey");
    if (certReqDataHex == null || sessionKeyHex == null) {
        logger.error("CertificateRequestData or SessionKey empty!");
    } else {
        // load host key
        FileInputStream in = new FileInputStream(HOST_KEY_FILE);
        PKCS8Key pem = new PKCS8Key(in, null);
        Key privateKey = pem.getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);

        // unwrap session key and decrypt request data
        byte[] wrappedKey = unhexlify(sessionKeyHex);
        ByteArrayInputStream certReqDataEnc = new ByteArrayInputStream(unhexlify(certReqDataHex));
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        responseXML = decryptString(certReqDataEnc, cipher);
    }
    return responseXML;
}

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

private Key getKeyFromProperties(String alias) {
    Key key = null;//from w  w w.  ja  va  2 s .com
    Properties prop = getProperties();
    String str = prop.getProperty(alias);
    if (StringUtils.isNotEmpty(str)) {
        // TODO: unwrapping with rsa key is also needed later on
        try {
            PrivateKey privK = getPrivateKey("symwrap");
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", getEncProviderName());
            cipher.init(Cipher.UNWRAP_MODE, privK);
            byte[] bytes = Hex.decode(str);
            // TODO: hardcoded AES for now
            key = cipher.unwrap(bytes, "AES", Cipher.SECRET_KEY);
        } catch (CryptoTokenOfflineException e) {
            log.debug(e);
        } catch (NoSuchAlgorithmException e) {
            log.debug(e);
        } catch (NoSuchProviderException e) {
            log.debug(e);
        } catch (NoSuchPaddingException e) {
            log.debug(e);
        } catch (InvalidKeyException e) {
            log.debug(e);
        }
    }
    return key;
}

From source file:org.kuali.rice.core.impl.encryption.DemonstrationGradeEncryptionServiceImpl.java

private SecretKey unwrapEncodedKey(String key) throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();

    // Create the cipher
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init((Cipher.UNWRAP_MODE), desKey);

    byte[] bytes = Base64.decodeBase64(key.getBytes());

    SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec keyspec = new DESKeySpec(bytes);
    SecretKey k = desFactory.generateSecret(keyspec);

    return k;/*from  w  w  w  .  jav a  2  s .  c  om*/

}

From source file:org.kuali.rice.kew.documentoperation.web.DocumentContentOperationAction.java

private SecretKey getSecretKey(String encryptionKey) throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();

    // Create the cipher
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init((Cipher.UNWRAP_MODE), desKey);

    byte[] bytes = Base64.decodeBase64(encryptionKey.getBytes());

    SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec keyspec = new DESKeySpec(bytes);
    desKey = desFactory.generateSecret(keyspec);
    // Create the cipher
    cipher.init((Cipher.WRAP_MODE), desKey);
    return desKey;
}

From source file:org.kuali.rice.krad.devtools.maintainablexml.EncryptionService.java

private SecretKey unwrapEncodedKeyOld(String key) throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();

    // Create the cipher
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init((Cipher.UNWRAP_MODE), desKey);

    byte[] bytes = Base64.decodeBase64(key.getBytes());

    // If decoding was done with commons-codec 1.3 and the key not ended with '='
    bytes[6] = 1;/*from ww  w  . j a  v  a 2 s. co m*/
    bytes[7] = 1;

    SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec keyspec = new DESKeySpec(bytes);
    SecretKey k = desFactory.generateSecret(keyspec);

    return k;

}

From source file:org.soulwing.credo.service.crypto.jca.JcaAESEncryptedSecretKeyWrapper.java

@Override
protected Cipher createCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(transform);
    cipher.init(Cipher.UNWRAP_MODE, getKey(), new IvParameterSpec(iv));
    return cipher;
}

From source file:org.soulwing.credo.service.crypto.jca.JcaEncryptedPrivateKeyWrapper.java

/**
 * {@inheritDoc}/*from   w  w w  .  jav a  2s  .  c  o m*/
 */
@Override
public PrivateKey derive() {
    int delimiter = transform.indexOf('/');
    if (delimiter == -1) {
        throw new IllegalArgumentException("illegal transform syntax: " + transform);
    }
    try {
        String algorithm = transform.substring(0, delimiter);
        Cipher cipher = Cipher.getInstance(transform);
        cipher.init(Cipher.UNWRAP_MODE, secretKey.derive(), new IvParameterSpec(iv));
        return (PrivateKey) cipher.unwrap(cipherText, algorithm, Cipher.SECRET_KEY);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchPaddingException ex) {
        throw new RuntimeException(ex);
    } catch (InvalidAlgorithmParameterException ex) {
        throw new RuntimeException(ex);
    } catch (InvalidKeyException ex) {
        throw new RuntimeException(ex);
    }
}