List of usage examples for javax.crypto Cipher getParameters
public final AlgorithmParameters getParameters()
From source file:adminpassword.Encryption.java
public String encrypt(String word, String idKey) throws Exception { byte[] ivBytes; String password = idKey; //you can give whatever you want. This is for testing purpose SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes);//from w w w . ja va 2 s . co m byte[] saltBytes = bytes; // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); //encrypting the word Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8")); //prepend salt and vi byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length]; System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length); System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length); System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length); return new Base64().encodeToString(buffer); }
From source file:adminpassword.AESDemo.java
public String encrypt(String plainText) throws Exception { //get salt/*from w w w . ja va 2 s. co m*/ salt = generateSalt(); byte[] saltBytes = salt.getBytes("UTF-8"); // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(password.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"); 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:ai.serotonin.backup.Backup.java
private File encryptFile(final File file) throws Exception { final SecureRandom random = new SecureRandom(); final byte[] salt = random.generateSeed(8); final String saltStr = Hex.encodeHexString(salt); final SecretKey secret = createSecretKey(salt); final Cipher cipher = createCipher(); cipher.init(Cipher.ENCRYPT_MODE, secret); final AlgorithmParameters params = cipher.getParameters(); final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); final String ivStr = Hex.encodeHexString(iv); final File encryptedFile = new File(file.getParent(), saltStr + "_" + ivStr + "_" + file.getName()); cipherizeFile(file, encryptedFile, cipher); file.delete();//w w w .j a v a 2 s . c o m LOG.info("Encrypted backup file to " + encryptedFile.getPath() + ", " + FileUtils.byteCountToDisplaySize(encryptedFile.length())); return encryptedFile; }
From source file:org.mayocat.security.DefaultCipher.java
private String crypt(String input, Mode mode) throws EncryptionException { if (Strings.isNullOrEmpty(this.configuration.getEncryptionKey())) { throw new EncryptionException("Invalid or missing cookie encryption key in configuration file. " + "You MUST specify a key in order to support cookie authentication."); }/*from w ww . j a va2s . co m*/ try { byte[] in = input.getBytes(); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); byte[] keyBytes = this.configuration.getEncryptionKey().getBytes("UTF-8"); DESKeySpec desKeySpec = new DESKeySpec(keyBytes); SecretKey key = keyFactory.generateSecret(desKeySpec); javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); IvParameterSpec spec = null; if (cipher.getParameters() != null) { spec = cipher.getParameters().getParameterSpec(IvParameterSpec.class); } switch (mode) { case CRYPT: default: if (spec != null) { cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, spec); } else { cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key); } byte[] encrypted = cipher.doFinal(in); return new String(Base64.encodeBase64(encrypted)); case DECRYPT: if (spec != null) { cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, spec); } else { cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key); } byte[] decrypted = cipher.doFinal(Base64.decodeBase64(in)); return new String(decrypted); } } catch (BadPaddingException e) { this.logger.warn("Bad padding when attempting to decipher cookies. Key changed ?"); throw new EncryptionException(e); } catch (Exception e) { this.logger.error("Fail to perform cookie crypt or decrypt operation", e); throw new EncryptionException(e); } }
From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java
/** * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created * //www .j ava 2 s . c om * @param value * - value to be encrypted * @throws GeneralSecurityException * - security exception * @return Encrypted value */ @Override public String encrypt(String value) throws GeneralSecurityException { if (!keyFile.exists()) { KeyGenerator keyGen = KeyGenerator.getInstance(AES); keyGen.init(KEY_SIZE); SecretKey sk = keyGen.generateKey(); FileWriter fw = null; try { fw = new FileWriter(keyFile); fw.write(byteArrayToHexString(sk.getEncoded())); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } SecretKeySpec sks = getSecretKeySpec(); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); byte[] encrypted = cipher.doFinal(value.getBytes()); return byteArrayToHexString(encrypted); }
From source file:com.mtramin.rxfingerprint.FingerprintEncryptionObservable.java
@Override protected void onAuthenticationSucceeded(AsyncEmitter<FingerprintEncryptionResult> emitter, FingerprintManagerCompat.AuthenticationResult result) { try {// w w w . j a v a 2s . c o m Cipher cipher = result.getCryptoObject().getCipher(); byte[] encryptedBytes = cipher.doFinal(toEncrypt.getBytes("UTF-8")); byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); CryptoData cryptoData = CryptoData.fromBytes(encryptedBytes, ivBytes); emitter.onNext( new FingerprintEncryptionResult(FingerprintResult.AUTHENTICATED, null, cryptoData.toString())); emitter.onCompleted(); } catch (IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException | UnsupportedEncodingException e) { emitter.onError(e); } }
From source file:org.eclipse.che.api.crypt.server.JCEEncryptTextService.java
@Override public EncryptResult encryptText(final String textToEncrypt) throws EncryptException { byte[] ivBlob; byte[] cipherBlob; try {/*from www. j a v a2s. c om*/ final SecretKey secret = generateSecret(); final Cipher cipher = Cipher.getInstance(this.transformation); cipher.init(Cipher.ENCRYPT_MODE, secret); final AlgorithmParameters params = cipher.getParameters(); ivBlob = params.getParameterSpec(IvParameterSpec.class).getIV(); cipherBlob = cipher.doFinal(textToEncrypt.getBytes("UTF-8")); } catch (final InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidParameterSpecException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { throw new EncryptException(e); } final String cipherText = Base64.encodeBase64String(cipherBlob); final String ivText = Base64.encodeBase64String(ivBlob); return new EncryptResult(cipherText, ivText); }
From source file:net.alegen.datpass.library.crypto.CryptoManager.java
public EncryptionOutput encrypt(String plaintext, String password) { try {//from ww w . jav a 2 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:org.alfresco.util.encryption.impl.AES256PasswordBasedEncrypter.java
/** * @see org.alfresco.util.encryption.Encrypter#encrypt(byte[]) *//*from w ww.jav a 2s . c om*/ @Override public String encrypt(final String clearText) { String result = null; long start = -1; long end = -1; if (log.isDebugEnabled()) start = System.nanoTime(); if (clearText != null) { try { Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); byte[] iv = null; byte[] cipherText = null; cipher.init(Cipher.ENCRYPT_MODE, secretKey); iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); cipherText = cipher.doFinal(clearText.getBytes(CHARACTER_ENCODING)); byte[] ivBase64 = Base64.encodeBase64(iv); byte[] cipherTextBase64 = Base64.encodeBase64(cipherText); String intermediate = (new String(ivBase64)) + SEPARATOR + (new String(cipherTextBase64)); byte[] encrypted = Base64.encodeBase64(intermediate.getBytes(CHARACTER_ENCODING)); result = new String(encrypted, CHARACTER_ENCODING); } catch (final RuntimeException re) { throw re; } catch (final Exception e) { // Convert checked exceptions to unchecked, as they're Pure Evil throw new RuntimeException(e); } } if (log.isDebugEnabled()) { end = System.nanoTime(); long diff = end - start; double diffInMs = (double) diff / 1000000; log.debug("Encryption took " + String.valueOf(diffInMs) + "ms"); } return (result); }
From source file:org.alfresco.encryption.AbstractEncryptor.java
/** * {@inheritDoc}/*from w ww .j ava 2 s. com*/ */ @Override public Pair<byte[], AlgorithmParameters> encrypt(String keyAlias, AlgorithmParameters params, byte[] input) { Cipher cipher = getCipher(keyAlias, params, Cipher.ENCRYPT_MODE); if (cipher == null) { return new Pair<byte[], AlgorithmParameters>(input, null); } try { byte[] output = cipher.doFinal(input); params = cipher.getParameters(); return new Pair<byte[], AlgorithmParameters>(output, params); } catch (Throwable e) { // cipher.init(Cipher.ENCRYPT_MODE, key, params); throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e); } }