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:dualcontrol.CryptoHandler.java

public void handle(DualControlKeyStoreSession dualControl, Socket socket) throws Exception {
    try {//from  w w w  . jav a 2s.  c  o m
        this.dualControl = dualControl;
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        int length = dis.readShort();
        byte[] bytes = new byte[length];
        dis.readFully(bytes);
        String data = new String(bytes);
        String[] fields = data.split(":");
        String mode = fields[0];
        String alias = fields[1];
        this.dos = new DataOutputStream(socket.getOutputStream());
        if (mode.equals("GETKEY")) {
            if (enableGetKey) {
                SecretKey key = dualControl.loadKey(alias);
                dos.writeUTF(key.getAlgorithm());
                write(key.getEncoded());
            }
        } else {
            cipher(mode, alias, fields[2], fields[3], fields[4]);
        }
    } finally {
        dos.close();
    }
}

From source file:dualcontrol.CryptoHandler.java

private void cipher(String mode, String alias, String transformation, String ivString, String dataString)
        throws Exception {
    logger.debug(join("cipher", alias, transformation, mode));
    SecretKey key = dualControl.loadKey(alias);
    logger.debug("keyalg " + key.getAlgorithm());
    Cipher cipher = Cipher.getInstance(transformation);
    logger.debug("mode " + mode);
    if (mode.equals("DECRYPT")) {
        this.ivBytes = Base64.decodeBase64(ivString);
        logger.debug("iv " + Base64.encodeBase64String(ivBytes));
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        this.dataBytes = cipher.doFinal(Base64.decodeBase64(dataString));
        write(ivBytes, dataBytes);//ww  w .  j a  va 2s .  c o  m
    } else if (mode.equals("ENCRYPT")) {
        this.ivBytes = getIvBytes(ivString);
        logger.debug("iv " + Base64.encodeBase64String(ivBytes));
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        long startTime = System.nanoTime();
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        this.dataBytes = cipher.doFinal(dataString.getBytes());
        logger.info("encrypt time nanos " + Nanos.elapsed(startTime));
        write(ivBytes, dataBytes);
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void writeKeyToPath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/* w  w  w  . jav  a  2 s  .com*/
    Path path = file.toPath();

    SupportedCipherDetails cipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;
    byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded();
    SecretKey key = SecretKeyUtils.loadKey(keyBytes, cipherDetails);
    SecretKeyUtils.writeKeyToPath(key, path);

    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, cipherDetails);
    Assert.assertEquals(actual.getAlgorithm(), key.getAlgorithm());
    Assert.assertTrue(Arrays.equals(key.getEncoded(), actual.getEncoded()));
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void canLoadKeyFromFilePath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/*w  ww  .j a  va2s  . c om*/
    FileUtils.writeByteArrayToFile(file, keyBytes);
    Path path = file.toPath();

    SecretKey expected = SecretKeyUtils.loadKey(keyBytes, AesGcmCipherDetails.INSTANCE_128_BIT);
    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, AesGcmCipherDetails.INSTANCE_128_BIT);

    Assert.assertEquals(actual.getAlgorithm(), expected.getAlgorithm());
    Assert.assertTrue(Arrays.equals(expected.getEncoded(), actual.getEncoded()),
            "Secret key loaded from URI doesn't match");
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.common.AerohiveEncryptTool.java

public AerohiveEncryptTool(String arg_Key) {
    if (arg_Key != null && !arg_Key.trim().equals(""))
        m_Str_Key = arg_Key;

    try {/*w  ww  . j a  v a  2  s  .com*/
        // Create the key
        KeySpec keySpec = new PBEKeySpec(m_Str_Key.toCharArray(), m_Byte_Salt, m_Int_IterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        m_Cipher_Ecipher = Cipher.getInstance(key.getAlgorithm());
        m_Cipher_Dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(m_Byte_Salt, m_Int_IterationCount);

        // Create the ciphers
        m_Cipher_Ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        m_Cipher_Dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
        //DebugUtil.commonDebugWarn(e.getMessage());
    }
}

From source file:de.alpharogroup.crypto.simple.SimpleDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException//from w  ww  .ja  v a 2 s  .  c o m
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the SecretKeyFactory object fails.
 * @throws InvalidKeyException
 *             is thrown if initialization of the cypher object fails.
 */
private void initialize() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        KeySpec keySpec = null;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        }
        if (this.getPrivateKey() == null) {
            keySpec = new PBEKeySpec(CryptConst.PRIVATE_KEY.toCharArray());
        }
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(CryptConst.PBEWITH_MD5AND_DES);
        final SecretKey key = factory.generateSecret(keySpec);
        this.cipher = Cipher.getInstance(key.getAlgorithm());
        final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(CryptConst.SALT,
                CryptConst.ITERATIONCOUNT);
        this.cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}

From source file:de.alpharogroup.crypto.simple.SimpleEncryptor.java

/**
 * Initializes the {@link SimpleEncryptor} object.
 * //from  ww  w.ja  v  a 2  s.c o m
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the SecretKeyFactory object fails.
 * @throws InvalidKeyException
 *             is thrown if initialization of the cypher object fails.
 */
private void initialize() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        final KeySpec keySpec;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        } else {
            keySpec = new PBEKeySpec(CryptConst.PRIVATE_KEY.toCharArray());
        }
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(CryptConst.PBEWITH_MD5AND_DES);
        final SecretKey key = factory.generateSecret(keySpec);
        this.cipher = Cipher.getInstance(key.getAlgorithm());
        final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(CryptConst.SALT,
                CryptConst.ITERATIONCOUNT);
        this.cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void canLoadKeyFromURIPath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/*from  w  w w .  ja va2  s  .  c o m*/
    FileUtils.writeByteArrayToFile(file, keyBytes);
    URI uri = file.toURI();

    SecretKey expected = SecretKeyUtils.loadKey(keyBytes, AesGcmCipherDetails.INSTANCE_128_BIT);
    SecretKey actual = SecretKeyUtils.loadKeyFromPath(Paths.get(uri), AesGcmCipherDetails.INSTANCE_128_BIT);

    Assert.assertEquals(actual.getAlgorithm(), expected.getAlgorithm());
    Assert.assertTrue(Arrays.equals(expected.getEncoded(), actual.getEncoded()),
            "Secret key loaded from URI doesn't match");
}

From source file:by.bsuir.chujko.model.entities.security.StringCrypter.java

/**
 * To update secret key.//from  www . ja  v  a  2  s  .co m
 * 
 * @param key
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException 
 */
private void updateSecretKey(SecretKey key)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
    ecipher = Cipher.getInstance(key.getAlgorithm());
    dcipher = Cipher.getInstance(key.getAlgorithm());
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
}

From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context//from   w w  w .ja  v a 2 s.  c  om
 */
public Item evaluateItem(XPathContext xpathContext) throws XPathException {
    final String key = argument[0].evaluateAsString(xpathContext).toString();
    final String data = argument[1].evaluateAsString(xpathContext).toString();
    final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString();
    final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", "");
    final String encoding = argument != null && argument.length >= 4
            ? argument[3].evaluateAsString(xpathContext).toString()
            : kBASE64;

    if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException(
                "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this));
    }

    if (!kSUPPORTED_ENCODINGS.contains(encoding)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'",
                xformsElement.getTarget(), this));
    }

    try {
        // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104
        // In practice, you would save this key.
        SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm);

        // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        mac.update(data.getBytes("utf-8"));

        byte[] digest = mac.doFinal();

        final BinaryEncoder encoder;
        if ("base64".equals(encoding)) {
            encoder = new Base64(digest.length, "".getBytes(), false);
        } else {
            encoder = new Hex();
        }

        return new StringValue(new String(encoder.encode(digest), "ASCII"));

    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(e);
    } catch (UnsupportedEncodingException e) {
        throw new XPathException(e);
    } catch (EncoderException e) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(
                new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this));
    } catch (InvalidKeyException e) {
        throw new XPathException(e);
    }

}