Example usage for java.security AlgorithmParameters getParameterSpec

List of usage examples for java.security AlgorithmParameters getParameterSpec

Introduction

In this page you can find the example usage for java.security AlgorithmParameters getParameterSpec.

Prototype

public final <T extends AlgorithmParameterSpec> T getParameterSpec(Class<T> paramSpec)
        throws InvalidParameterSpecException 

Source Link

Document

Returns a (transparent) specification of this parameter object.

Usage

From source file:org.eclipse.che.api.crypt.server.JCEEncryptTextService.java

@Override
public EncryptResult encryptText(final String textToEncrypt) throws EncryptException {
    byte[] ivBlob;
    byte[] cipherBlob;
    try {/*from  w w  w . ja  va 2s .c o m*/
        final SecretKey secret = generateSecret();

        final Cipher cipher = Cipher.getInstance(this.transformation);
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        final AlgorithmParameters params = cipher.getParameters();
        ivBlob = params.getParameterSpec(IvParameterSpec.class).getIV();
        cipherBlob = cipher.doFinal(textToEncrypt.getBytes("UTF-8"));
    } catch (final InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException
            | NoSuchPaddingException | InvalidParameterSpecException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException e) {
        throw new EncryptException(e);
    }

    final String cipherText = Base64.encodeBase64String(cipherBlob);
    final String ivText = Base64.encodeBase64String(ivBlob);

    return new EncryptResult(cipherText, ivText);
}

From source file:org.apache.abdera2.common.security.DHBase.java

private void init() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidParameterSpecException, InvalidKeySpecException {
    AlgorithmParameterGenerator pgen = AlgorithmParameterGenerator.getInstance("DH");
    pgen.init(512);//from  w ww  . ja  va2 s .com
    AlgorithmParameters params = pgen.generateParameters();
    DHParameterSpec dhspec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
    KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
    keypairgen.initialize(dhspec);
    keyPair = keypairgen.generateKeyPair();
    p = dhspec.getP();
    g = dhspec.getG();
    l = dhspec.getL();
}

From source file:SecureConnection.java

public byte[] getPublicKey(int size) throws Exception {
    AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
    paramGen.init(size);//from ww w  .  java 2s .  com
    AlgorithmParameters params = paramGen.generateParameters();
    DHParameterSpec dhParamSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
    return this.getPublicKeyStep2(dhParamSpec);
}

From source file:net.alegen.datpass.library.crypto.CryptoManager.java

public EncryptionOutput encrypt(String plaintext, String password) {
    try {//ww w . j  av a  2s .c o  m
        // set up the encryption key
        Random r = new Random(System.currentTimeMillis());
        byte[] salt = new byte[50];
        r.nextBytes(salt);
        SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, salt,
                AES_KEY_LENGTH, DEFAULT_ITERATIONS);
        salt = Base64.encodeBase64(salt);
        key = new SecretKeySpec(key.getEncoded(), "AES");

        // encrypt plain text with AES using generated key         
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV());
        byte[] ciphertext = Base64.encodeBase64(cipher.doFinal(plaintext.getBytes("UTF-8")));

        // package output and return
        return new EncryptionOutput(new String(ciphertext, "UTF-8"), new String(salt, "UTF-8"),
                new String(iv, "UTF-8"));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException | InvalidParameterSpecException e) {
        log.error("An error occured while encrypting the message.");
        return null;
    }
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 */// w ww.  j av  a  2  s  . co  m
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}

From source file:com.fegor.alfresco.security.crypto.Crypto.java

/**
 * Encryption configuration// w w  w . j a  v a2s  .c o m
 * 
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    salt_pos = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(salt_pos);

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    eCipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = eCipher.getParameters();

    vector_init = params.getParameterSpec(IvParameterSpec.class).getIV();

    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

/**
 * In order to correctly perform the encryption - decryption process, user must store their init vector table. This init vector will be given to the
 * user as a small file and it is required to perform the decryption process.
 *
 * @throws Exception//from ww  w . j  a  v  a  2  s . c  om
 */
protected final void processInitVector() throws Exception {
    String secretFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_SECRET), ".");
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    // get the zip file
    File encryptedFile = new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename);
    ZipOutputStream encryptedOutStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(encryptedFile)));
    // add the 16 bytes init vector for the cipher into the output stream
    ZipEntry ivZipEntry = new ZipEntry(secretFilename);
    encryptedOutStream.putNextEntry(ivZipEntry);
    // write the 16 bytes init vector for the cipher into the output stream
    AlgorithmParameters params = cipher.getParameters();
    byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    encryptedOutStream.write(initVector);
    encryptedOutStream.close();
}

From source file:org.eclipse.leshan.standalone.servlet.json.SecurityDeserializer.java

@Override
public SecurityInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json == null) {
        return null;
    }//from  w  ww  .j  a v a  2 s .  c  o m

    SecurityInfo info = null;

    if (json.isJsonObject()) {
        JsonObject object = (JsonObject) json;

        String endpoint = null;
        if (object.has("endpoint")) {
            endpoint = object.get("endpoint").getAsString();
        } else {
            throw new JsonParseException("Missing endpoint");
        }

        JsonObject psk = (JsonObject) object.get("psk");
        JsonObject rpk = (JsonObject) object.get("rpk");
        if (psk != null) {
            // PSK Deserialization
            String identity = null;
            if (psk.has("identity")) {
                identity = psk.get("identity").getAsString();
            } else {
                throw new JsonParseException("Missing PSK identity");
            }
            byte[] key;
            try {
                key = Hex.decodeHex(psk.get("key").getAsString().toCharArray());
            } catch (DecoderException e) {
                throw new JsonParseException(e);
            }

            info = SecurityInfo.newPreSharedKeyInfo(endpoint, identity, key);
        } else if (rpk != null) {
            PublicKey key;
            try {
                byte[] x = Hex.decodeHex(rpk.get("x").getAsString().toCharArray());
                byte[] y = Hex.decodeHex(rpk.get("y").getAsString().toCharArray());
                String params = rpk.get("params").getAsString();

                AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
                algoParameters.init(new ECGenParameterSpec(params));
                ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

                KeySpec keySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)),
                        parameterSpec);

                key = KeyFactory.getInstance("EC").generatePublic(keySpec);
            } catch (DecoderException | InvalidKeySpecException | NoSuchAlgorithmException
                    | InvalidParameterSpecException e) {
                throw new JsonParseException("Invalid security info content", e);
            }
            info = SecurityInfo.newRawPublicKeyInfo(endpoint, key);
        } else {
            throw new JsonParseException("Invalid security info content");
        }
    }

    return info;
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

/**
 * Method that will be called to process the summary collection file. Download process will create one zipped and encrypted collection of summary
 * files./*from w w  w. jav a  2s  .co m*/
 * <p/>
 * this.passphrase = password;
 *
 * @throws Exception
 */
protected final void processSummaries() throws Exception {
    // TODO: The better approach would be to create zip file and then encrypt it.
    // And then Content of the zip file:
    // * Zipped file of summary files and sql file
    // * Sample file to be used for decryption testing
    String zipFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ZIP), ".");
    File zipFile = new File(TaskUtils.getZippedOutputPath(), zipFilename);
    ZipOutputStream zipOutStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -1);
    Date cutOffDate = null;
    if (BooleanUtils.isTrue(partial)) {
        cutOffDate = calendar.getTime();
    }

    File inputPath = TaskUtils.getSummaryOutputPath();
    File[] files = inputPath.listFiles();
    if (files != null) {
        for (File file : files) {
            processStream(zipOutStream, inputPath.getAbsolutePath(), file, cutOffDate);
        }
    }
    zipOutStream.close();

    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    File encryptedOutFile = new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename);
    ZipOutputStream encryptedZipOutStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(encryptedOutFile)));

    int count;
    byte[] data;
    // add the 16 bytes init vector for the cipher into the output stream
    String secretFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_SECRET), ".");
    ZipEntry ivZipEntry = new ZipEntry(secretFilename);
    encryptedZipOutStream.putNextEntry(ivZipEntry);
    // write the 16 bytes init vector for the cipher into the output stream
    AlgorithmParameters params = cipher.getParameters();
    byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    encryptedZipOutStream.write(initVector);
    // add the sample file entry
    String sampleFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_SAMPLE), ".");
    ZipEntry sampleZipEntry = new ZipEntry(sampleFilename);
    encryptedZipOutStream.putNextEntry(sampleZipEntry);
    // write the sample file
    data = new byte[TaskConstants.BUFFER_SIZE];
    String sampleText = "This is sample text inside encrypted document. "
            + "If you see this text, that means your decryption parameters is correct";
    InputStream inStream = new ByteArrayInputStream(sampleText.getBytes());
    CipherInputStream sampleCipherInStream = new CipherInputStream(inStream, cipher);
    while ((count = sampleCipherInStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
        encryptedZipOutStream.write(data, 0, count);
    }
    sampleCipherInStream.close();
    // add the zipped summaries
    ZipEntry zipEntry = new ZipEntry(zipFile.getName());
    encryptedZipOutStream.putNextEntry(zipEntry);
    // write the zipped summaries
    data = new byte[TaskConstants.BUFFER_SIZE];
    InputStream zipInStream = new BufferedInputStream(new FileInputStream(zipFile));
    CipherInputStream zipCipherInStream = new CipherInputStream(zipInStream, cipher);
    while ((count = zipCipherInStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
        encryptedZipOutStream.write(data, 0, count);
    }
    zipCipherInStream.close();
    encryptedZipOutStream.close();
}

From source file:Crypto.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created 
 * along with the initialization vectory. The member variable mEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk./*from   ww w .  j a  v a  2 s . com*/
 *  
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    mSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(mSalt);
    Db("generated salt :" + Hex.encodeHexString(mSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* Derive the key, given password and salt. 
     * 
     * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
     * The end user must also install them (not compiled in) so beware. 
     * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
     */
    KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    mEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = mEcipher.getParameters();

    // get the initialization vectory and store as member var 
    mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
}