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:duthientan.mmanm.com.CipherRSA.java
@Override public void encrypt(String filePath) { try {/*from www . ja v a 2 s. c om*/ Cipher ecipher = Cipher.getInstance("RSA"); ecipher.init(Cipher.ENCRYPT_MODE, publicKey); Path path = Paths.get(filePath); String encryptFilePath = path.getParent().toString() + "/" + "RSA" + "_" + path.getFileName().toString(); byte[] data = Files.readAllBytes(path); byte[] textEncrypted = null; int chunkSize = 245; if (data.length < 245) { textEncrypted = ecipher.doFinal(data); } else { for (int i = 0; i < data.length; i += chunkSize) { byte[] segment = Arrays.copyOfRange(data, i, i + chunkSize > data.length ? data.length : i + chunkSize); byte[] segmentEncrypted = ecipher.doFinal(segment); textEncrypted = ArrayUtils.addAll(textEncrypted, segmentEncrypted); } } FileOutputStream fos = new FileOutputStream(encryptFilePath); fos.write(textEncrypted); fos.close(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalBlockSizeException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } catch (BadPaddingException ex) { Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.apigw.commons.crypto.Encrypter.java
/** * //www. j a v a2 s. c o m * @param message A string to encrypt * @return An encrypted (AES) and base64 encoded string * @throws java.lang.RuntimeException */ public String encrypt(String message) throws RuntimeException { log.debug("About to encrypt a message"); if (message == null) { log.trace("incoming message is null, returning null"); return null; } if (useEncryption) { try { SecretKeySpec skeySpec = getSecretKeySpec(); IvParameterSpec ivParameterSpec = getIvParameterSpec(); Cipher encryptCipher = getCipher(); encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = encryptCipher.doFinal(message.getBytes("utf8")); final String encryptedMessage = new String(Base64.encodeBase64(encrypted), "utf8"); log.debug("Message encrypted: {}", encryptedMessage); return encryptedMessage; } catch (Exception e) { log.error("Caught an error while encrypting", e); throw new RuntimeException(e); } } else { log.debug("Encryption is disabled, will not encrypt message"); return message; } }
From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java
/** * ?// w ww .j a va 2 s . c om * * @param data? * @param key * * @return byte[] ? */ public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception { // ?? PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // ?? PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); // ? Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data); }
From source file:DesEncrypter.java
private DesEncrypter(String passPhrase) { try {/*w w w .java 2 s. co m*/ // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (java.security.InvalidAlgorithmParameterException e) { } catch (java.security.spec.InvalidKeySpecException e) { } catch (javax.crypto.NoSuchPaddingException e) { } catch (java.security.NoSuchAlgorithmException e) { } catch (java.security.InvalidKeyException e) { } }
From source file:corner.encrypt.services.impl.DESedeEncryptServiceImpl.java
/** * @see corner.encrypt.services.EncryptService#encrypt(byte[], byte[]) *//* w w w. j ava 2s . co m*/ @Override public byte[] encrypt(byte[] src, byte[] key) { try { SecretKey deskey = new SecretKeySpec(key, Algorithm); Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT_MODE, deskey); return c1.doFinal(src); } catch (java.security.NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (javax.crypto.NoSuchPaddingException e2) { e2.printStackTrace(); } catch (java.lang.Exception e3) { e3.printStackTrace(); } return null; }
From source file:cn.org.once.cstack.utils.CustomPasswordEncoder.java
@Override public String encode(CharSequence sequence) { Cipher cipher;//from ww w. j a v a 2 s. c om String encryptedString = null; try { cipher = Cipher.getInstance(ALGO); cipher.init(Cipher.ENCRYPT_MODE, generateKey()); encryptedString = Base64.encodeBase64String(cipher.doFinal(sequence.toString().getBytes())); } catch (Exception e) { e.printStackTrace(); } return encryptedString; }
From source file:com.credomatic.gprod.db2query2csv.Security.java
/** * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). * @param KeySize tamao de la llave autogenerada para relizar el cifrado * @param value cadena de caracteres que sera cifrada * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado */// ww w .j a v a2s . c o m public static SecurityParams encrypt(int KeySize, String value) { SecurityParams result = null; try { // Get the KeyGenerator final KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(KeySize); // Generate the secret key specs. final SecretKey skey = kgen.generateKey(); final byte[] raw = skey.getEncoded(); final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); final Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); final String key = new Base64().encodeAsString(raw); final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes())); result = new SecurityParams(encrypt, key, KeySize); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:com.frame.Conf.Utilidades.java
/** * // w ww . jav a2 s.com * @param keypass Es la llave plublica para enctriptar el texto * @param texto Texto a encriptar * @return retorna el hash del texto encriptado * @throws Exception */ public String Encriptar(String keypass, String texto) throws Exception { String secretKey = keypass; //llave para encriptar datos String base64EncryptedString = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainTextBytes = texto.getBytes("utf-8"); byte[] buf = cipher.doFinal(plainTextBytes); byte[] base64Bytes = Base64.encodeBase64(buf); base64EncryptedString = new String(base64Bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { throw new Exception(ex.getMessage()); } return base64EncryptedString; }
From source file:net.sf.hajdbc.codec.crypto.CipherCodec.java
/** * {@inheritDoc}// ww w. j av a 2 s .co m * @see net.sf.hajdbc.codec.Codec#encode(java.lang.String) */ @Override public String encode(String value) throws SQLException { try { Cipher cipher = Cipher.getInstance(this.key.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, this.key); return new String(Base64.encodeBase64(cipher.doFinal(value.getBytes()))); } catch (GeneralSecurityException e) { throw new SQLException(e); } }
From source file:com.AES256Util.java
public String aesEncode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes())); byte[] encrypted = c.doFinal(str.getBytes("UTF-8")); String enStr = new String(Base64.encodeBase64(encrypted)); return enStr; }