Example usage for javax.crypto KeyGenerator init

List of usage examples for javax.crypto KeyGenerator init

Introduction

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

Prototype

public final void init(int keysize) 

Source Link

Document

Initializes this key generator for a certain keysize.

Usage

From source file:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java

@Test
public void testEncryptionAES() throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    SecretKey secretKey = keygen.generateKey();

    LOG.debug("secret key algo: " + secretKey.getAlgorithm());
    LOG.debug("secret key format: " + secretKey.getFormat());

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    LOG.debug("cipher provider: " + cipher.getProvider().getName());
    byte[] result = cipher.doFinal("hello world".getBytes());
    assertNotNull(result);//from   w  ww. j a va  2 s. com

    byte[] encodedSecretKey = secretKey.getEncoded();
    LOG.debug("encoded secret key size: " + encodedSecretKey.length * 8);

    // decrypt
    cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSecretKey, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptedResult = cipher.doFinal(result);
    assertEquals("hello world", new String(decryptedResult));
}

From source file:enc_mods.aes.java

public void setKey() {
    try {/* w  w w.  ja  v a  2s  . 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: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);
    SecretKey secretKey = keyGen.generateKey();
    return new String(Base64.encode(secretKey.getEncoded()), "UTF-8");
}

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

/**
 * Encrypts using an asymmetric cipher.//w  ww.  j a  va2 s . c o m
 *
 * @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;/*w  w  w.j a v a 2 s .  c  o  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:com.muk.services.commerce.CryptoServiceImpl.java

@PostConstruct
public void postConstruct() {
    try {// ww w. ja va  2  s.  c om
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        temporaryKey = new SecretKeySpec(kgen.generateKey().getEncoded(), "AES");

        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        ivSpec = new IvParameterSpec(iv);
    } catch (final NoSuchAlgorithmException ex) {
        LOG.error("Failed to initalize encryption key", ex);
    } catch (final NoSuchPaddingException padEx) {
        LOG.error("Failed to get cipher.", padEx);
    }
}

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

/**
 * Generate a random AES {@link SecretKey}
 *
 * @return//from w ww.j  a v  a  2 s  .c o  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);
    }
}

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);
    Key skey = kgen.generateKey();
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    // keyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
    keyStore.load(null, null);// w  w w .  ja  v  a 2  s.  co  m
    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:se.vgregion.portal.cs.util.CryptoUtilImpl.java

/**
 * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created
 * // ww  w.  j  ava2s  .  c  o  m
 * @param value
 *            - value to be encrypted
 * @throws GeneralSecurityException
 *             - security exception
 * @return Encrypted value
 */
@Override
public String encrypt(String value) throws GeneralSecurityException {
    if (!keyFile.exists()) {
        KeyGenerator keyGen = KeyGenerator.getInstance(AES);
        keyGen.init(KEY_SIZE);
        SecretKey sk = keyGen.generateKey();
        FileWriter fw = null;
        try {
            fw = new FileWriter(keyFile);
            fw.write(byteArrayToHexString(sk.getEncoded()));
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    SecretKeySpec sks = getSecretKeySpec();

    Cipher cipher = Cipher.getInstance(AES);
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return byteArrayToHexString(encrypted);
}

From source file:com.torchmind.authenticator.AbstractTokenGenerator.java

/**
 * {@inheritDoc}/*  ww w . j  ava 2 s . c  o m*/
 */
@NonNull
@Override
public SecretKey generateSecret() {
    try {
        KeyGenerator generator = KeyGenerator.getInstance("Hmac" + this.algorithm.name());
        generator.init(80);
        return generator.generateKey();
    } catch (NoSuchAlgorithmException ex) {
        throw new UnsupportedOperationException(
                "The specified algorithm is not supported by this Java VM implementation: " + ex.getMessage(),
                ex);
    }
}