Example usage for javax.crypto SecretKey getAlgorithm

List of usage examples for javax.crypto SecretKey getAlgorithm

Introduction

In this page you can find the example usage for javax.crypto SecretKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:energy.usef.core.service.business.MessageEncryptionServiceIntegrationTest.java

@Before
public void initTest() throws UnsupportedEncodingException {
    Whitebox.setInternalState(keystoreHelperService, "config", config);
    service = new MessageEncryptionService();
    Whitebox.setInternalState(service, "keystoreHelperService", keystoreHelperService);

    energy.usef.core.util.encryption.NaCl.sodium().crypto_sign_ed25519_seed_keypair(publicKey, privateKey,
            SEED.getBytes(UTF_8));/*from   www  .  j  a  v a2s  . c  om*/
    SecretKey secretKey = new SecretKeySpec(privateKey, ALGORITHM);

    LOGGER.info("Public Key: [{}]", new String(publicKey, StandardCharsets.UTF_8));
    LOGGER.info("Private Key: [{}]", new String(privateKey, StandardCharsets.UTF_8));
    LOGGER.info("Secret Key Algorithm: [{}]", secretKey.getAlgorithm());
    LOGGER.info("Secret Key Format: [{}]", secretKey.getFormat());
    LOGGER.info("Secret Key Encoded: [{}]", new String(secretKey.getEncoded(), StandardCharsets.UTF_8));

    LOGGER.info("### Executing test: {}", name.getMethodName());

    Mockito.when(keystoreHelperService.loadSecretKey())
            .thenReturn(Arrays.copyOf(privateKey, privateKey.length));
}

From source file:com.ephesoft.dcma.encryption.core.EncryptorDecryptor.java

/**
 * This method is used to start the encryption process.
 * /*from   w  w  w.  j ava  2  s .  com*/
 * @param data byte[]
 * @param salt byte[]
 * @param isEncryption boolean
 * @return byte[]
 * @throws CryptographyException {@link CryptographyException}
 */
public byte[] startCrypting(byte[] data, byte[] salt, boolean isEncryption) throws CryptographyException {
    KeySpec keySpec = new PBEKeySpec(EncryptionConstants.KEY.toCharArray(), salt,
            EncryptionConstants.ITERATION_COUNT);
    SecretKey key;
    byte[] finalBytes = null;
    try {
        key = SecretKeyFactory.getInstance(EncryptionConstants.ALGORITHM).generateSecret(keySpec);
        Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, EncryptionConstants.ITERATION_COUNT);
        if (isEncryption) {
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        } else {
            ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        }
        finalBytes = ecipher.doFinal(data);
    } catch (InvalidKeySpecException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Key used is invalid", e);
            throw new CryptographyException("Key used is invalid", e);
        } else {
            LOGGER.error("Decryption : Key used is invalid", e);
            throw new CryptographyException("Key used is invalid", e);
        }
    } catch (NoSuchAlgorithmException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Algorithm used does not exist", e);
            throw new CryptographyException("Algorithm used does not exist", e);
        } else {
            LOGGER.error("Decryption : Algorithm used does not exist", e);
            throw new CryptographyException("Algorithm used does not exist", e);
        }
    } catch (NoSuchPaddingException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Padding used does not exist", e);
            throw new CryptographyException("Padding used does not exist", e);
        } else {
            LOGGER.error("Decryption : Padding used does not exist", e);
            throw new CryptographyException("Padding used does not exist", e);
        }
    } catch (InvalidKeyException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Key generated is invalid", e);
            throw new CryptographyException("Key generated is invalid", e);
        } else {
            LOGGER.error("Decryption : Key generated is invalid", e);
            throw new CryptographyException("Key generated is invalid", e);
        }
    } catch (InvalidAlgorithmParameterException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Algorithm parameter is invalid", e);
            throw new CryptographyException("Algorithm parameter is invalid", e);
        } else {
            LOGGER.error("Decryption : Algorithm parameter is invalid", e);
            throw new CryptographyException("Algorithm parameter is invalid", e);
        }
    } catch (IllegalBlockSizeException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Block size is illegal", e);
            throw new CryptographyException("Block size is illegal", e);
        } else {
            LOGGER.error("Decryption : Block size is illegal", e);
            throw new CryptographyException("Block size is illegal", e);
        }
    } catch (BadPaddingException e) {
        if (isEncryption) {
            LOGGER.error("Encryption : Padding done is invalid", e);
            throw new CryptographyException("Padding done is invalid", e);
        } else {
            LOGGER.error("Decryption : Padding done is invalid", e);
            throw new CryptographyException("Padding done is invalid", e);
        }
    }
    return finalBytes;
}

From source file:com.thruzero.common.core.security.SimpleCipher.java

/**
 * Construct using the {@code salt}, {@code passPhrase} and {@code iterationCount} defined by the given
 * {@code simpleCipherConfiguration}.//from  w  w  w . j a  va2s.  co m
 *
 * @throws SimpleCipherException
 */
public SimpleCipher(final SimpleCipherConfiguration simpleCipherConfiguration) throws SimpleCipherException {
    try {
        int count = simpleCipherConfiguration.getIterationCount();
        byte[] salt = simpleCipherConfiguration.getSalt();

        KeySpec keySpec = new PBEKeySpec(simpleCipherConfiguration.getPassPhrase(), salt, count);

        AlgorithmParameterSpec parameterSpec = new PBEParameterSpec(salt, count);
        SecretKey key = SecretKeyFactory.getInstance(PBE_WITH_MD5_AND_DES).generateSecret(keySpec);

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

        decryptionCipher = Cipher.getInstance(key.getAlgorithm());
        decryptionCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SimpleCipherException(
                "Couldn't instantiate SimpleCipher because of " + ExceptionUtils.getMessage(e), e);
    } catch (Exception e) {
        throw new SimpleCipherException(
                "Couldn't instantiate SimpleCipher because of " + ExceptionUtils.getMessage(e), e);
    }
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

private static String getAlgorithm(SecretKey secretKey) {

    if (null == secretKey) {
        return null;
    }/*from  www .  j av a  2s  . c  o m*/

    if (secretKey.getAlgorithm().equals("AES")) {
        return EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;
    } else {
        throw new RuntimeException("SecretKey algorithm: " + secretKey.getAlgorithm() + " not supported.");
    }

}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

/**
 * TODO remove, used only in midpoint ninja cmd tool, not part of API
 *//*from   w ww  . j  a va2s . c  o  m*/
@Deprecated
public String getSecretKeyDigest(SecretKey key) throws EncryptionException {
    for (Map.Entry<String, SecretKey> entry : digestToSecretKeyHashMap.entrySet()) {
        if (entry.getValue().equals(key)) {
            return entry.getKey();
        }
    }

    throw new EncryptionException("Could not find hash for secret key algorithm " + key.getAlgorithm()
            + ". Hash values for keys must be recomputed during initialization");
}

From source file:org.fejoa.library.crypto.UserKeyParameters.java

static public SecretKey deriveUserKey(SecretKey baseKey, UserKeyParameters settings) throws CryptoException {
    byte[] baseKeyBytes = baseKey.getEncoded();
    assert baseKeyBytes.length == 32;
    ByteArrayOutputStream combinedKey = new ByteArrayOutputStream();
    try {//ww  w.  j  a v  a 2 s  .com
        combinedKey.write(baseKeyBytes);
        combinedKey.write(settings.userKeySalt);
    } catch (IOException e) {
        e.printStackTrace();
        // should not happen
        assert false;
    }

    MessageDigest messageDigest;
    try {
        messageDigest = getMessageDigest(settings.hashAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(e);
    }
    byte[] out = CryptoHelper.hash(combinedKey.toByteArray(), messageDigest);
    return CryptoHelper.secretKey(out, baseKey.getAlgorithm());
}

From source file:org.j2free.security.DESEncrypter.java

/**
 * /*from w  w w.  j a  v  a2  s  . co  m*/
 * @param passPhrase
 */
public DESEncrypter(String passPhrase) {

    try {
        // Create the key based on the passPhrase
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, ITERATION_COUNT);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

        encoder = Cipher.getInstance(key.getAlgorithm());
        decoder = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

        // Create the ciphers
        encoder.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        decoder.init(Cipher.DECRYPT_MODE, key, paramSpec);

    } catch (Exception e) {
        throw LaunderThrowable.launderThrowable(e);
    }
}

From source file:org.jamwiki.utils.Encryption.java

/**
 * Encrypt a String value using the DES encryption algorithm.
 * /*  w w w .  ja v  a2  s . co  m*/
 * @param unencryptedBytes
 *          The unencrypted String value that is to be encrypted.
 * @return An encrypted version of the String that was passed to this method.
 */
private static String encrypt64(byte[] unencryptedBytes)
        throws GeneralSecurityException, UnsupportedEncodingException {
    if (unencryptedBytes == null || unencryptedBytes.length == 0) {
        throw new IllegalArgumentException("Cannot encrypt a null or empty byte array");
    }
    SecretKey key = createKey();
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedBytes = Base64.encodeBase64(cipher.doFinal(unencryptedBytes));
    return bytes2String(encryptedBytes);
}

From source file:org.jamwiki.utils.Encryption.java

/**
 * Unencrypt a String value using the DES encryption algorithm.
 * /*from   w  ww  .  j a v a2 s.  c  om*/
 * @param encryptedString
 *          The encrypted String value that is to be unencrypted.
 * @return An unencrypted version of the String that was passed to this
 *         method.
 */
private static String decrypt64(String encryptedString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    if (StringUtils.isBlank(encryptedString)) {
        return encryptedString;
    }
    SecretKey key = createKey();
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] encryptedBytes = encryptedString.getBytes("UTF8");
    byte[] unencryptedBytes = cipher.doFinal(Base64.decodeBase64(encryptedBytes));
    return bytes2String(unencryptedBytes);
}

From source file:org.jboss.ejb3.examples.ch05.encryption.EncryptionBean.java

/**
 * Initializes this service before it may handle requests
 * //from w  w  w . j av  a 2  s. com
 * @throws Exception If some unexpected error occurred
 */
@PostConstruct
public void initialize() throws Exception {
    // Log that we're here
    log.info("Initializing, part of " + PostConstruct.class.getName() + " lifecycle");

    /*
     * Symmetric Encryption
     */

    // Obtain parameters used in initializing the ciphers
    final String cipherAlgorithm = DEFAULT_ALGORITHM_CIPHER;
    final byte[] ciphersSalt = DEFAULT_SALT_CIPHERS;
    final int ciphersIterationCount = DEFAULT_ITERATION_COUNT_CIPHERS;
    final String ciphersPassphrase = this.getCiphersPassphrase();

    // Obtain key and param spec for the ciphers
    final KeySpec ciphersKeySpec = new PBEKeySpec(ciphersPassphrase.toCharArray(), ciphersSalt,
            ciphersIterationCount);
    final SecretKey ciphersKey = SecretKeyFactory.getInstance(cipherAlgorithm).generateSecret(ciphersKeySpec);
    final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(ciphersSalt, ciphersIterationCount);

    // Create and init the ciphers
    this.encryptionCipher = Cipher.getInstance(ciphersKey.getAlgorithm());
    this.decryptionCipher = Cipher.getInstance(ciphersKey.getAlgorithm());
    encryptionCipher.init(Cipher.ENCRYPT_MODE, ciphersKey, paramSpec);
    decryptionCipher.init(Cipher.DECRYPT_MODE, ciphersKey, paramSpec);

    // Log
    log.info("Initialized encryption cipher: " + this.encryptionCipher);
    log.info("Initialized decryption cipher: " + this.decryptionCipher);

    /*
     * One-way Hashing
     */

    // Get the algorithm for the MessageDigest
    final String messageDigestAlgorithm = this.getMessageDigestAlgorithm();

    // Create the MessageDigest
    try {
        this.messageDigest = MessageDigest.getInstance(messageDigestAlgorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Could not obtain the " + MessageDigest.class.getSimpleName()
                + " for algorithm: " + messageDigestAlgorithm, e);
    }
    log.info("Initialized MessageDigest for one-way hashing: " + this.messageDigest);
}