Example usage for java.security Key getAlgorithm

List of usage examples for java.security Key getAlgorithm

Introduction

In this page you can find the example usage for java.security Key getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:net.fender.crypto.CryptoUtil.java

/**
 * @param keyName//from   w  w w  .j a v a 2s  .c o  m
 * @param base64Encoded
 * @return
 * @throws GeneralSecurityException
 */
public static String decryptUsingSystemPropertyKey(String keyName, String base64Encoded)
        throws GeneralSecurityException {
    byte[] encryptedBytes = Base64.decodeBase64(base64Encoded.getBytes());
    Key key = getSystemPropertyKey(keyName);
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
    String decrypted = new String(decryptedBytes);
    return decrypted;
}

From source file:com.liferay.util.Encryptor.java

public static String encrypt(Key key, String plainText) throws EncryptorException {

    try {/*from  w  w w .ja  va 2  s . com*/
        Security.addProvider(getProvider());

        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] decryptedBytes = plainText.getBytes(ENCODING);
        byte[] encryptedBytes = cipher.doFinal(decryptedBytes);

        String encryptedString = Base64.encode(encryptedBytes);

        return encryptedString;
    } catch (Exception e) {
        throw new EncryptorException(e);
    }
}

From source file:com.liferay.util.Encryptor.java

public static String decrypt(Key key, String encryptedString) throws EncryptorException {

    try {/*www. ja  v  a  2  s  .c o  m*/
        Security.addProvider(getProvider());

        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] encryptedBytes = Base64.decode(encryptedString);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        String decryptedString = new String(decryptedBytes, ENCODING);

        return decryptedString;
    } catch (Exception e) {
        throw new EncryptorException(e);
    }
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

final public static _CRYPTOfactory getInstanceFromKeystore(final KeyStore keystore, final char[] keystorepass,
        final String alias)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException, IOException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
    final Key keyFromStore = keystore.getKey(alias, keystorepass);
    final String type = keyFromStore.getAlgorithm();
    return new _CRYPTOfactory(
            (Crypter) Class.forName(_CRYPTOfactory.class.getPackage().getName() + "." + type + "Crypter")
                    .getConstructor(byte[].class).newInstance(keyFromStore.getEncoded()));
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * KEY?//from w  w  w . jav  a2  s  .c  om
 * 
 * @param schemaIndex
 * @param key
 *            ?,??????? ???DES DESede(TripleDES)
 *            DESedeWrap PBEWithMD5AndDES(OID.1.2.840.113549.1.5.3 
 *            1.2.840.113549.1.5.3) PBEWithMD5AndTripleDES
 *            PBEWithSHA1AndRC2_40(OID.1.2.840.113549.1.12.1.6 
 *            1.2.840.113549.1.12.1.6)
 *            PBEWithSHA1AndDESede(OID.1.2.840.113549
 *            .1.12.1.3,1.2.840.113549.1.12.1.3) Blowfish AES(Rijndael)
 *            AESWrap RC2 ARCFOUR(RC4) RSA RSA/ECB/PKCS1Padding RSA 15?
 * @return
 */
public static byte[] encrypt(InputStream in, Key key, AlgorithmParameterSpec spec, boolean padding) {
    Assert.notNull(key, "SecretKey Key must not null");
    String alg = (key instanceof RawSecretKeySpec) ? ((RawSecretKeySpec) key).chiperAlgomrithm
            : key.getAlgorithm();
    if (padding && alg.indexOf('/') == -1) {
        alg = alg + "/ECB/PKCS1Padding";
    }
    try {
        Cipher c1 = Cipher.getInstance(alg);
        c1.init(Cipher.ENCRYPT_MODE, key, spec);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(c1.update(b, 0, len));
        }
        out.write(c1.doFinal());
        return out.toByteArray();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.concursive.commons.codec.PrivateStringTest.java

public void testNewKey() throws Exception {
    // Generate a key
    Key key = PrivateString.generateKey();
    assertEquals("AES", key.getAlgorithm());

    // Hex encode the key for portability
    String hexEncodedKey = new String(Hex.encodeHex(key.getEncoded()));
    assertNotNull("hexEncodedKey", hexEncodedKey);

    // Encrypt some text
    String encryptedText = PrivateString.encrypt(key, plainText);
    assertNotNull("encryptedText", encryptedText);

    // Decrypt the text for comparison
    String decryptedText = PrivateString.decrypt(key, encryptedText);
    assertEquals(plainText, decryptedText);

    // Decode the key for re-use and make sure it's the same
    Key hexDecodedKey = PrivateString.decodeHex(hexEncodedKey, key.getAlgorithm());
    assertEquals(key, hexDecodedKey);/*from   w  ww . j  a  v a2s.co m*/

    // Decode the encrypted text for comparison
    String hexDecryptedText = PrivateString.decrypt(hexDecodedKey, encryptedText);
    assertEquals(plainText, hexDecryptedText);

    // Compare the original key and the hex encoded key
    String hexEncryptedText = PrivateString.encrypt(hexDecodedKey, hexDecryptedText);
    assertEquals(encryptedText, hexEncryptedText);
}

From source file:Test.java

public boolean permits(Set<CryptoPrimitive> primitives, String algorithm, Key key,
            AlgorithmParameters parameters) {
        if (algorithm == null)
            algorithm = key.getAlgorithm();

        if (algorithm.indexOf("RSA") == -1)
            return false;

        if (key != null) {
            RSAKey rsaKey = (RSAKey) key;
            int size = rsaKey.getModulus().bitLength();
            if (size < 2048)
                return false;
        }//from  w w w .  jav  a  2 s  .  c  o m

        return true;
    }

From source file:jef.tools.security.EncrypterUtil.java

/**
 * KEY?//from   ww  w. jav  a 2s. c om
 * 
 * @param schemaIndex
 * @param key
 *            ?.???????
 * @return AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
 *         iterationCount);
 */
public static byte[] decrypt(InputStream in, Key key, AlgorithmParameterSpec spec) {
    Assert.notNull(key, "SecretKey Key must not null");
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        Cipher c1 = Cipher
                .getInstance((key instanceof RawSecretKeySpec) ? ((RawSecretKeySpec) key).chiperAlgomrithm
                        : key.getAlgorithm());
        c1.init(Cipher.DECRYPT_MODE, key, spec);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(c1.update(b, 0, len));
        }
        out.write(c1.doFinal());
        return out.toByteArray();
    } catch (GeneralSecurityException e) {
        LogUtil.exception(e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

protected void validateKey(Key key) throws InvalidKeyException, NoSuchAlgorithmException {
    String algorithm = key.getAlgorithm();
    int size = key.getEncoded().length * 8;
    if (!KEY_ALGORITHM.equalsIgnoreCase(algorithm)) {
        String msg = "Expected key of type: " + KEY_ALGORITHM + ", instead it was: " + algorithm;
        log.error(msg);/*from w w w  .j a  v a2  s.  c o m*/
        throw new InvalidKeyException(msg);
    } else if (size > Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM)) {
        String msg = "Illegal key size, max platform support for " + KEY_ALGORITHM + " keys is "
                + Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM);
        log.error(msg);
        throw new InvalidKeyException(msg);
    }
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

@PostConstruct
public void init() throws Exception {
    log.debug("Initializing...");
    if (useEncryption) {
        securityProvider = new BouncyCastleProvider();
        Security.addProvider(securityProvider);
        keyStore = initKeyStore(keyStoreFile, keyStorePassword, keyStoreType);
        saltKeyStore = initKeyStore(saltKeyKeyStoreFile, saltKeyKeyStorePassword, saltKeyKeyStoreType);
        salt = initSalt();/*w  w  w  .  j  a  v a 2  s  . c o  m*/
        Key key = keyStore.getKey(alias, keyStorePassword.toCharArray());
        validateKey(key);
        String algorithm = key.getAlgorithm();
        int size = key.getEncoded().length * 8;
        log.debug("operations will be performed using {} key with size {}", algorithm, size);

    } else {
        keyStore = null;
        log.warn("No keystore file specified, will not encrypt messages");
    }
    log.debug("Finished initializing");
}