List of usage examples for javax.crypto Cipher SECRET_KEY
int SECRET_KEY
To view the source code for javax.crypto Cipher SECRET_KEY.
Click Source Link
From source file:MainClass.java
public static void main(String[] args) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("DESede"); Key sharedKey = kg.generateKey(); String password = "password"; byte[] salt = "salt1234".getBytes(); PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20); PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey passwordKey = kf.generateSecret(keySpec); Cipher c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.WRAP_MODE, passwordKey, paramSpec); byte[] wrappedKey = c.wrap(sharedKey); c = Cipher.getInstance("DESede"); c.init(Cipher.ENCRYPT_MODE, sharedKey); byte[] input = "input".getBytes(); byte[] encrypted = c.doFinal(input); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec); Key unwrappedKey = c.unwrap(wrappedKey, "DESede", Cipher.SECRET_KEY); c = Cipher.getInstance("DESede"); c.init(Cipher.DECRYPT_MODE, unwrappedKey); System.out.println(new String(c.doFinal(encrypted))); }
From source file:RSATest.java
public static void main(String[] args) { try {/*w w w . j a va 2 s .c om*/ if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:eu.peppol.security.OxalisCipherConverter.java
/** * Creates an instance of OxalisCipher://from www .j av a2 s.c om * <ol> * <li>Decodes the supplied hex string representation of a wrapped key into an array of bytes representation</li> * <li>Creates a cipher, which is initialized with a private key</li> * <li>Unwraps (decrypts) the secret key represented by an array of bytes into a SecretKey</li> * <li>Creates an OxalisCipher using the unwrapped SecretKey</li> * </ol> * @param wrappedSymmetricKeyAsHexString * @param privateKey * @return */ public OxalisCipher createCipherFromWrappedHexKey(String wrappedSymmetricKeyAsHexString, PrivateKey privateKey) { // 1) Decodes the hex string representation of a wrapped key byte[] encodedBytes = encodedBytesFromHexString(wrappedSymmetricKeyAsHexString); try { // 2) Creates the Cipher using supplied private key Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM); cipher.init(Cipher.UNWRAP_MODE, privateKey); // 3) Unwraps (decrypts) the secret key using our private key SecretKey secretKey = (SecretKey) cipher.unwrap(encodedBytes, OxalisCipher.SYMMETRIC_KEY_ALGORITHM, Cipher.SECRET_KEY); // 4) creates the Oxalis cipher OxalisCipher oxalisCipher = new OxalisCipher(secretKey); return oxalisCipher; } catch (NoSuchAlgorithmException e) { throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e); } catch (NoSuchPaddingException e) { throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e); } catch (InvalidKeyException e) { throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e); } }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException { secureRandom = new SecureRandom(); this.vaultPath = vaultPath; this.encryptionMode = encryptionMode; File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME); if (!headerFile.exists()) { try {/*from www . ja va 2s . com*/ KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(AES_KEY_SIZE_BIT); Key encryptionKey = keyGenerator.generateKey(); byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase); } catch (Exception e) { Util.log("Cannot create vault header!"); e.printStackTrace(); } } try { FileInputStream headerInputStream = new FileInputStream(headerFile); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); e.printStackTrace(); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); } catch (InvalidKeyException e) { throw new InvalidKeyException("Passphrase is wrong!"); } catch (Exception e) { Util.log("Cannot decrypt AES key"); e.printStackTrace(); } }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
/** * Reads the encrypted masterkey from the given input stream and decrypts it with the given password. * /*ww w.j a v a 2s.c o m*/ * @throws DecryptFailedException If the decryption failed for various reasons (including wrong password). * @throws WrongPasswordException If the provided password was wrong. Note: Sometimes the algorithm itself fails due to a wrong * password. In this case a DecryptFailedException will be thrown. * @throws UnsupportedKeyLengthException If the masterkey has been encrypted with a higher key length than supported by the system. In * this case Java JCE needs to be installed. */ @Override public void decryptMasterKey(InputStream in, CharSequence password) throws DecryptFailedException, WrongPasswordException, UnsupportedKeyLengthException, IOException { try { // load encrypted masterkey: final KeyFile keyfile = objectMapper.readValue(in, KeyFile.class); // check, whether the key length is supported: final int maxKeyLen = Cipher.getMaxAllowedKeyLength(AES_KEY_ALGORITHM); if (keyfile.getKeyLength() > maxKeyLen) { throw new UnsupportedKeyLengthException(keyfile.getKeyLength(), maxKeyLen); } // derive key: final SecretKey kek = scrypt(password, keyfile.getScryptSalt(), keyfile.getScryptCostParam(), keyfile.getScryptBlockSize(), AES_KEY_LENGTH_IN_BITS); // decrypt and check password by catching AEAD exception final Cipher decCipher = aesKeyWrapCipher(kek, Cipher.UNWRAP_MODE); SecretKey primary = (SecretKey) decCipher.unwrap(keyfile.getPrimaryMasterKey(), AES_KEY_ALGORITHM, Cipher.SECRET_KEY); SecretKey secondary = (SecretKey) decCipher.unwrap(keyfile.getHMacMasterKey(), HMAC_KEY_ALGORITHM, Cipher.SECRET_KEY); // everything ok, assign decrypted keys: this.primaryMasterKey = primary; this.hMacMasterKey = secondary; } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("Algorithm should exist.", ex); } catch (InvalidKeyException e) { throw new WrongPasswordException(); } }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
@Override public boolean changePassphrase(String oldPassphrase, String newPassphrase) { SecretKeyFactory secretKeyFactory; File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME); File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW"); if (!headerFileNew.exists()) { try {/*from www.ja v a2 s .c o m*/ // Decrypt AES encryption key secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); // Create new vault nonce and salt byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt); // Create new key for AES key encryption SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey, newKeyFromPassphrase); } catch (Exception e) { Util.log("Error while reading or creating new vault header!"); return false; } } else { Util.log("New header file already exists. Cannot change passphrase!"); return false; } // Try to parse new header file try { FileInputStream headerInputStream = new FileInputStream(headerFileNew); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); headerFileNew.delete(); return false; } // Delete old header file and replace with new header file if (!headerFileOld.delete()) { headerFileNew.delete(); Util.log("Cannot delete old vault header!"); return false; } try { org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld); } catch (IOException e) { Util.log("Cannot replace old vault header!"); return false; } headerFileNew.delete(); return true; }
From source file:com.kactech.otj.Utils.java
public static String open(byte[] encryptedEnvelope, PrivateKey privateKey) throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String str;//from www . j av a 2 s .c om byte[] by; ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope); buff.order(ByteOrder.BIG_ENDIAN); int envType = buff.getShort();// expected 1(asymmetric) if (envType != 1) throw new UnsupportedOperationException("unexpected envelope type " + envType); int arraySize = buff.getInt();// can result in negative integer but not expecting it here if (arraySize != 1)//TODO throw new UnsupportedOperationException("current code doesn't support multi-nym response"); byte[] encKeyBytes = null; byte[] vectorBytes = null; for (int i = 0; i < arraySize; i++) { int nymIDLen = buff.getInt(); by = new byte[nymIDLen]; buff.get(by); String nymID; try { nymID = new String(by, 0, by.length - 1, Utils.US_ASCII); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // take nymID W/O trailing \0 //TODO nymID matching! int keyLength = buff.getInt(); encKeyBytes = new byte[keyLength]; buff.get(encKeyBytes); int vectorLength = buff.getInt(); vectorBytes = new byte[vectorLength]; buff.get(vectorBytes); } byte[] encryptedMsg = new byte[buff.remaining()]; buff.get(encryptedMsg); Cipher cipher; try { cipher = Cipher.getInstance(WRAP_ALGO); } catch (Exception e) { throw new RuntimeException(e); } cipher.init(Cipher.UNWRAP_MODE, privateKey); SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY); try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (Exception e) { throw new RuntimeException(e); } cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes)); by = cipher.doFinal(encryptedMsg); try { str = new String(by, 0, by.length - 1, Utils.UTF8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // w/o trailing \0 return str; }
From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java
@Override public SecretKey decryptSecretKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key, String keyToDecrypt) throws NetInfCheckedSecurityException { try {/* ww w . ja v a 2s. c om*/ LOG.debug("Decrypting SecretKey."); LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey); LOG.trace("Used algorithm of encrypted key: " + algorithmKeyIsUsedFor); LOG.trace("Used key: " + key); LOG.trace("Used key to be decrypted: " + keyToDecrypt); Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey); cipher.init(Cipher.UNWRAP_MODE, key); return (SecretKey) cipher.unwrap(Base64.decodeBase64(keyToDecrypt), algorithmKeyIsUsedFor, Cipher.SECRET_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 w w . j a v a 2s. co 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 ww . j a v a 2s .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; }