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:Main.java

public static void main(String[] argv) throws Exception {
    AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
    paramGen.init(1024);// w w w  . j a v  a  2 s.c om

    AlgorithmParameters params = paramGen.generateParameters();
    DHParameterSpec dhSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);

    System.out.println("" + dhSpec.getP() + "," + dhSpec.getG() + "," + dhSpec.getL());
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Creates a new {@link FileEncryptionProvider} instance that provides encryption/decryption
 * capabilities based on the specified password.
 * @param password encryption/decryption password.
 * @return a new {@link FileEncryptionProvider} instance.
 * @throws Exception if an error occurs in the execution of the operation.
 *//*ww w  .  j  av a  2 s  .  c o  m*/
public static FileEncryptionProvider getInstance(final String password) throws Exception {
    checkArgument(StringUtils.isNotBlank(password), "Uninitialized or invalid password");
    // generate key from password
    final byte[] salt = generateSalt();
    LOGGER.trace("Generated salt: " + Hex.encodeHexString(salt));
    final SecretKey secret = generateKey(password, salt);
    LOGGER.trace("Generated key: " + Hex.encodeHexString(secret.getEncoded()));
    // create encryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encryptCipher.init(Cipher.ENCRYPT_MODE, secret);
    // initialization vector needed by the CBC mode
    final AlgorithmParameters params = encryptCipher.getParameters();
    final byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    // create decryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    decryptCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
    LOGGER.trace(String.format("Encryption/decryption ciphers were created - %s",
            encryptCipher.getProvider().getInfo()));
    return new FileEncryptionProvider(encryptCipher, decryptCipher);
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * //ww  w.  j a  v  a  2s. c  om
 * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
public static String encryptAESPBKDF2(String plainText) throws Exception {

    // get salt
    salt = generateSaltAESPBKDF2();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // encrypt the message
    Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:org.eclipse.leshan.server.demo.LeshanServerDemo.java

public static void createAndStartServer(int webPort, String localAddress, int localPort,
        String secureLocalAddress, int secureLocalPort, String redisUrl) throws Exception {
    // Prepare LWM2M server
    LeshanServerBuilder builder = new LeshanServerBuilder();
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setEncoder(new DefaultLwM2mNodeEncoder());
    LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
    builder.setDecoder(decoder);//  w ww. java  2s.c  o m

    // connect to redis if needed
    Pool<Jedis> jedis = null;
    if (redisUrl != null) {
        // TODO: support sentinel pool and make pool configurable
        jedis = new JedisPool(new URI(redisUrl));
    }

    // Get public and private server key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    try {
        // Get point values
        byte[] publicX = Hex
                .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
        byte[] publicY = Hex
                .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
        byte[] privateS = Hex
                .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());

        // Get Elliptic Curve Parameter spec for secp256r1
        AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
        algoParameters.init(new ECGenParameterSpec("secp256r1"));
        ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

        // Create key specs
        KeySpec publicKeySpec = new ECPublicKeySpec(
                new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
        KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

        // Get keys
        publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
        builder.setPublicKey(publicKey);
        builder.setPrivateKey(privateKey);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
        LOG.error("Unable to initialize RPK.", e);
        System.exit(-1);
    }

    // Define model provider
    LwM2mModelProvider modelProvider = new StandardModelProvider();
    builder.setObjectModelProvider(modelProvider);

    // Set securityStore & registrationStore
    EditableSecurityStore securityStore;
    if (jedis == null) {
        // use file persistence
        securityStore = new FileSecurityStore();
    } else {
        // use Redis Store
        securityStore = new RedisSecurityStore(jedis);
        builder.setRegistrationStore(new RedisRegistrationStore(jedis));
    }
    builder.setSecurityStore(securityStore);

    // Create and start LWM2M server
    LeshanServer lwServer = builder.build();

    // Now prepare Jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    server.setHandler(root);

    // Create Servlet
    EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort());
    ServletHolder eventServletHolder = new ServletHolder(eventServlet);
    root.addServlet(eventServletHolder, "/event/*");

    ServletHolder clientServletHolder = new ServletHolder(
            new ClientServlet(lwServer, lwServer.getSecureAddress().getPort()));
    root.addServlet(clientServletHolder, "/api/clients/*");

    ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
    root.addServlet(securityServletHolder, "/api/security/*");

    ServletHolder objectSpecServletHolder = new ServletHolder(
            new ObjectSpecServlet(lwServer.getModelProvider()));
    root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");

    // Start Jetty & Leshan
    lwServer.start();
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding//from  w  w w . j  a  v  a 2 s. c  o  m
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String encryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String encPass = null;

    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.ENCRYPT_MODE, sks);

        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);

        byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding));
        byte[] iv = ivParameterSpec.getIV();

        String combined = Base64.getEncoder().encodeToString(iv) + ":"
                + Base64.getEncoder().encodeToString(cryptoText);

        encPass = Base64.getEncoder().encodeToString(combined.getBytes());
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    } catch (InvalidParameterSpecException ipsx) {
        throw new SecurityException(ipsx.getMessage(), ipsx);
    }

    return encPass;
}

From source file:mitm.common.security.smime.SMIMEEncryptionAlgorithm.java

/**
 * Returns the effective key size (in bits) of the given algorithm. Returns -1 if the key size
 * cannot be determined.  /*from   w w  w .j  av  a 2s.co  m*/
 * @param algorithm
 * @param parameters
 * @return
 */
public static int getKeySize(SMIMEEncryptionAlgorithm algorithm, AlgorithmParameters parameters) {
    int strength = -1;

    if (algorithm == null) {
        return strength;
    }

    if (algorithm.fixedSize) {
        strength = algorithm.defaultKeySize();
    } else {
        if (parameters != null) {
            if (algorithm == RC2_CBC) {
                try {
                    RC2ParameterSpec rc2Params = parameters.getParameterSpec(RC2ParameterSpec.class);

                    strength = rc2Params.getEffectiveKeyBits();
                } catch (InvalidParameterSpecException e) {
                    logger.error("RC2ParameterSpec is invalid.", e);
                }
            }
            // TODO: add CAST5_CBC support
        }
    }

    return strength;
}

From source file:adminpassword.Encryption.java

public String encrypt(String word, String idKey) throws Exception {

    byte[] ivBytes;
    String password = idKey; //you can give whatever you want. This is for testing purpose
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);// w w w  .  j  av a  2  s  . c o m

    byte[] saltBytes = bytes;

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);
    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypting the word
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));

    //prepend salt and vi
    byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
    System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
    System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
    System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length,
            encryptedTextBytes.length);
    return new Base64().encodeToString(buffer);
}

From source file:adminpassword.AESDemo.java

public String encrypt(String plainText) throws Exception {

    //get salt//  ww  w .ja  va 2s .  c om
    salt = generateSalt();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:ai.serotonin.backup.Backup.java

private File encryptFile(final File file) throws Exception {
    final SecureRandom random = new SecureRandom();
    final byte[] salt = random.generateSeed(8);
    final String saltStr = Hex.encodeHexString(salt);

    final SecretKey secret = createSecretKey(salt);

    final Cipher cipher = createCipher();
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    final AlgorithmParameters params = cipher.getParameters();
    final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    final String ivStr = Hex.encodeHexString(iv);

    final File encryptedFile = new File(file.getParent(), saltStr + "_" + ivStr + "_" + file.getName());

    cipherizeFile(file, encryptedFile, cipher);

    file.delete();//from w  w w . ja  va 2 s.  com

    LOG.info("Encrypted backup file to " + encryptedFile.getPath() + ", "
            + FileUtils.byteCountToDisplaySize(encryptedFile.length()));
    return encryptedFile;
}

From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java

private String encryptText(String plainText) {
    try {/* w  w  w.  j a va2s  .  c om*/
        this.iv = prefs.getByteArray("DRUGS", null);
        if (this.iv == null) { //If not set, set the IV
            cipher.init(Cipher.ENCRYPT_MODE, this.secret);
            AlgorithmParameters params = cipher.getParameters();
            this.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
            prefs.putByteArray("DRUGS", this.iv);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, this.secret, new IvParameterSpec(this.iv));
        }

        byte[] ciphertext = cipher.doFinal(plainText.getBytes("UTF-8"));
        String ret = new String(Base64.encodeBase64(ciphertext));
        return ret;
    } catch (InvalidParameterSpecException | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException | InvalidKeyException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}