Example usage for javax.crypto SecretKey getEncoded

List of usage examples for javax.crypto SecretKey getEncoded

Introduction

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

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java

public void validate(final String filename, final String password) throws Exception {
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    byte[] initVector = null;
    byte[] encryptedSampleBytes = null;
    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String zipEntryName = zipEntry.getName();
        if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            InputStream inputStream = encryptedFile.getInputStream(zipEntry);
            initVector = FileCopyUtils.copyToByteArray(inputStream);
            if (initVector.length != IV_SIZE) {
                throw new Exception("Secret file is corrupted or invalid secret file are being used.");
            }//from   www. j av a 2 s. c o m
        } else if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)) {
            InputStream inputStream = encryptedFile.getInputStream(zipEntry);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileCopyUtils.copy(inputStream, baos);
            encryptedSampleBytes = baos.toByteArray();
        }
    }

    if (initVector != null && encryptedSampleBytes != null) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        // generate the secret key
        SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);
        // create the cipher
        Cipher cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector));
        // decrypt the sample
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedSampleBytes);
        CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, cipher);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileCopyUtils.copy(cipherInputStream, baos);

        String sampleText = baos.toString();
        if (!sampleText.contains("This is sample text")) {
            throw new Exception("Upload parameters incorrect!");
        }
    }
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association setHandle(Association association) throws AssociationException, IOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException {
    ByteArrayOutputStream encodedAssociation = new ByteArrayOutputStream();
    String type = association.getType();
    if (type == Association.TYPE_HMAC_SHA1) {
        encodedAssociation.write(1);/*from   w  ww . jav a2 s.  co m*/
    } else if (type == Association.TYPE_HMAC_SHA256) {
        encodedAssociation.write(2);
    } else {
        throw new AssociationException("unknown type: " + type);
    }
    SecretKey macKey = association.getMacKey();
    byte[] macKeyBytes = macKey.getEncoded();
    encodedAssociation.write(macKeyBytes);
    Date expiry = association.getExpiry();
    Long time = expiry.getTime();
    DataOutputStream dos = new DataOutputStream(encodedAssociation);
    dos.writeLong(time);
    dos.flush();
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    byte[] iv = new byte[16];
    this.secureRandom.nextBytes(iv);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] handleValue = cipher.doFinal(encodedAssociation.toByteArray());
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    result.write(iv);
    result.write(handleValue);
    if (null != this.macSecretKeySpec) {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] toBeSigned = result.toByteArray();
        byte[] signature = mac.doFinal(toBeSigned);
        result = new ByteArrayOutputStream();
        result.write(signature);
        result.write(iv);
        result.write(handleValue);
    }
    String handle = Base64.encodeBase64URLSafeString(result.toByteArray());
    this.secureRandom.setSeed(result.toByteArray());
    if (handle.getBytes().length > 255) {
        throw new AssociationException("handle size > 255");
    }
    if (type == Association.TYPE_HMAC_SHA1) {
        return Association.createHmacSha1(handle, macKeyBytes, expiry);
    } else if (type == Association.TYPE_HMAC_SHA256) {
        return Association.createHmacSha256(handle, macKeyBytes, expiry);
    }
    throw new AssociationException("unknown type: " + type);
}

From source file:com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java

@Override
public QueryResult createKey(Param param, String owner)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    logger.info("User is trying to create key. userName:" + owner + ", keyName:" + param.getKeyName());
    File newKeyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
    if (newKeyfile.exists()) {
        logger.info("keyName \"" + param.getKeyName() + "\" exists, please choose another keyName.");
        return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_EXISTS), null);
    }/*  w  w  w.  j  a v  a2s  .  c om*/

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256);
    SecretKey secretKey = keyGen.generateKey();
    String hexkey = Hex.encodeHexString(secretKey.getEncoded());

    Properties prop = new Properties();
    prop.setProperty("owner", owner);
    prop.setProperty("keyName", param.getKeyName());
    prop.setProperty("hexkey", hexkey);
    prop.setProperty("users", param.getUsers());

    File keyFileFolder = new File(env.getProperty("keyfile.path"));
    if (!keyFileFolder.exists()) {
        keyFileFolder.mkdirs();
        Runtime.getRuntime().exec("chmod 700 " + env.getProperty("keyfile.path"));
    }
    prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
    Runtime.getRuntime().exec("chmod 600 " + env.getProperty("keyfile.path") + param.getKeyName());
    logger.info("save keyfile \"{}\" to keyfile folder: {}", param.getKeyName(),
            env.getProperty("keyfile.path"));

    return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + param.getKeyName() + ") created",
            null);
}

From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java

public String createPassword() throws CryptographyException {
    KeyGenerator kgen;/*from   w ww  .jav a  2s .c o  m*/
    try {
        kgen = KeyGenerator.getInstance(keyGenerator);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptographyException(e.getMessage());
    }

    kgen.init(passwordLength);

    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();

    return new String(Hex.encodeHex(raw));
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 *//*from   w  w w .  j av a 2 s .  c om*/
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}

From source file:sec_algo.commonenc.java

/**
* Creates a new AES key//from   w  w  w  . j a va 2 s. c  om
*/
public void makeKey() {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(AES_Key_Size);
        SecretKey aeskey = kgen.generateKey();
        key = aeskey.getEncoded();
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Decrypting text that is encrypted by the advanced encryption standard.
 *
 * @param password The char array containing of the plaintext password
 * @param encryptedBlock The Encrypted text to be targeted and decrypted.
 *
 * @return The decrypted byte array of the encrypted text.
 *//*from www . j a v a 2 s.co  m*/
public byte[] decrypt(char[] password, char[] encryptedBlock)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, DecoderException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password with the MD5 function and decode the encryptedBlock
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] decoded = Hex.decodeHex(encryptedBlock);

    // The decoded byte array has the IV, encryptedText, and salt bytes stored in that order.
    // The IV bytes are of length 16 and salt is of length 20.
    byte[] encryptedText = new byte[decoded.length - 36], ivBytes = new byte[16], salt = new byte[20];

    // The decoded bytes are ordered in the following form: ivBytes + encryptedText + saltBytes.
    // Extract the bytes into their corresponding array.
    System.arraycopy(decoded, 0, ivBytes, 0, ivBytes.length);
    System.arraycopy(decoded, ivBytes.length, encryptedText, 0, encryptedText.length);
    System.arraycopy(decoded, decoded.length - salt.length, salt, 0, salt.length);

    // generate the key from the acquired data
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // finally, attempt to decrypt the encryptedText
    cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
    return cipher.doFinal(encryptedText);
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception/*from  www.  j  a  va  2 s . co  m*/
 */
protected final void initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey tmp = factory.generateSecret(spec);

    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);

    if (log.isDebugEnabled())
        log.debug("Encrypting with: " + secret.getAlgorithm());

    cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
}

From source file:com.joyent.manta.util.HmacClonerTest.java

private void testHMacStateCanBeClonedAfterInitialization(SupportedCipherDetails cipherDetails,
        final String hmacName) {
    final SecretKey key = SecretKeyUtils.generate(cipherDetails);

    final HMac originalHmac = SupportedHmacsLookupMap.INSTANCE.get(hmacName).get();
    originalHmac.init(new KeyParameter(key.getEncoded()));
    final HMac clonedHmac = new HmacCloner().createClone(originalHmac);

    final byte[] inputData = RandomUtils.nextBytes(cipherDetails.getBlockSizeInBytes() * 3);
    originalHmac.update(inputData, 0, inputData.length);
    clonedHmac.update(inputData, 0, inputData.length);

    final byte[] originalComputed = new byte[originalHmac.getMacSize()];
    final byte[] clonedComputed = new byte[originalHmac.getMacSize()];
    originalHmac.doFinal(originalComputed, 0);
    clonedHmac.doFinal(clonedComputed, 0);

    AssertJUnit.assertArrayEquals(originalComputed, clonedComputed);
}

From source file:com.joyent.manta.util.HmacClonerTest.java

private void testHMacStateCanBeClonedAfterUse(final SupportedCipherDetails cipherDetails,
        final String hmacName) {
    final SecretKey key = SecretKeyUtils.generate(cipherDetails);

    final HMac originalHmac = SupportedHmacsLookupMap.INSTANCE.get(hmacName).get();
    originalHmac.init(new KeyParameter(key.getEncoded()));

    final byte[] firstUpdate = RandomUtils.nextBytes(cipherDetails.getBlockSizeInBytes() * 3);
    originalHmac.update(firstUpdate, 0, firstUpdate.length);
    final HMac clonedHmac = new HmacCloner().createClone(originalHmac);

    final byte[] inputData = RandomUtils.nextBytes(cipherDetails.getBlockSizeInBytes() * 3);
    originalHmac.update(inputData, 0, inputData.length);
    clonedHmac.update(inputData, 0, inputData.length);

    final byte[] originalComputed = new byte[originalHmac.getMacSize()];
    final byte[] clonedComputed = new byte[originalHmac.getMacSize()];

    originalHmac.doFinal(originalComputed, 0);
    clonedHmac.doFinal(clonedComputed, 0);

    AssertJUnit.assertArrayEquals(originalComputed, clonedComputed);
}