List of usage examples for javax.crypto Cipher ENCRYPT_MODE
int ENCRYPT_MODE
To view the source code for javax.crypto Cipher ENCRYPT_MODE.
Click Source Link
From source file:models.logic.CipherDecipher.java
public static void encrypt(SecretKey key, InputStream is, OutputStream os) throws Throwable { encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os); }
From source file:CipherProvider.java
/** * Cipher setuped for encryption// w ww.j a va 2s . c om * * @return Cipher setuped for encryption */ Cipher getEncryptCipher() { if (StringUtils.isNotBlank(password) && (encryptCipher == null)) { encryptCipher = getCipher(password, Cipher.ENCRYPT_MODE); } return encryptCipher; }
From source file:com.muk.services.commerce.CryptoServiceImpl.java
private byte[] encrypt(byte[] byteArray) { byte[] result = null; try {//from www . ja v a2s . c o m final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, temporaryKey, ivSpec); result = cipher.doFinal(byteArray); } catch (final InvalidKeyException keyEx) { LOG.error("Failed to init cipher.", keyEx); } catch (final NoSuchPaddingException padEx) { LOG.error("Failed to init cipher.", padEx); } catch (final NoSuchAlgorithmException algEx) { LOG.error("Failed to init cipher.", algEx); } catch (final BadPaddingException badPadEx) { LOG.error("Failed to encrypt.", badPadEx); } catch (final IllegalBlockSizeException blockEx) { LOG.error("Failed to encrypt.", blockEx); } catch (final InvalidAlgorithmParameterException paramEx) { LOG.error("Failed to encrypt.", paramEx); } return result; }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding/* w w w. j a va 2 s . com*/ * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String encPass = null; try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.ENCRYPT_MODE, sks); AlgorithmParameters parameters = pbeCipher.getParameters(); IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class); byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding)); byte[] iv = ivParameterSpec.getIV(); String combined = Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(cryptoText); encPass = Base64.getEncoder().encodeToString(combined.getBytes()); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } catch (InvalidParameterSpecException ipsx) { throw new SecurityException(ipsx.getMessage(), ipsx); } return encPass; }
From source file:com.haulmont.cuba.core.sys.SecurityTokenManager.java
/** * Encrypt filtered data and write the result to the security token *///ww w . jav a 2 s . c o m public void writeSecurityToken(Entity entity) { SecurityState securityState = getOrCreateSecurityState(entity); if (securityState != null) { JSONObject jsonObject = new JSONObject(); Multimap<String, Object> filtered = getFilteredData(securityState); if (filtered != null) { Set<Map.Entry<String, Collection<Object>>> entries = filtered.asMap().entrySet(); String[] filteredAttributes = new String[entries.size()]; int i = 0; for (Map.Entry<String, Collection<Object>> entry : entries) { MetaProperty metaProperty = entity.getMetaClass().getPropertyNN(entry.getKey()); if (metadata.getTools().isOwningSide(metaProperty)) { jsonObject.put(entry.getKey(), entry.getValue()); } filteredAttributes[i++] = entry.getKey(); } setFilteredAttributes(securityState, filteredAttributes); } if (!securityState.getReadonlyAttributes().isEmpty()) { jsonObject.put(READ_ONLY_ATTRIBUTES_KEY, securityState.getReadonlyAttributes()); } if (!securityState.getHiddenAttributes().isEmpty()) { jsonObject.put(HIDDEN_ATTRIBUTES_KEY, securityState.getHiddenAttributes()); } if (!securityState.getRequiredAttributes().isEmpty()) { jsonObject.put(REQUIRED_ATTRIBUTES_KEY, securityState.getRequiredAttributes()); } String json = jsonObject.toString(); byte[] encrypted; Cipher cipher = getCipher(Cipher.ENCRYPT_MODE); try { encrypted = cipher.doFinal(json.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException("An error occurred while generating security token", e); } setSecurityToken(securityState, encrypted); } }
From source file:br.com.vizzatech.cryptocipher.CryptoXCipher.java
/** * Construtor private/*from w ww . j a v a 2s . c o m*/ * * @param sal * Palavra chave * @param algoritmo * Algoritmo a ser utilizado * @param cifraCesar * em quantos numeros os caracteres sero trocados * @param charset * @throws IllegalArgumentException */ private CryptoXCipher(String sal, String algoritmo, int cifraCesar, Charset charset) throws IllegalArgumentException { try { this.charset = charset; SecretKey chave = getKey(algoritmo, sal); this.encrypt = Cipher.getInstance(algoritmo); this.decrypt = Cipher.getInstance(algoritmo); this.encrypt.init(Cipher.ENCRYPT_MODE, chave, paramSpec); this.decrypt.init(Cipher.DECRYPT_MODE, chave, paramSpec); this.cifraCesar = cifraCesar; } catch (Exception e) { throw new IllegalArgumentException(e); } }
From source file:com.ccstats.crypto.AESWorker.java
/** * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes * as they are necessary for decrypting the encrypted result. * * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely * generated. Finally, the encryption standard is carried out and the encrypted text is obtained. * * @param password the password as a char array. * @param text The plaintext bytes to be encrypted. * * @return The Encrypted text in hexadecimal format. */// ww w . ja va 2 s.com public char[] encrypt(char[] password, byte[] text) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) { this.keyLength = Cipher.getMaxAllowedKeyLength("AES"); System.err.printf( "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n", this.keyLength, this.keyLength); } // hash the password and acquire a securely and randomly generated salt password = hash(new String(password).getBytes(StandardCharsets.UTF_8)); byte[] salt = new byte[20]; new SecureRandom().nextBytes(salt); // acquire the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength); SecretKey key = factory.generateSecret(spec); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); // init the cipher and process the encryption cipher.init(Cipher.ENCRYPT_MODE, keySpec); AlgorithmParameters ap = cipher.getParameters(); byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV(); byte[] result = cipher.doFinal(text); return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt)); }
From source file:com.liferay.util.Encryptor.java
public static String encrypt(Key key, String plainText) throws EncryptorException { try {//from w w w . j ava 2 s. co m Security.addProvider(getProvider()); Cipher cipher = Cipher.getInstance(key.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] decryptedBytes = plainText.getBytes(ENCODING); byte[] encryptedBytes = cipher.doFinal(decryptedBytes); String encryptedString = Base64.encode(encryptedBytes); return encryptedString; } catch (Exception e) { throw new EncryptorException(e); } }
From source file:com.lightszentip.module.security.password.PasswordModuleImpl.java
/** * {@inheritDoc}//from w ww. java 2 s. c o m */ @Override public String encrypt(String value, String key, EncryptionType type) { return crypt(value, key, type, Cipher.ENCRYPT_MODE); }
From source file:com.titilink.common.app.EncryptDecryptUtil.java
public void testDES() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException { ////w ww.j ava 2 s . c om DESKeySpec desKeySpec = new DESKeySpec("SECURITY".getBytes(Charset.forName("UTF-8"))); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); //?? Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom()); byte[] cipherData = cipher .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8"))); //? Cipher cipher1 = Cipher.getInstance("DES"); cipher1.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom()); byte[] plainData = cipher1.doFinal(cipherData); System.out.println(new String(plainData, Charset.forName("UTF-8"))); }