List of usage examples for javax.crypto Cipher unwrap
public final Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException
From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java
@Override public PrivateKey decryptPrivateKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key, String keyToDecrypt) throws NetInfCheckedSecurityException { try {// ww w. j a va2s . c om Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey); cipher.init(Cipher.UNWRAP_MODE, key); return (PrivateKey) cipher.unwrap(Utils.stringToBytes(keyToDecrypt), algorithmKeyIsUsedFor, Cipher.PRIVATE_KEY); } catch (NoSuchAlgorithmException e) { throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage()); } catch (NoSuchPaddingException e) { throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage()); } catch (InvalidKeyException e) { throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage()); } }
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.ja v a2 s. c o m*/ 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 w w .j a va2 s.c o m*/ * @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 */// w ww. j a va 2 s . c om 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;//w ww.j av a 2 s . c o m 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.soulwing.credo.service.crypto.jca.JcaEncryptedPrivateKeyWrapper.java
/** * {@inheritDoc}//from ww w.j a v a 2s .c om */ @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); } }
From source file:org.tolven.security.password.PasswordHolder.java
private void loadSecretKey(File encryptedSecretKeyFile, char[] password) { try {// w ww. jav a 2 s . c om ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream in = null; try { in = new FileInputStream(encryptedSecretKeyFile); byte[] bytes = new byte[1024]; int n = 0; while ((n = in.read(bytes)) != -1) { baos.write(bytes, 0, n); } } finally { if (in != null) { in.close(); } } byte[] encryptedSecretKey = Base64.decodeBase64(baos.toByteArray()); String alias = getKeyStore().aliases().nextElement(); Key key = getKeyStore().getKey(alias, password); Cipher cipher = Cipher.getInstance(key.getAlgorithm()); cipher.init(Cipher.UNWRAP_MODE, key); secretKey = (SecretKey) cipher.unwrap(encryptedSecretKey, "DESede", Cipher.SECRET_KEY); } catch (Exception ex) { throw new RuntimeException("Could not load secret key from " + encryptedSecretKeyFile.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()); }