List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:org.opendatakit.briefcase.export.CipherFactory.java
/** * Return the next {@link Cipher} instance. This method has side-effects and will * change the initialization vector, which will affect the next call to this method. * * @throws CryptoException/*from w w w . j a v a 2 s .c om*/ */ Cipher next() { try { ++ivSeedArray[ivCounter % ivSeedArray.length]; ++ivCounter; IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray); Cipher c = Cipher.getInstance("AES/CFB/PKCS5Padding"); c.init(Cipher.DECRYPT_MODE, symmetricKey, baseIv); return c; } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { throw new CryptoException(e); } }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Method that encrypts data/*from w w w . jav a 2s .com*/ * @param data The data which should be encrypted * @return The encrypted bytes, null if encryption failed * */ public byte[] encrypt(byte[] data) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // cipher.getParameters() seems to return null on Android 4.3 (Bug?) // Solution implemented from here: // https://code.google.com/p/android/issues/detail?id=58191 byte[] iv; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { iv = generateIv(); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvParameterSpec.class).getIV(); } byte[] cipherText = cipher.doFinal(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(iv); outputStream.write(cipherText); return outputStream.toByteArray(); } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidKeyException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidParameterSpecException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (BadPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IOException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidAlgorithmParameterException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } }
From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.EncryptingContentWriterDecorator.java
public OutputStream getContentOutputStream() throws ContentIOException { logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] BEGIN"); IvParameterSpec iv = null;/*ww w .j a v a 2 s .c o m*/ try { Cipher cipher = null; try { cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec), "SunJCE"); } catch (NoSuchProviderException e) { logger.warn( "[EncryptingContentWriterDecorator::getContentOutputStream] Unknown provider \"SunJCE\". Using default..."); cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec)); } if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) { iv = new IvParameterSpec(transformationSpec.getIv()); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] " + "Cipher initialized: ENCRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm()); CipherOutputStream cos = new CipherOutputStream(writer.getContentOutputStream(), cipher); return cos; } catch (NoSuchPaddingException e) { logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid padding: " + transformationSpec.getPadding()); throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e); } catch (NoSuchAlgorithmException e) { logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm: " + transformationSpec.getAlgorithm()); throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e); } catch (InvalidKeyException e) { logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid key!"); throw new EncryptionRuntimeException("Invalid key!", e); } catch (InvalidAlgorithmParameterException e) { logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm parameter: " + iv); throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e); } finally { logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] END"); } }
From source file:net.seleucus.wsp.crypto.FwknopSymmetricCrypto.java
public static String encrypt(byte[] key, String message) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecureRandom sr = new SecureRandom(); byte[] salt = new byte[8]; sr.nextBytes(salt);//from w ww. jav a 2 s.co m byte[][] key_and_iv = deriveKeyAndIV(salt, key); SecretKeySpec enc_key; enc_key = new SecretKeySpec(key_and_iv[0], "AES"); Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(key_and_iv[1]); aes.init(Cipher.ENCRYPT_MODE, enc_key, iv); byte[] salted = "Salted__".getBytes("UTF-8"); byte[] cipher = aes.doFinal(message.getBytes("UTF-8")); byte[] result = new byte[salted.length + salt.length + cipher.length]; // now we need to glue: "Salted__" + salt + cipher System.arraycopy(salted, 0, result, 0, salted.length); System.arraycopy(salt, 0, result, salted.length, salt.length); System.arraycopy(cipher, 0, result, salted.length + salt.length, cipher.length); // remove = and FWKNOP_ENCRYPTION_HEADER return Base64.encodeBase64String(result).replace("=", "").replace(FWKNOP_ENCRYPTION_HEADER, ""); }
From source file:org.apigw.commons.crypto.ApigwCrypto.java
/** * * @return IvParameterSpec of the global salt to be used for encryption/decryption *///from ww w . ja va 2s . c o m protected IvParameterSpec getIvParameterSpec() { return new IvParameterSpec(salt); }
From source file:tor.TorCrypto.java
/** * Tor Hybrid Encrypt function//from ww w . j a v a2 s .co m * * @param in Data to encrypt * @param pk Onion Router public key to encrypt to * @return Encrypted data */ public static byte[] hybridEncrypt(byte[] in, PublicKey pk) { try { Cipher rsa = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC"); rsa.init(Cipher.ENCRYPT_MODE, pk); if (in.length < PK_ENC_LEN - PK_PAD_LEN) { return rsa.doFinal(in); } else { // prep key and IV byte[] key = new byte[KEY_LEN]; rnd.nextBytes(key); byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; SecretKeySpec keysp = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); // prepare m1 byte m1a[] = Arrays.copyOfRange(in, 0, PK_ENC_LEN - PK_PAD_LEN - KEY_LEN); byte m1[] = ArrayUtils.addAll(key, m1a); byte rsaciphertext[] = rsa.doFinal(m1); // prepare m2 byte m2[] = Arrays.copyOfRange(in, m1a.length, in.length); Cipher aes = Cipher.getInstance("AES/CTR/NoPadding"); aes.init(Cipher.ENCRYPT_MODE, keysp, ivSpec); byte aesciphertext[] = aes.doFinal(m2); // merge return ArrayUtils.addAll(rsaciphertext, aesciphertext); } } catch (BadPaddingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } }
From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java
public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) { SecretKey tempKey = null;/* w w w.j a va 2 s. c o m*/ IvParameterSpec tempIvSpec = null; if (encrySrvConfig.getEncryptSalt() == null) { throw new IllegalArgumentException( "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString()); } if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) { LOG.debug("Set the Encryption service password and encrypt salt"); String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true); final Random random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); String encodedSalt = Base64.getEncoder().encodeToString(salt); encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd) .setEncryptSalt(encodedSalt).build(); updateEncrySrvConfig(newPwd, encodedSalt); initializeConfigDataTree(encrySrvConfig, dataBroker); } final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt()); try { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod()); final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt, encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength()); tempKey = keyFactory.generateSecret(spec); tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType()); tempIvSpec = new IvParameterSpec(enryptionKeySalt); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { LOG.error("Failed to initialize secret key", e); } key = tempKey; ivspec = tempIvSpec; Cipher cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.ENCRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create encrypt cipher.", e); } this.encryptCipher = cipher; cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.DECRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create decrypt cipher.", e); } this.decryptCipher = cipher; }
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static List<SecurityKeyData> loadUserKeys(AuthInfo userData, String challengeStoreAttribute, String encyrptionKeyName) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Attribute challengeAttr = userData.getAttribs().get(challengeStoreAttribute); Type t = new TypeToken<List<KeyHolder>>() { }.getType();//from w ww. ja v a 2 s .c o m ArrayList<SecurityKeyData> devices = new ArrayList<SecurityKeyData>(); if (challengeAttr != null) { SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName); if (key == null) { throw new Exception("Queue message encryption key not found"); } EncryptedMessage msg = gson.fromJson(inflate(challengeAttr.getValues().get(0)), EncryptedMessage.class); IvParameterSpec spec = new IvParameterSpec(msg.getIv()); Cipher cipher; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, spec); byte[] bytes = cipher.doFinal(msg.getMsg()); String json = new String(bytes); java.util.List<KeyHolder> fromJSON = gson.fromJson(json, t); for (KeyHolder kh : fromJSON) { devices.add(new SecurityKeyData(kh.getEnrollmentTime(), kh.getKeyHandle(), kh.getPublicKey(), null, kh.getCounter())); } } return devices; }
From source file:com.fujitsu.dc.common.auth.token.LocalToken.java
/** * ??./*from w w w. j a v a 2 s. c o m*/ * @param in * @param ivBytes * @return ??? */ public static String encode(final String in, final byte[] ivBytes) { // IV??CELL?URL?????? Cipher cipher; try { cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING); cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(ivBytes)); byte[] cipherBytes = cipher.doFinal(in.getBytes(CharEncoding.UTF_8)); return DcCoreUtils.encodeBase64Url(cipherBytes); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:io.personium.common.auth.token.LocalToken.java
/** * ??.// ww w .ja v a2s . com * @param in * @param ivBytes * @return ??? */ public static String encode(final String in, final byte[] ivBytes) { // IV??CELL?URL?????? Cipher cipher; try { cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING); cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(ivBytes)); byte[] cipherBytes = cipher.doFinal(in.getBytes(CharEncoding.UTF_8)); return PersoniumCoreUtils.encodeBase64Url(cipherBytes); } catch (Exception e) { throw new RuntimeException(e); } }