Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator generateKey.

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

@Override
public String generateKey(int keySize)
        throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    LOG.info("Generating a new encryption key of size " + keySize);
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(keySize);//from   w  w w.j  av a 2s.c  o  m
    SecretKey secretKey = keyGen.generateKey();
    return new String(Base64.encode(secretKey.getEncoded()), "UTF-8");
}

From source file:pl.mwaleria.safecommunicator.core.cipher.CipherManager.java

public byte[] encrypt(byte[] input, PublicKey publicKey) throws CryptoException {
    try {//from  www  .j  a  v a  2s  . co m
        KeyGenerator generator = KeyGenerator.getInstance(Constants.CIPHER_SYMETRIC_ALGORITHM);
        generator.init(Constants.CIPHER_SYMETRIC_SIZE);
        SecretKey key = generator.generateKey();
        byte[] aesKey = key.getEncoded();
        byte[] cryptedAesKey = this.encryptAsymetric(aesKey, publicKey);
        Cipher cipher = Cipher.getInstance(Constants.CIPHER_SYMETRIC_INSTANCE);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return ArrayUtils.addAll(cryptedAesKey, cipher.doFinal(input));
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(CipherManager.class.getName()).log(Level.SEVERE, null, ex);
        throw new CryptoException(ex);
    }
}

From source file:enc_mods.aes.java

public void setKey() {
    try {/*from  w  w w. ja  va 2  s .c  o  m*/
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(AES_Key_Size);
        SecretKey aeskey = kgen.generateKey();
        key = aeskey.getEncoded();
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Blowfish encryption//  ww  w.j  a v a  2s. c om
 *
 * @param value
 * @return
 * @throws java.lang.Exception
 */
public static String encrypt(String value) throws Exception {
    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    File file = new File(DefaultConfig.SECRET_KEY);
    SecretKey secretkey;

    if (file.exists()) {
        // Load key from file
        secretkey = new SecretKeySpec(FileUtils.readFileToByteArray(file), "Blowfish");
    } else {
        // create a key
        secretkey = keygenerator.generateKey();
        FileUtils.writeByteArrayToFile(file, secretkey.getEncoded());
    }

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // encrypt message
    return bytesToHex(cipher.doFinal(value.getBytes()));
}

From source file:com.bamboocloud.im.provisioner.json.crypto.simple.SimpleEncryptor.java

/**
 * Encrypts using an asymmetric cipher./*from  w  w  w . j  a  v a 2  s . c om*/
 *
 * @param value the value to be encrypted.
 * @return the encrypted value.
 * @throws GeneralSecurityException if a cryptographic operation failed.
 * @throws IOException if an I/O exception occurred.
 */
private Object asymmetric(Object object) throws GeneralSecurityException, IOException {
    String symmetricCipher = "AES/ECB/PKCS5Padding"; // no IV required for randomly-generated session key
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128);
    SecretKey sessionKey = generator.generateKey();
    Cipher symmetric = Cipher.getInstance(symmetricCipher);
    symmetric.init(Cipher.ENCRYPT_MODE, sessionKey);
    String data = Base64.encodeBase64String(symmetric.doFinal(mapper.writeValueAsBytes(object)));
    Cipher asymmetric = Cipher.getInstance(cipher);
    asymmetric.init(Cipher.ENCRYPT_MODE, key);
    HashMap<String, Object> keyObject = new HashMap<String, Object>();
    keyObject.put("cipher", this.cipher);
    keyObject.put("key", this.alias);
    keyObject.put("data", Base64.encodeBase64String(asymmetric.doFinal(sessionKey.getEncoded())));
    HashMap<String, Object> result = new HashMap<String, Object>();
    result.put("cipher", symmetricCipher);
    result.put("key", keyObject);
    result.put("data", data);
    return result;
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

protected static String encryptString(String decStr) {
    String encStr = null;//from   www .  j av a 2  s  . co m
    KeyStore ks = getKeyStore();
    if (ks != null) {
        SecretKey sk = getSecretKey(ks);
        if (sk == null) {
            // create key
            KeyGenerator kgen = null;
            try {
                kgen = KeyGenerator.getInstance("AES");
            } catch (NoSuchAlgorithmException e) {
                writeLog("encryptString: " + e.getMessage());
            }
            if (kgen != null) {
                int keyLength;
                try {
                    keyLength = Cipher.getMaxAllowedKeyLength("AES");
                } catch (NoSuchAlgorithmException e) {
                    keyLength = 128;
                    writeLog("encryptString: " + e.getMessage());
                }
                kgen.init(keyLength);
                sk = kgen.generateKey();
                // create a keystore
                try {
                    ks.load(null, sPassphrase.toCharArray());
                    ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null);
                    ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray());
                } catch (NoSuchAlgorithmException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (CertificateException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (IOException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (KeyStoreException e) {
                    writeLog("encryptString: " + e.getMessage());
                }
            }
        }
        if ((sk != null) && (decStr != null)) {
            Cipher cipher;
            try {
                cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, sk);
                return new String(Base64.encodeBase64(cipher.doFinal(decStr.getBytes("UTF-8"))));
            } catch (NoSuchAlgorithmException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (NoSuchPaddingException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (InvalidKeyException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (IllegalBlockSizeException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (BadPaddingException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (UnsupportedEncodingException e) {
                writeLog("encryptString: " + e.getMessage());
            }
        }
    }
    return encStr;
}

From source file:org.nuxeo.ecm.core.blob.binary.TestAESBinaryManager.java

protected void createKeyStore(File file) throws GeneralSecurityException, IOException {
    AESBinaryManager.setUnlimitedJCEPolicy();

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(256);//from ww w .  j a  va  2 s. c o m
    Key skey = kgen.generateKey();
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    // keyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
    keyStore.load(null, null);
    keyStore.setKeyEntry(KEY_ALIAS, skey, KEY_PASSWORD.toCharArray(), null);
    OutputStream out = new FileOutputStream(file);
    keyStore.store(out, KEY_STORE_PASSWORD.toCharArray());
    out.close();
}

From source file:org.sonar.api.config.AesCipher.java

String generateRandomSecretKey() {
    try {//w ww  .  ja  va  2s  . co  m
        KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
        keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
        SecretKey secretKey = keyGen.generateKey();
        return new String(Base64.encodeBase64(secretKey.getEncoded()));

    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate secret key", e);
    }
}

From source file:org.sonar.process.AesCipher.java

String generateRandomSecretKey() {
    try {//from   w  w  w .j a v  a2 s  .c  o  m
        KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
        keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
        SecretKey secretKey = keyGen.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());

    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate secret key", e);
    }
}

From source file:net.thewaffleshop.nimbus.api.EncryptionAPI.java

/**
 * Generate a random AES {@link SecretKey}
 *
 * @return//from   ww w  .  ja v  a  2 s .co  m
 */
public SecretKey createSecretKey() {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey key = keyGen.generateKey();
        return key;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}