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:com.fegor.alfresco.security.crypto.Crypto.java
/** * Encryption configuration//from w w w .jav a 2 s. c om * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; salt_pos = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(salt_pos); if (logger.isDebugEnabled()) logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]"); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files * .shtml */ KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); eCipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = eCipher.getParameters(); vector_init = params.getParameterSpec(IvParameterSpec.class).getIV(); if (logger.isDebugEnabled()) logger.debug( this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]"); }
From source file:com.fengduo.bee.commons.security.EncryptBuilder.java
public String encrypt(String source, String secretKey) { if (StringUtils.isEmpty(source) || StringUtils.isEmpty(secretKey)) { return null; }/*from w w w . j a v a 2s . co m*/ if (secretKey.length() != 16) { logger.error("Key?16?"); return null; } try { return Base64.encode(doCrypt(source, secretKey, new ICrypt() { @Override public void initCipher(SecretKey key, SecureRandom sr, Cipher cipher) throws InvalidKeyException { cipher.init(Cipher.ENCRYPT_MODE, key, sr); } @Override public byte[] getCryptedData(String source) { return source.getBytes(); } })); } catch (Exception e) { String info = source + "\r\n" + ExceptionUtils.getFullStackTrace(e); logger.error(info); } return null; }
From source file:at.tfr.securefs.util.Main.java
public void parseOpts(String[] args) throws Exception { List<String> argList = Arrays.asList(args); Iterator<String> iter = argList.iterator(); if (args.length == 0) { System.out.println("Usage: [options] <file>"); System.out.println("<file>: file to use for de/encryption"); System.out.println("Options:"); System.out.println("\t-t\tTest using test key with file"); System.out.println("\t-d\tdecrypt file with test key - default"); System.out.println("\t-e\tencrypt file with test key"); System.out.println("\t-s <salt> \tsalt - default: use file name"); System.out.println("\t-b <path> \base path for file access, default use ClassLoader roots"); System.out.println("\t-o <outFile> \tfile to write to, relative to basePath"); System.exit(0);//from ww w.j av a 2 s. co m } while (iter.hasNext()) { String a = iter.next(); switch (a) { case "-t": test = true; break; case "-d": mode = Cipher.DECRYPT_MODE; break; case "-e": mode = Cipher.ENCRYPT_MODE; break; case "-s": configuration.setSalt(iter.next()); break; case "-b": basePath = new File(iter.next()).toPath(); break; case "-o": outFile = iter.next(); break; default: file = a; } } if (file == null) throw new FileNotFoundException("no file defined"); if (basePath == null) { URL resource = this.getClass().getResource("/" + file); if (resource == null) throw new FileNotFoundException("cannot find basePath for file: " + file); URI uri = resource.toURI(); String absolutePath = new File(uri).getAbsolutePath(); basePath = new File(absolutePath).getParentFile().toPath(); } }
From source file:com.waveerp.desEncryption.java
public String encrypt(String value) { try {// w w w. jav a 2 s . c o m Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE"); ecipher.init(Cipher.ENCRYPT_MODE, sKey, ivParSpec); if (value == null) return null; byte[] utf8 = value.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new String(Base64.encodeBase64(enc), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:hudson.model.UsageStatistics.java
private Cipher getCipher() { try {/*w w w . j a v a 2s . c o m*/ if (key == null) { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); key = keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage))); } Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher; } catch (GeneralSecurityException e) { throw new Error(e); // impossible } }
From source file:com.joyent.manta.util.CipherClonerTest.java
private void canCloneCipher(final SupportedCipherDetails cipherDetails) throws Exception { final SecretKey secretKey = SecretKeyUtils.generate(cipherDetails); final byte[] iv = cipherDetails.generateIv(); final byte[] inputData = RandomUtils.nextBytes(cipherDetails.getBlockSizeInBytes() * 3); // notice we are specifically calling getBouncyCastleCipher() final Cipher originalCipher = cipherDetails.getBouncyCastleCipher(); originalCipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv)); final Cipher clonedCipher = new CipherCloner().createClone(originalCipher); final ByteArrayOutputStream originalOutput = new ByteArrayOutputStream(); final CipherOutputStream originalCipherOutput = new CipherOutputStream(originalOutput, originalCipher); originalCipherOutput.write(inputData); originalCipherOutput.flush();/*w w w.j av a2s.co m*/ // we don't want to close originalCipherOutput because that would finalize originalCipher // and allow it to be reused below final ByteArrayOutputStream clonedOutput = new ByteArrayOutputStream(); final CipherOutputStream clonedCipherOutput = new CipherOutputStream(clonedOutput, clonedCipher); clonedCipherOutput.write(inputData); clonedCipherOutput.flush(); final byte[] originalEncrypted = originalOutput.toByteArray(); final byte[] clonedEncrypted = clonedOutput.toByteArray(); Assert.assertEquals(originalEncrypted.length, clonedEncrypted.length); AssertJUnit.assertArrayEquals(originalEncrypted, clonedEncrypted); }
From source file:im.whistle.crypt.Crypt.java
/** * Encrypts a message.//from ww w . jav a 2 s .c o m * @param args Arguments: data, publicKey[, privateKey] * @param callback Callback */ public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { PRNGProvider.init(); // Ensure OpenSSL fix // Get the arguments String data = args.getString(0); String pub = args.getString(1); String priv = null; if (args.length() == 3) { priv = args.getString(2); } String sig = null; // Convert everything into byte arrays byte[] dataRaw = data.getBytes("utf-8"); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); // Generate random AES key and IV byte[] aesKey = new byte[AES_BYTES]; new SecureRandom().nextBytes(aesKey); byte[] aesIv = new byte[16]; // Block size new SecureRandom().nextBytes(aesIv); Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); // Encrypt data with AES byte[] encData = c.doFinal(dataRaw); // Encrypt aes data with RSA X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec)); c.update(aesKey); c.update(aesIv); byte[] encKey = c.doFinal(); // Concatenate and transform byte[] encRaw = new byte[encKey.length + encData.length]; System.arraycopy(encKey, 0, encRaw, 0, encKey.length); System.arraycopy(encData, 0, encRaw, encKey.length, encData.length); encKey = null; encData = null; String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8"); // Sign if (priv != null) { // Fail on error (no try-catch) byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initSign(kf.generatePrivate(privateKeySpec)); s.update(encRaw); sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8"); } JSONArray res = new JSONArray(); res.put(enc); res.put(sig); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex); callback.error(ex); } }
From source file:com.shenit.commons.codec.DesUtils.java
/** * /*from w w w . j a v a 2 s . c om*/ * * @param rawKeyData * @param slat * @param secure * ?SecureRandom? * @return */ public static byte[] encrypt(byte[] rawData, byte[] rawKey) { return crypt(rawData, rawKey, Cipher.ENCRYPT_MODE); }
From source file:com.boylesoftware.web.impl.auth.CipherToolbox.java
/** * Encrypt specified authentication data into a Base64 cookie value. * * @param userId User id./*from w w w .j av a 2 s . c o m*/ * @param salt Salt. * * @return Encrypted value as a Base64 encoded string. */ String encrypt(final int userId, final int salt) { this.clearBuf.clear(); this.clearBuf.putInt(salt).putLong(RAND.nextLong()).putInt(userId).putLong(RAND.nextLong()) .putLong(System.currentTimeMillis()); this.clearBuf.flip(); this.cipherBuf.clear(); try { this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey); this.cipher.doFinal(this.clearBuf, this.cipherBuf); } catch (final GeneralSecurityException e) { throw new RuntimeException("Error encrypting authentication cookie.", e); } this.cipherBuf.flip(); this.base64Buf.clear(); Base64.encode(this.cipherBuf, this.base64Buf); this.base64Buf.flip(); return this.base64Buf.toString(); }
From source file:dualcontrol.CryptoHandler.java
private void cipher(String mode, String alias, String transformation, String ivString, String dataString) throws Exception { logger.debug(join("cipher", alias, transformation, mode)); SecretKey key = dualControl.loadKey(alias); logger.debug("keyalg " + key.getAlgorithm()); Cipher cipher = Cipher.getInstance(transformation); logger.debug("mode " + mode); if (mode.equals("DECRYPT")) { this.ivBytes = Base64.decodeBase64(ivString); logger.debug("iv " + Base64.encodeBase64String(ivBytes)); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); this.dataBytes = cipher.doFinal(Base64.decodeBase64(dataString)); write(ivBytes, dataBytes);/*from ww w. ja va 2 s . co m*/ } else if (mode.equals("ENCRYPT")) { this.ivBytes = getIvBytes(ivString); logger.debug("iv " + Base64.encodeBase64String(ivBytes)); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); long startTime = System.nanoTime(); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); this.dataBytes = cipher.doFinal(dataString.getBytes()); logger.info("encrypt time nanos " + Nanos.elapsed(startTime)); write(ivBytes, dataBytes); } }