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:de.marius_oe.cfs.cryption.Crypter.java
/** * Encrypts the given input stream and stores the encrypted data in the * destinationFile.//w w w .j a va2s .co m * * @param inStream * plain text stream * @param destinationStream * stream for the encrypted data * @param compressStream * whether the data should be compressed before encryption */ public static void encrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) { logger.debug("encrypting inputstream - compressed: {}", compressStream); InputStream tempInputStream; if (compressStream) { logger.debug("Compress InputStream."); tempInputStream = StreamUtils.zipStream(inStream); } else { tempInputStream = inStream; } Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, null); logger.debug("Encrypt InputStream."); tempInputStream = new CipherInputStream(tempInputStream, cipher); try { // write iv to the beginning of the stream destinationStream.write((byte) cipher.getIV().length); destinationStream.write(cipher.getIV()); int bytesCopied = IOUtils.copy(tempInputStream, destinationStream); logger.debug("encryption done. copied {} encrypted bytes to the outputstream", bytesCopied); tempInputStream.close(); destinationStream.close(); } catch (IOException e) { logger.error("Encryption failed - Reason: {}", e.getLocalizedMessage()); throw new RuntimeException(e); } }
From source file:net.alegen.datpass.library.crypto.CryptoManager.java
public EncryptionOutput encrypt(String plaintext, String password) { try {/*from ww w .j a v a2 s .c om*/ // set up the encryption key Random r = new Random(System.currentTimeMillis()); byte[] salt = new byte[50]; r.nextBytes(salt); SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, salt, AES_KEY_LENGTH, DEFAULT_ITERATIONS); salt = Base64.encodeBase64(salt); key = new SecretKeySpec(key.getEncoded(), "AES"); // encrypt plain text with AES using generated key Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); AlgorithmParameters params = cipher.getParameters(); byte[] iv = Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV()); byte[] ciphertext = Base64.encodeBase64(cipher.doFinal(plaintext.getBytes("UTF-8"))); // package output and return return new EncryptionOutput(new String(ciphertext, "UTF-8"), new String(salt, "UTF-8"), new String(iv, "UTF-8")); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidParameterSpecException e) { log.error("An error occured while encrypting the message."); return null; } }
From source file:com.cl.roadshow.crypto.AESCtr.java
/** * Private encryption method.//www . j ava 2 s . co m * * @param keystring * @param message * @param bits * @return bytearray containing encrypted message * @throws Exception */ private static byte[] encrypt(String keystring, String message, int bits) throws Exception { byte[] encValue = null; SecureRandom random = new SecureRandom(); byte[] nonceBytes = new byte[8]; random.nextBytes(nonceBytes); IvParameterSpec nonce = new IvParameterSpec(Arrays.copyOf(nonceBytes, 16)); Key key = generateKey(keystring, bits); Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, key, nonce); byte[] ciphertextWithoutNonce = c.doFinal(message.getBytes("UTF-8")); encValue = Arrays.copyOf(nonceBytes, nonceBytes.length + ciphertextWithoutNonce.length); for (int i = 0; i < ciphertextWithoutNonce.length; i++) { encValue[i + 8] = ciphertextWithoutNonce[i]; } return encValue; }
From source file:eu.europa.ec.markt.dss.signature.token.Pkcs12SignatureToken.java
@Override public byte[] encryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo, DSSPrivateKeyEntry keyEntry) throws NoSuchAlgorithmException { try {//from ww w.jav a 2 s .c om DigestInfo digestInfo = new DigestInfo(digestAlgo.getAlgorithmIdentifier(), digestValue); byte[] infoBytes = digestInfo.getDEREncoded(); Cipher cipher = Cipher.getInstance(keyEntry.getEncryptionAlgorithm().getPadding()); cipher.init(Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry) keyEntry).getPrivateKey()); return cipher.doFinal(infoBytes); } catch (BadPaddingException e) { // More likely the password is not good. throw new BadPasswordException(MSG.PKCS12_BAD_PASSWORD); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java
public byte[] encrypt(byte[] data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = getCipherInstance(); if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) { IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES); cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec); } else {/*from w w w. j a va 2 s .c o m*/ cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes())); } if (jcrypto.isApplyBase64()) { //sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); //return encoder.encode(cipher.doFinal(data)).getBytes(); return Base64.encodeBase64(cipher.doFinal(data)); } else { return cipher.doFinal(data); } }
From source file:eap.util.EDcodeUtil.java
public static String desEncodeAsBase64(String data, String key) { return base64Encode(des(utf8Encode(data), utf8Encode(key), Cipher.ENCRYPT_MODE)); }
From source file:it.doqui.index.ecmengine.business.personalization.encryption.CryptoTransformationSpec.java
public static byte[] generateIv(CryptoTransformationSpec spec, SecretKey key) { logger.debug("[CryptoTransformationSpec::generateIv] BEGIN"); try {/* w w w .j a va2 s . c o m*/ Cipher cipher = null; byte[] iv = null; try { cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(spec), "SunJCE"); } catch (NoSuchProviderException e) { logger.warn("[CryptoTransformationSpec::generateIv] Unknown provider \"SunJCE\". Using default..."); cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(spec)); } cipher.init(Cipher.ENCRYPT_MODE, key); iv = cipher.getIV(); return iv; } catch (NoSuchPaddingException e) { logger.warn("[CryptoTransformationSpec::generateIv] Invalid padding: " + spec.getPadding()); throw new EncryptionRuntimeException("Invalid padding: " + spec.getPadding(), e); } catch (NoSuchAlgorithmException e) { logger.warn("[CryptoTransformationSpec::generateIv] Invalid algorithm: " + spec.getAlgorithm()); throw new EncryptionRuntimeException("Invalid algorithm: " + spec.getAlgorithm(), e); } catch (InvalidKeyException e) { logger.warn("[CryptoTransformationSpec::generateIv] Invalid key!"); throw new EncryptionRuntimeException("Invalid key!", e); } finally { logger.debug("[CryptoTransformationSpec::generateIv] END"); } }
From source file:com.mb.framework.util.SecurityUtil.java
/** * //from w ww . jav a2 s.c o m * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding * * @param String * @return String * @throws Exception */ public static String encryptAESPBKDF2(String plainText) throws Exception { // get salt salt = generateSaltAESPBKDF2(); byte[] saltBytes = salt.getBytes("UTF-8"); // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // encrypt the message Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8")); return new Base64().encodeAsString(encryptedTextBytes); }
From source file:com.anteam.demo.codec.cipher.symmetric.DESTest.java
License:asdf
public byte[] testDESedeEn(String plainText) { try {//from w w w .j a v a 2 s.co m // Create an array to hold the key byte[] encryptKey = "This is a test DESede key".getBytes(); // Create a DESede key spec from the key DESedeKeySpec spec = new DESedeKeySpec(encryptKey); // Get the secret key factor for generating DESede keys SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); // Generate a DESede SecretKey object SecretKey theKey = keyFactory.generateSecret(spec); // Create a DESede Cipher Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); // Create an initialization vector (necessary for CBC mode) IvParameterSpec IvParameters = new IvParameterSpec( new byte[] { 0x01, 0x02, 0x03, 0x04, 0x0F, 0x0E, 0x0D, 0x0C }); // Initialize the cipher and put it into encrypt mode cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters); return cipher.doFinal(plainText.getBytes()); } catch (Exception exc) { exc.printStackTrace(); } return null; }