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:org.apigw.commons.crypto.ApigwCrypto.java

/**
 * Will init the global salt / IV, this salt should not be stored together with encrypted values.
 *///from   w  w  w  . ja v a2s  . co  m
private byte[] initSalt() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException {
    byte[] encryptedSalt = Base64.decodeBase64(encodedEncryptedSalt.getBytes());
    Key saltKey = saltKeyStore.getKey(saltKeyAlias, saltKeyPassword.toCharArray());
    validateKey(saltKey);
    String algorithm = saltKey.getAlgorithm();
    int size = saltKey.getEncoded().length * 8;
    log.debug("initializing salt using {} key with size {}", algorithm, size);
    SecretKeySpec skeySpec = new SecretKeySpec(saltKey.getEncoded(), KEY_ALGORITHM);

    IvParameterSpec ivParameterSpec = new IvParameterSpec(getIV(encryptedSalt));
    Cipher decryptCipher = Cipher.getInstance(TRANSFORMATION, securityProvider);
    decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decryptedSalt = decryptCipher.doFinal(encryptedSalt);
    return removeIV(decryptedSalt);
}

From source file:cn.ctyun.amazonaws.services.s3.internal.crypto.EncryptionUtils.java

/**
 * Decrypts an encrypted symmetric key using the provided encryption materials and returns
 * it as a SecretKey object.//www . j  a v  a2  s .c  o m
 */
private static SecretKey getDecryptedSymmetricKey(byte[] encryptedSymmetricKeyBytes,
        EncryptionMaterials materials, Provider cryptoProvider) {
    Key keyToDoDecryption;
    if (materials.getKeyPair() != null) {
        // Do envelope decryption with private key from key pair
        keyToDoDecryption = materials.getKeyPair().getPrivate();
    } else {
        // Do envelope decryption with symmetric key
        keyToDoDecryption = materials.getSymmetricKey();
    }
    try {
        Cipher cipher;
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm(), cryptoProvider);
        } else {
            cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm());
        }
        cipher.init(Cipher.DECRYPT_MODE, keyToDoDecryption);
        byte[] decryptedSymmetricKeyBytes = cipher.doFinal(encryptedSymmetricKeyBytes);
        return new SecretKeySpec(decryptedSymmetricKeyBytes, JceEncryptionConstants.SYMMETRIC_KEY_ALGORITHM);
    } catch (Exception e) {
        throw new AmazonClientException(
                "Unable to decrypt symmetric key from object metadata : " + e.getMessage(), e);
    }
}

From source file:cn.ctyun.amazonaws.services.s3.internal.crypto.EncryptionUtils.java

/**
 * Encrypts a symmetric key using the provided encryption materials and returns
 * it in raw byte array form./*from ww w.  j a va  2 s . c om*/
 */
public static byte[] getEncryptedSymmetricKey(SecretKey toBeEncrypted, EncryptionMaterials materials,
        Provider cryptoProvider) {
    Key keyToDoEncryption;
    if (materials.getKeyPair() != null) {
        // Do envelope encryption with public key from key pair
        keyToDoEncryption = materials.getKeyPair().getPublic();
    } else {
        // Do envelope encryption with symmetric key
        keyToDoEncryption = materials.getSymmetricKey();
    }
    try {
        Cipher cipher;
        byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded();
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm(), cryptoProvider);
        } else {
            cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm()); // Use default JCE Provider
        }
        cipher.init(Cipher.ENCRYPT_MODE, keyToDoEncryption);
        return cipher.doFinal(toBeEncryptedBytes);
    } catch (Exception e) {
        throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e);
    }
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

public byte[] loadSecretKey() {
    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    Key key = null;
    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);//from w  ww. j  a v  a2 s  .c o m
        key = ks.getKey(keystorePKAlias, ksKeyPassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException e) {
        LOGGER.error("Exception occured during the loading of the secret key. {}", e);
        throw new RuntimeException(e);
    }
    if (key == null) {
        return new byte[0];
    }
    LOGGER.info("Algorithm: " + key.getAlgorithm());
    LOGGER.info("Format: " + key.getFormat());
    return key.getEncoded();
}

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * Gets a unique path to a private key./*from w w  w . j  a v  a 2s  .  c o  m*/
 *
 * @param  key  Private key.
 * @param  type  PEM or DER.
 * @param  password  Password on private key; may be null.
 *
 * @return  Path to key.
 */
private String getKeyPath(final Key key, final String type, final char[] password) {
    final StringBuffer sb = new StringBuffer();
    if (key instanceof PrivateKey) {
        sb.append("target/test-output/privkey_");
    } else if (key instanceof SecretKey) {
        sb.append("target/test-output/secretkey_");
    } else if (key instanceof PublicKey) {
        sb.append("target/test-output/pubkey_");
    } else {
        throw new IllegalArgumentException("Unrecognized key type.");
    }
    sb.append(key.getAlgorithm());
    sb.append("_");
    try {
        sb.append(fingerPrint(key));
    } catch (CryptException e) {
        sb.append(key.hashCode());
    }
    if (!(key instanceof PublicKey)) {
        if (password != null) {
            sb.append("_withpass");
        } else {
            sb.append("_nopass");
        }
    }
    sb.append('.');
    sb.append(type.toLowerCase());
    return sb.toString();
}

From source file:mitm.common.security.keystore.hibernate.SerializableKeyEntry.java

public SerializableKeyEntry(Key key, char[] password, PBEncryption encryptor)
        throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
    if (encryptor == null || password == null) {
        this.rawKey = key.getEncoded();
        this.protection = Protection.NONE;
    } else {/*  w  ww . j  av a  2 s .c o m*/
        this.rawKey = encryptor.encrypt(key.getEncoded(), password);
        this.protection = Protection.ENCRYPTED;
    }

    this.algorithm = key.getAlgorithm();
    this.format = key.getFormat();

    if (key instanceof PrivateKey) {
        keyType = KeyType.PRIVATE;
    } else {
        if (key instanceof PublicKey) {
            keyType = KeyType.PUBLIC;
        } else {
            keyType = KeyType.SECRET;
        }
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result//from   w ww.j  a  v a 2 s .  com
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorFactoryConnIdImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result//  w w w.  j  ava2s .  c o m
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:com.amazonaws.services.s3.internal.crypto.S3CryptoModuleBase.java

protected final SecuredCEK secureCEK(SecretKey toBeEncrypted, EncryptionMaterials materials,
        Provider cryptoProvider) {
    Key kek;
    if (materials.getKeyPair() != null) {
        // Do envelope encryption with public key from key pair
        kek = materials.getKeyPair().getPublic();
    } else {/*from  w w w  . j a v a2s .  c o m*/
        // Do envelope encryption with symmetric key
        kek = materials.getSymmetricKey();
    }
    S3KeyWrapScheme kwScheme = cryptoScheme.getKeyWrapScheme();
    String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
    try {
        if (keyWrapAlgo != null) {
            Cipher cipher = cryptoProvider == null ? Cipher.getInstance(keyWrapAlgo)
                    : Cipher.getInstance(keyWrapAlgo, cryptoProvider);
            cipher.init(Cipher.WRAP_MODE, kek, cryptoScheme.getSecureRandom());
            return new SecuredCEK(cipher.wrap(toBeEncrypted), keyWrapAlgo);
        }
        // fall back to the Encryption Only (EO) key encrypting method
        Cipher cipher;
        byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded();
        String algo = kek.getAlgorithm();
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(algo, cryptoProvider);
        } else {
            cipher = Cipher.getInstance(algo); // Use default JCE Provider
        }
        cipher.init(Cipher.ENCRYPT_MODE, kek);
        return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null);
    } catch (Exception e) {
        throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e);
    }
}

From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java

/**
 * Restituisce i parametri per la ricostruzione di una chiave di
 * crittografia.//from  w w  w  .j a  va2 s.  c  o  m
 * 
 * <P>Il metodo {@code toProperties} rileva i provider del servizio
 * {@code KeyToPropertySetProvider} disponibili e delega il calcolo dei
 * parametri al primo di questi che supporta la tipologia della chiave di
 * crittografia {@code key}; se nessuno dei provider supporta la specifica
 * tipologia di chiavi, restituisce i parametri che rappresentano la chiave
 * codificata come sequenza di byte nel formato Base64 come definito da RFC
 * 2045.</P>
 * 
 * @param  key     Chiave.
 * @param  encoded Indica se restituire i parametri che rappresentano la
 *                 chiave codificata come sequenza di byte senza rilevare
 *                 gli eventuali provider {@code KeyToPropertySetProvider}
 *                 disponibili.
 * @return         Propriet&agrave;. 
 * @see #getKey
 * @see it.scoppelletti.programmerpower.security.spi.CryptoKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.EncodedKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.KeyToPropertySetProvider
 * @see <A HREF="http://www.ietf.org/rfc/rfc2045.txt" TARGET="_blank">RFC
 *      2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format
 *      of Internet Message Bodies</A> 
 */
public static Properties toProperties(Key key, boolean encoded) {
    byte[] data;
    KeyRep.Type keyType;
    Properties props;
    KeyToPropertySetService svc;
    SecurityResources res = new SecurityResources();

    if (key == null) {
        throw new ArgumentNullException("key");
    }

    if (!encoded) {
        svc = new KeyToPropertySetService(key);
        props = svc.query();
        if (props != null) {
            return props;
        }
    }

    if (key instanceof PublicKey) {
        keyType = KeyRep.Type.PUBLIC;
    } else if (key instanceof PrivateKey) {
        keyType = KeyRep.Type.PRIVATE;
    } else if (key instanceof SecretKey) {
        keyType = KeyRep.Type.SECRET;
    } else {
        throw new InvalidCastException(key.getClass().getName(), KeyRep.Type.class.getName());
    }

    data = key.getEncoded();
    if (data == null) {
        throw new SecurityException(res.getEncodedFormatNotSupportedException());
    }

    props = new Properties();
    if (keyType == KeyRep.Type.SECRET) {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, RawKeyFactory.class.getName());
    } else {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, EncodedKeyFactory.class.getName());
        props.setProperty(EncodedKeyFactory.PROP_KEYTYPE, keyType.name());
    }

    props.setProperty(RawKeyFactory.PROP_ALGORITHM, key.getAlgorithm());
    props.setProperty(RawKeyFactory.PROP_DATA, Base64.encodeBase64String(data));

    return props;
}