/* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
public CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorithm) throws IOException, GeneralSecurityException { super(out); // create a new symmetric cipher key used for this stream String keyAlgorithm = getKeyAlgorithm(algorithm); SecretKey symKey = KeyGenerator.getInstance(keyAlgorithm).generateKey(); // place the symmetric key by encrypting it with asymmetric cipher out.write(asym.doFinal(symKey.getEncoded())); // the rest of the data will be encrypted by this symmetric cipher Cipher sym = Secret.getCipher(algorithm); sym.init(Cipher.ENCRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); super.out = new CipherOutputStream(out,sym); }
private byte[] generateKey() throws NoSuchAlgorithmException { KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); byte[] key = keygen.generateKey().getEncoded(); return key; }
/** * @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); }
/** * Gets the encoded session key. * * @return the encoded session key * @throws GeneralSecurityException the general security exception */ public byte[] getEncodedSessionKey() throws GeneralSecurityException { SecretKey key = getSessionKey(); Cipher keyCipher = RSA_CIPHER.get(); keyCipher.init(Cipher.ENCRYPT_MODE, remotePublicKey); return keyCipher.doFinal(key.getEncoded()); }
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); byte encKey[] = CryptoFunctions.generateKey(skey.getEncoded(), hashAlgo, blockKey, 16); SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm()); if (cipher == null) { EncryptionHeader em = encryptionInfo.getHeader(); cipher = CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), null, null, encryptMode); } else { cipher.init(encryptMode, key); } return cipher; }
SecretKey key = KeyGenerator.getInstance("DES").generateKey(); byte[] data = key.getEncoded(); SecretKey key2 = new SecretKeySpec(data, 0, data.length, "DES");
private SecretKey deriveSecretKey() throws GeneralSecurityException { SecretKeyFactory secretKeyFactory; try { if (provider != null) { secretKeyFactory = SecretKeyFactory.getInstance(keyAlgorithm, provider); } else { secretKeyFactory = SecretKeyFactory.getInstance(keyAlgorithm); } } catch (NoSuchAlgorithmException e) { throw log.noSuchKeyAlgorithm(keyAlgorithm, e); } PBEKeySpec pbeKeySpec = keyLength == 0 ? new PBEKeySpec(password, salt, iteration) : new PBEKeySpec(password, salt, iteration, keyLength); SecretKey partialKey = secretKeyFactory.generateSecret(pbeKeySpec); return new SecretKeySpec(partialKey.getEncoded(), transformation); }
/** * Upgrades a connection with transport encryption by the specified symmetric cipher. * * @return * A new {@link Connection} object that includes the transport encryption. */ public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException { Cipher cout = Cipher.getInstance(algorithm); cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherOutputStream o = new CipherOutputStream(out, cout); Cipher cin = Cipher.getInstance(algorithm); cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherInputStream i = new CipherInputStream(in, cin); return new Connection(i,o); }
private SecretKey getKey() { if (key==null) { synchronized (this) { if (key==null) { try { byte[] encoded = load(); if (encoded==null) { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM); SecretKey key = kg.generateKey(); store(encoded=key.getEncoded()); } key = new SecretKeySpec(encoded,ALGORITHM); } catch (IOException e) { throw new Error("Failed to load the key: "+getId(),e); } catch (NoSuchAlgorithmException e) { throw new Error("Failed to load the key: "+getId(),e); } } } } return key; }
import java.nio.file.Files; import java.nio.file.Paths; KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); byte[] encoded = key.getEncoded(); Files.write(Paths.get("target-file"), encoded);
// 1. Generate a session key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128) SecretKey sessionKey = keyGen.generateKey(); // 2. Encrypt the session key with the RSA public key Cipher rsaCipher = Cipher.getInstance("RSA"); rsaCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey) byte[] encryptedSessionKey = rsaCipher.doFinal(sessionKey.getEncoded()); // 3. Encrypt the data using the session key (unencrypted) Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.ENCRYPT_MODE, sessionKey); <-- sessionKey is the unencrypted // session key. // ... use aesCipher to encrypt your data // 4. Save the encrypted data along with the encrypted // session key (encryptedSessionKey). // PLEASE NOTE THAT BECAUSE OF THE ENCRYPTION MODE (CBC), // YOU ALSO NEED TO ALSO SAVE THE IV (INITIALIZATION VECTOR). // aesCipher.aesCipher.getParameters(). // getParametersSpec(IvParameters.class).getIV();
static Cipher cipher(char[] masterPassword, byte[] salt, int cipherMode) throws HttpAuthException { try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec keySpec = new PBEKeySpec(masterPassword, salt, 10000, 128); 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 HttpAuthException("Failed to prepare a cipher instance", e); } }
throw new PulsarClientException.CryptoException(msg); dataKeyCipher.init(Cipher.ENCRYPT_MODE, pubKey); encryptedKey = dataKeyCipher.doFinal(dataKey.getEncoded());
protected static Cipher initCipherForBlock(Cipher cipher, int block, EncryptionInfoBuilder builder, SecretKey skey, int encryptMode) throws GeneralSecurityException { EncryptionVerifier ver = builder.getVerifier(); HashAlgorithm hashAlgo = ver.getHashAlgorithm(); byte blockKey[] = new byte[4]; LittleEndian.putUInt(blockKey, 0, block); byte encKey[] = CryptoFunctions.generateKey(skey.getEncoded(), hashAlgo, blockKey, 16); SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm()); if (cipher == null) { EncryptionHeader em = builder.getHeader(); cipher = CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), null, null, encryptMode); } else { cipher.init(encryptMode, key); } return cipher; }
@Override public byte[] createIV() throws NoSuchAlgorithmException { KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); return keygen.generateKey().getEncoded(); } }
@Override public Encryptor clone() throws CloneNotSupportedException { Encryptor other = (Encryptor)super.clone(); other.secretKey = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm()); // encryptionInfo is set from outside return other; } }
private static byte[] function(char[] password, byte[] salt) { try { PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, HASH_SIZE * Byte.SIZE); return factory.generateSecret(spec).getEncoded(); } catch (InvalidKeySpecException e) { throw new SecurityException(e); } }
public AESDecryptor() { try { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec; spec = new PBEKeySpec(Constants.FRAMEWORK_NAME.toCharArray(), SALT, ITERATIONS, KEY_SIZE); SecretKey tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // CBC = Cipher Block chaining // PKCS5Padding Indicates that the keys are padded cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // For production use commons base64 encoder base64Decoder = new BASE64Decoder(); } catch (Exception e) { throw new RuntimeException("Unable to initialize AESDecryptor", e); } }
private CryptBuf(int mode, SecretKey sharedSecret) throws GeneralSecurityException { cipher = Cipher.getInstance("AES/CFB8/NoPadding"); // NON-NLS cipher.init(mode, sharedSecret, new IvParameterSpec(sharedSecret.getEncoded())); }