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:com.projectsontracks.model.CaribooKey.java

/**
 * Creates a new AES key/*from   ww  w. j a  v  a2 s.  c o  m*/
 *
 * @throws java.security.NoSuchAlgorithmException
 */
public void createKey() throws NoSuchAlgorithmException {
    // Initialize the key generator
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(this.size);
    // Generates the key
    SecretKey skey = kgen.generateKey();
    // Returns the key in its primary encoding format, or null if this key does not support encoding.
    key = skey.getEncoded();
    //used to construct a SecretKey from a byte array, without having to go through a (provider-based) SecretKeyFactory.
    keySpec = new SecretKeySpec(key, "AES");
}

From source file:org.craftercms.security.authentication.impl.CipheredAuthenticationCookieFactory.java

/**
 * Generates a random encryption key./*  w ww  .ja  va  2 s. c  o m*/
 */
protected Key generateRandomKey() throws CrafterSecurityException {
    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(CIPHER_ALGORITHM);
        keyGenerator.init(secureRandom);

        return keyGenerator.generateKey();
    } catch (Exception e) {
        throw new CrafterSecurityException("Unable to generate random encryption key", e);
    }
}

From source file:com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java

@Override
public QueryResult createKey(Param param, String owner)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    logger.info("User is trying to create key. userName:" + owner + ", keyName:" + param.getKeyName());
    File newKeyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
    if (newKeyfile.exists()) {
        logger.info("keyName \"" + param.getKeyName() + "\" exists, please choose another keyName.");
        return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_EXISTS), null);
    }//from ww  w  . j  a v a  2s .  c o m

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256);
    SecretKey secretKey = keyGen.generateKey();
    String hexkey = Hex.encodeHexString(secretKey.getEncoded());

    Properties prop = new Properties();
    prop.setProperty("owner", owner);
    prop.setProperty("keyName", param.getKeyName());
    prop.setProperty("hexkey", hexkey);
    prop.setProperty("users", param.getUsers());

    File keyFileFolder = new File(env.getProperty("keyfile.path"));
    if (!keyFileFolder.exists()) {
        keyFileFolder.mkdirs();
        Runtime.getRuntime().exec("chmod 700 " + env.getProperty("keyfile.path"));
    }
    prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
    Runtime.getRuntime().exec("chmod 600 " + env.getProperty("keyfile.path") + param.getKeyName());
    logger.info("save keyfile \"{}\" to keyfile folder: {}", param.getKeyName(),
            env.getProperty("keyfile.path"));

    return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + param.getKeyName() + ") created",
            null);
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

public void encrypt(InputStream plainInput, OutputStream encryptedOutput, PublicKey key)
        throws IOException, GeneralSecurityException {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(KEY_SIZE);

    SecretKey aesKey = kgen.generateKey();

    byte[] data = IOUtil.toByteArray(plainInput);
    byte[] encryptedData = getCipher("AES", aesKey, Cipher.ENCRYPT_MODE).doFinal(data);

    byte[] raw = aesKey.getEncoded();
    byte[] encryptedKey = getCipher("RSA/ECB/PKCS1Padding", key, javax.crypto.Cipher.ENCRYPT_MODE).doFinal(raw);

    // useful when debugging but can't be left uncommented due to NEXUS-2530
    // if ( getLogger().isDebugEnabled() )
    // {/* w w w  .  j  a  va  2  s  .  c  o m*/
    // log.debug( "before encrypt: " + new String( Base64.encodeBase64( raw ) ) );
    // log.debug( "Encrypted key: " + new String( Base64.encodeBase64( encryptedKey ) ) );
    // log.debug( "Encrypted data: " + new String( Base64.encodeBase64( encryptedData ) ) );
    // }

    Base64OutputStream output = new Base64OutputStream(encryptedOutput);
    IOUtil.copy(encryptedKey, output);
    IOUtil.copy(encryptedData, output);
    output.close();
    encryptedOutput.flush();
}

From source file:org.pentaho.di.trans.steps.symmetriccrypto.symmetricalgorithm.SymmetricCrypto.java

public byte[] generateKey(int keySize) throws CryptoKeyException {
    try {//w ww .  j ava2  s.c  om
        // Get a key generator for algorithm
        KeyGenerator kg = KeyGenerator.getInstance(meta.getAlgorithm());
        // SecureRandom random = new SecureRandom();
        kg.init(keySize);
        // Use it to generate a key
        SecretKey secretKey = kg.generateKey();

        return secretKey.getEncoded();

    } catch (Exception e) {
        throw new CryptoKeyException(e);
    }
}

From source file:org.apache.ws.security.message.SymmetricSignatureTest.java

/**
 * Setup method//from  w  w  w  .  j a v  a2  s.c o  m
 * <p/>
 * 
 * @throws Exception Thrown when there is a problem in setup
 */
@org.junit.Before
public void setUp() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    keyData = key.getEncoded();
}

From source file:org.craftercms.commons.crypto.SimpleAesCipher.java

public SimpleAesCipher(String base64Key) {
    KeyGenerator kgen = null;
    try {//from ww w.  ja va 2 s  .c o m
        kgen = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    kgen.init(128); // 192 and 256 bits may not be available

    byte[] raw = Base64.decodeBase64(base64Key);

    skeySpec = new SecretKeySpec(raw, "AES");

    try {
        cipher = Cipher.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.lucene.gdata.server.authentication.BlowfishAuthenticationController.java

/**
 * @see org.apache.lucene.gdata.server.authentication.AuthenticationController#initialize()
 *//*from  w w w.java2  s.  c o  m*/
public void initialize() {
    if (this.key == null)
        throw new IllegalArgumentException("Auth key must not be null");
    if (this.key.length() < 5 || this.key.length() > 16)
        throw new IllegalArgumentException("Auth key length must be greater than 4 and less than 17");

    try {
        Provider sunJce = new com.sun.crypto.provider.SunJCE();
        Security.addProvider(sunJce);
        KeyGenerator kgen = KeyGenerator.getInstance(ALG);
        kgen.init(448); // 448 Bit^M
        byte[] raw = this.key.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALG);
        this.deCrypt = Cipher.getInstance(ALG);
        this.enCrypt = Cipher.getInstance(ALG);
        this.deCrypt.init(Cipher.DECRYPT_MODE, skeySpec);
        this.enCrypt.init(Cipher.ENCRYPT_MODE, skeySpec);
    } catch (Exception e) {
        throw new AuthenticatorException(
                "Can't initialize BlowfishAuthenticationController -- " + e.getMessage(), e);

    }
    calculateTimeOffset();
}

From source file:com.microsoft.azure.storage.queue.QueueEncryptionPolicy.java

/**
 * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
 * /*from w w  w  .j a v a  2  s  . com*/
 * @param inputMessage
 *            The input message in bytes.
 * @return The encrypted message that will be uploaded to the service.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
String encryptMessage(byte[] inputMessage) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage();
    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptedMessage.setEncryptedMessageContents(
                new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length))));

        encryptionData.setContentEncryptionIV(myAes.getIV());
        encryptedMessage.setEncryptionData(encryptionData);
        return encryptedMessage.serialize();
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:org.codice.ddf.configuration.migration.CipherUtils.java

/**
 * Creates a secret key and stores it in a file
 *
 * @param keyPath the path for storing the secret key
 * @throws MigrationException when an invalid key algorithm is used
 * @throws MigrationException when the key can not be written to a file
 * @throws NoSuchAlgorithmException when an invalid algorithm is used for the {@link KeyGenerator}
 * @return a {@link SecretKey}//from w w w .j a v a  2  s . c o m
 */
private SecretKey createSecretKey(Path keyPath) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(MigrationZipConstants.KEY_ALGORITHM);
        keyGenerator.init(128);
        secretKey = keyGenerator.generateKey();
        char[] hexKey = encodeHex(secretKey.getEncoded());
        writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8);
        return secretKey;
    } catch (IOException e) {
        throw new MigrationException(String.format(MigrationZipConstants.FILE_IO_ERROR, keyPath, e));
    }
}