private byte[] aes(byte[] data, byte[] key, byte[] iv, int mode) throws Exception { Cipher cipher = Cipher.getInstance(AES_MODE); cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); return cipher.doFinal(data); }
public static byte[] encrypt(byte[] data, IvParameterSpec zeroIv, SecretKeySpec keySpec) { try { Profiler.enter("time cost on [aes encrypt]: data length=" + data.length); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING); cipher.init(Cipher.ENCRYPT_MODE, keySpec, zeroIv); return cipher.doFinal(data); } catch (Exception e) { LOGGER.error("AES encrypt ex, iv={}, key={}", Arrays.toString(zeroIv.getIV()), Arrays.toString(keySpec.getEncoded()), e); throw new CryptoException("AES encrypt ex", e); } finally { Profiler.release(); } }
@Inject public CookieEncryption(NinjaProperties properties) { Optional<SecretKeySpec> secretKeySpec = Optional.empty(); if (properties.getBooleanWithDefault(NinjaConstant.applicationCookieEncrypted, false)) { String secret = properties.getOrDie(NinjaConstant.applicationSecret); try { int maxKeyLengthBits = Cipher.getMaxAllowedKeyLength(ALGORITHM); if (maxKeyLengthBits == Integer.MAX_VALUE) { maxKeyLengthBits = 256; } secretKeySpec = Optional.of( new SecretKeySpec(secret.getBytes(), 0, maxKeyLengthBits / Byte.SIZE, ALGORITHM)); logger.info("Ninja session encryption is using {} / {} bit.", secretKeySpec.get().getAlgorithm(), maxKeyLengthBits); } catch (Exception exception) { logger.error("Can not create class to encrypt cookie.", exception); throw new RuntimeException(exception); } } this.secretKeySpec = secretKeySpec; }
try { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(ENCODE_RULES.getBytes()); keygen.init(128, random); SecretKey originalKey = keygen.generateKey(); byte[] raw = originalKey.getEncoded(); SecretKey key = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] byteDecode = cipher.doFinal(byteContent); String aesDecode = new String(byteDecode, "utf-8"); return aesDecode;
byte[] iv = new byte[cipher.getBlockSize()]; new SecureRandom().nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(keyString.getBytes()); byte[] key = new byte[16]; System.arraycopy(digest.digest(), 0, key, 0, key.length); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8")); System.out.println("encrypted: " + new String(encrypted));
protected static Cipher initCipherForBlock(Cipher cipher, int block, EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode) throws GeneralSecurityException { EncryptionVerifier ver = encryptionInfo.getVerifier(); HashAlgorithm hashAlgo = ver.getHashAlgorithm(); byte blockKey[] = new byte[4]; LittleEndian.putUInt(blockKey, 0, block); MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo); hashAlg.update(skey.getEncoded()); byte encKey[] = hashAlg.digest(blockKey); EncryptionHeader header = encryptionInfo.getHeader(); int keyBits = header.getKeySize(); encKey = CryptoFunctions.getBlock0(encKey, keyBits / 8); if (keyBits == 40) { encKey = CryptoFunctions.getBlock0(encKey, 16); } SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm()); if (cipher == null) { cipher = CryptoFunctions.getCipher(key, header.getCipherAlgorithm(), null, null, encryptMode); } else { cipher.init(encryptMode, key); } return cipher; }
public EncryptionResult encrypt(byte[] plain) throws Exception { byte[] salt = new byte[saltSize]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(salt); SecretKey tmp = getKeyFromPassword(new String(passPhrase), salt); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), alg); Cipher ecipher = Cipher.getInstance(transformation); ecipher.init(Cipher.ENCRYPT_MODE, secret); return new EncryptionResult(salt, ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(), ecipher.doFinal(plain)); }
private Cipher createCipher(byte[] salt, final int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { digest.reset(); digest.update(pwdAsBytes); digest.update(salt, 0, 8); result = digest.digest(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
secretKey = new SecretKeySpec(passwordKey, CIPHER_ALGORITHM); ivParameterSpec = new IvParameterSpec(rawSecretKey); MessageDigest digest; try { digest = MessageDigest.getInstance(MESSAGEDIGEST_ALGORITHM); return digest.digest(text.getBytes()); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "No such algorithm " + MESSAGEDIGEST_ALGORITHM, e);
new SecureRandom().nextBytes(iv); jnlpMac = JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(slaveName.getBytes("UTF-8")); SecretKey key = new SecretKeySpec(jnlpMac, 0, /* export restrictions */ 128 / 8, "AES"); byte[] encrypted; try { Cipher c = Secret.getCipher("AES/CFB8/NoPadding"); c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); encrypted = c.doFinal(csos.getBytes()); } catch (GeneralSecurityException x) { throw new IOException(x);
hmacKey = digest.digest(key.toArray()); } else { key.append(format == FORMAT.CLIENT ? SERVER_MAGIC_CONFIDENTIALITY : CLIENT_MAGIC_CONFIDENTIALITY); hmacKey = digest.digest(key.toArray()); throw saslDigest.mechUnknownCipher(cipher).toSaslException(); ciph = Cipher.getInstance(transformationSpec.getTransformation()); int slash = ciph.getAlgorithm().indexOf('/'); String alg = (slash > -1 ? ciph.getAlgorithm().substring(0, slash) : ciph.getAlgorithm()); cipherKey = new SecretKeySpec(cipherKeyBytes, alg); } else if (cipher.equals("des")) { cipherKeyBytes = Arrays.copyOf(hmacKey, 7); // first 7 bytes ciph.init((wrap ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), cipherKey, new IvParameterSpec(IV), secureRandomGenerator); } else { ciph.init((wrap ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), cipherKey, secureRandomGenerator);
private SecretKey generateKey() { SecureRandom r = new SecureRandom(); byte[] keyBytes = new byte[16]; r.nextBytes(keyBytes); return new SecretKeySpec(keyBytes, "AES"); }
SecureRandom rnd = new SecureRandom(); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); rnd.nextBytes(encryptionKey); byte[] userValidationSalt = new byte[8]; byte[] userKeySalt = new byte[8]; rnd.nextBytes(userValidationSalt); rnd.nextBytes(userKeySalt); byte[] hashU = computeHash2B(concat(userPasswordBytes, userValidationSalt), cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashUE, "AES"), new IvParameterSpec(new byte[16])); byte[] ue = cipher.doFinal(encryptionKey); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashOE, "AES"), new IvParameterSpec(new byte[16])); byte[] oe = cipher.doFinal(encryptionKey); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new IvParameterSpec(new byte[16])); byte[] permsEnc = cipher.doFinal(perms);
public TurnToken generate() { try { Mac mac = Mac.getInstance("HmacSHA1"); long validUntilSeconds = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) / 1000; long user = Math.abs(new SecureRandom().nextInt()); String userTime = validUntilSeconds + ":" + user; mac.init(new SecretKeySpec(key, "HmacSHA1")); String password = Base64.encodeBytes(mac.doFinal(userTime.getBytes())); return new TurnToken(userTime, password, urls); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError(e); } } }
private static Cipher cipher(char[] masterPassword, byte[] salt, int cipherMode) throws ConfigEncryptionException { try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec keySpec = new PBEKeySpec(masterPassword, salt, HASH_ITERATIONS, KEY_LENGTH); SecretKeySpec spec = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(cipherMode, spec, new IvParameterSpec(salt)); return cipher; } catch (Exception e) { throw new ConfigEncryptionException("Failed to prepare a cipher instance", e); } }
/** * @param keyLength * Block size of the asymmetric cipher, in bits. I thought I can get it from {@code asym.getBlockSize()} * but that doesn't work with Sun's implementation. */ public CombinedCipherInputStream(InputStream in, Cipher asym, String algorithm, int keyLength) throws IOException, GeneralSecurityException { super(in); String keyAlgorithm = getKeyAlgorithm(algorithm); // first read the symmetric key cipher byte[] symKeyBytes = new byte[keyLength/8]; new DataInputStream(in).readFully(symKeyBytes); SecretKey symKey = new SecretKeySpec(asym.doFinal(symKeyBytes),keyAlgorithm); // the rest of the data will be decrypted by this symmetric cipher Cipher sym = Secret.getCipher(algorithm); sym.init(Cipher.DECRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); super.in = new CipherInputStream(in,sym); }
private ByteString hmac(String algorithm, ByteString key) { try { Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.toByteArray(), algorithm)); return ByteString.of(mac.doFinal(data)); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } catch (InvalidKeyException e) { throw new IllegalArgumentException(e); } }
public PBKDF2Encryptor(final String passPhrase, final byte[] salt, final int iterationCount, final int i1) { this.iterationCount = iterationCount; try { // create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, i1); SecretKey tmp = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // encryptor ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ecipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = ecipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); // decryptor dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); } catch (Exception ex) { throw new IllegalArgumentException(ex); } }
} else if (rfile.length() == 0L) { new SecureRandom().nextBytes(iv); rfile.write(iv); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv)); lastBlock = cipher.doFinal(lastBlockEnc); rfile.seek(rfile.length()-16); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv)); byte[] out; if (lastBlock != null) { // lastBlock is null if we're starting a new file }; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv)); byte[] buff = new byte[1<<13]; //8kiB while (true) {
private static Mac initMac(byte[] key) { // Java forbids empty keys if (key.length == 0) { key = new byte[1]; } try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return mac; } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }