kgen = KeyGenerator.getInstance("AES"); kgen.init(256); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); cipher.doFinal("This is just an example".getBytes()); strongEncryptionAvaialble = true; LOGGER.info("Strong cryptography is available");
@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; } }
@Override public String getFormat() { return secretKey.getFormat(); }
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); } }
public static byte[] salting(String pass, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { final int iterations = 500; final int keyLength = 512; final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final PBEKeySpec spec = new PBEKeySpec(pass.toCharArray(), salt, iterations, keyLength); final SecretKey key = skf.generateSecret(spec); final byte[] tmp = key.getEncoded(); return tmp; }
private byte[] generateKey() throws NoSuchAlgorithmException { KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); byte[] key = keygen.generateKey().getEncoded(); return key; }
rsaCipher = Cipher.getInstance("RSA"); // NON-NLS } catch (GeneralSecurityException ex) { ConsoleMessages.Error.Net.Crypt.RSA_INIT_FAILED.log(ex); rsaCipher.init(Cipher.DECRYPT_MODE, privateKey); sharedSecret = new SecretKeySpec(rsaCipher.doFinal(message.getSharedSecret()), "AES"); // NON-NLS } catch (Exception ex) { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(session.getSessionId().getBytes()); digest.update(sharedSecret.getEncoded()); digest.update(session.getServer().getKeyPair().getPublic().getEncoded());
/** * 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 Cipher createCipher(int opmode, char[] password, byte[] salt, byte[] iv) throws GeneralSecurityException { PBEKeySpec keySpec = new PBEKeySpec(password, salt, KDF_ITERS, CIPHER_KEY_BITS); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KDF_ALGO); SecretKey secretKey = keyFactory.generateSecret(keySpec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), CIPHER_ALGO); GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_BITS, iv); Cipher cipher = Cipher.getInstance(CIPHER_ALGO + "/" + CIPHER_MODE + "/" + CIPHER_PADDING); cipher.init(opmode, secret, spec); cipher.updateAAD(salt); return cipher; }
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; }
/** * @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); }
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); }
try { KeyGenerator gen = KeyGenerator.getInstance("AES"); gen.init(128); SecretKey key = gen.generateKey(); byte[] keyBytes = key.getEncoded(); System.out.print("Ge nyckeln ett filnamn: "); String filename = scan.next(); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv); ecipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv); c.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object byte[] b = baos.toByteArray(); byte[] keyStart = "this is a key".getBytes(); KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(keyStart); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] key = skey.getEncoded(); // encrypt byte[] encryptedData = encrypt(key,b); // decrypt byte[] decryptedData = decrypt(key,encryptedData);
// 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();
private void saveSecretKey(String ksAlias, ObjectOutputStream oos, KeyStore.SecretKeyEntry entry) throws IOException, GeneralSecurityException { ByteArrayOutputStream entryData = new ByteArrayOutputStream(1024); ObjectOutputStream entryOos = new ObjectOutputStream(entryData); entryOos.writeUTF(ksAlias); writeBytes(entry.getSecretKey().getEncoded(), entryOos); entryOos.flush(); encrypt.init(Cipher.ENCRYPT_MODE, storageSecretKey, (AlgorithmParameterSpec) null); // ELY-1308: third param need to workaround BouncyCastle bug int blockSize = encrypt.getBlockSize(); if (blockSize == 0) throw log.algorithmNotBlockBased(encrypt.getAlgorithm()); Assert.checkMaximumParameter("cipher block size", 256, blockSize); byte[] padded = pkcs7Pad(entryData.toByteArray(), blockSize); byte[] encrypted = encrypt.doFinal(padded); byte[] iv = encrypt.getIV(); if (iv == null) throw log.algorithmNotIV(encrypt.getAlgorithm()); oos.writeInt(SECRET_KEY_ENTRY_TYPE); writeBytes(encrypted, oos); writeBytes(iv, oos); }
/** * 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 existing, int block, boolean lastChunk, EncryptionInfoBuilder builder, SecretKey skey, int encryptionMode) throws GeneralSecurityException { EncryptionHeader header = builder.getHeader(); if (existing == null || lastChunk) { String padding = (lastChunk ? "PKCS5Padding" : "NoPadding"); existing = getCipher(skey, header.getCipherAlgorithm(), header.getChainingMode(), header.getKeySalt(), encryptionMode, padding); } byte[] blockKey = new byte[4]; LittleEndian.putInt(blockKey, 0, block); byte[] iv = generateIv(header.getHashAlgorithmEx(), header.getKeySalt(), blockKey, header.getBlockSize()); AlgorithmParameterSpec aps; if (header.getCipherAlgorithm() == CipherAlgorithm.rc2) { aps = new RC2ParameterSpec(skey.getEncoded().length*8, iv); } else { aps = new IvParameterSpec(iv); } existing.init(encryptionMode, skey, aps); return existing; }
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; }
public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator, CipherAlgorithm alg) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256); SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec); this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES"); this.alg = alg; this.encryptor = alg.createCipher(); this.decryptor = alg.createCipher(); this.ivGenerator = ivGenerator != null ? ivGenerator : alg.defaultIvGenerator(); }