Example usage for javax.crypto.spec SecretKeySpec SecretKeySpec

List of usage examples for javax.crypto.spec SecretKeySpec SecretKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec SecretKeySpec SecretKeySpec.

Prototype

public SecretKeySpec(byte[] key, String algorithm) 

Source Link

Document

Constructs a secret key from the given byte array.

Usage

From source file:de.taimos.dvalin.interconnect.model.MessageCryptoUtil.java

private static Cipher getCipher(int mode) throws Exception {
    final SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(MessageCryptoUtil.AES_KEY.toCharArray()),
            "AES");
    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(mode, skeySpec);//  ww  w  .ja v a  2s  . c o  m
    return cipher;
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.CookieEncrypter.java

public CookieEncrypter() throws Exception {
    // Get the KeyGenerator
    KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
    kgen.init(BIT_LENGTH); // 192 and 256 bits may not be available

    // Generate the secret key specs
    SecretKey skey = kgen.generateKey();
    byte[] secretKey = skey.getEncoded();
    keySpec = new SecretKeySpec(secretKey, ALGORITHM);
}

From source file:S3ClientSideEncryptionWithSymmetricMasterKey.java

public static SecretKey loadSymmetricAESKey(String path, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
    // Read private key from file.
    File keyFile = new File(path + "/" + keyName);
    FileInputStream keyfis = new FileInputStream(keyFile);
    byte[] encodedPrivateKey = new byte[(int) keyFile.length()];
    keyfis.read(encodedPrivateKey);//w ww .j av a  2s.c  o m
    keyfis.close();

    // Generate secret key.
    return new SecretKeySpec(encodedPrivateKey, "AES");
}

From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java

/**
 * Decrypt the encrypted value with provided key
 */// ww  w  .  ja  va 2s . c o  m
public static String decrypt(String key, String encryptedValue) {
    String decryptedString = null;
    try {
        IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        decryptedString = new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)));

    } catch (Exception ex) {
        System.out.println("Caught exception while decrypting string");
        ex.printStackTrace();
    }

    return decryptedString;
}

From source file:io.apiman.common.util.AesEncrypter.java

/**
 * Returns a {@link SecretKeySpec} given a secret key.
 * @param secretKey// www . j  a  va2 s  .c om
 */
private static SecretKeySpec keySpecFromSecretKey(String secretKey) {
    if (!keySpecs.containsKey(secretKey)) {
        byte[] ivraw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(ivraw, "AES"); //$NON-NLS-1$
        keySpecs.put(secretKey, skeySpec);
    }
    return keySpecs.get(secretKey);
}

From source file:net.oauth.signature.GoogleCodeCompatibilityTests.java

/**
 * tests compatibilty with the google code HMAC_SHA1 signature.
 *//*from  w  ww .  j a v  a 2 s .  c  o m*/
@Test
public void testHMAC_SHA1_1() throws Exception {
    HMAC_SHA1 theirMethod = new HMAC_SHA1();
    String baseString = "GET&http%3A%2F%2Flocalhost%3A8080%2Fgrailscrowd%2Foauth%2Frequest_token&oauth_consumer_key%3Dtonrconsumerkey%26oauth_nonce%3D1227967049787975000%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1227967049%26oauth_version%3D1.0";
    theirMethod.setConsumerSecret("xxxxxx");
    theirMethod.setTokenSecret("");
    SecretKeySpec spec = new SecretKeySpec("xxxxxx&".getBytes("UTF-8"), HMAC_SHA1SignatureMethod.MAC_NAME);
    HMAC_SHA1SignatureMethod ourMethod = new HMAC_SHA1SignatureMethod(spec);
    String theirSignature = theirMethod.getSignature(baseString);
    String ourSignature = ourMethod.sign(baseString);
    assertEquals(theirSignature, ourSignature);
}

From source file:uploadProcess.java

public static boolean encrypt(File inputFolder, File outputFolder, String fileName, String patientID) {
    try {// w w  w  .  j a  va2  s.  co m

        String ukey = GetKey.getPatientKey(patientID);
        File filePath = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
        FileInputStream fis = new FileInputStream(filePath);
        File outputFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        byte[] k = ukey.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        //            System.out.println(key);
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.ENCRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(fos, enc);
        byte[] buf = new byte[1024];
        int read;
        while ((read = fis.read(buf)) != -1) {
            cos.write(buf, 0, read);
        }
        fis.close();
        fos.flush();
        cos.close();

        //Upload File to cloud
        DropboxUpload upload = new DropboxUpload();
        upload.uploadFile(outputFolder, fileName, StoragePath.getDropboxDir() + patientID);
        DeleteDirectory.delete(outputFolder);
        return true;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:com.google.walkaround.util.server.auth.DigestUtils2.java

/**
 * Computes the RFC2104 SHA1 HMAC digest for the given message and secret.
 *
 * @param message the data to compute the digest of
 *///from w  ww .  ja v a 2  s . c o  m
public static byte[] sha1hmac(Secret key, byte[] message) {
    try {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.data, HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] ret = mac.doFinal(message);
        assert ret.length == SHA1_BLOCK_SIZE;
        return ret;

    } catch (InvalidKeyException e) {
        throw new RuntimeException("Failed to generate HMAC", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to generate HMAC", e);
    }
}

From source file:com.google.u2f.gaedemo.impl.DataStoreImpl.java

@Override
public String storeSessionData(EnrollSessionData sessionData) {

    SecretKey key = new SecretKeySpec(SecretKeys.get().sessionEncryptionKey(), "AES");
    byte[] ivBytes = new byte[16];
    random.nextBytes(ivBytes);//from www .  j a va 2  s.c o  m
    final IvParameterSpec IV = new IvParameterSpec(ivBytes);
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, IV);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }

    SealedObject sealed;
    try {
        sealed = new SealedObject(sessionData, cipher);
    } catch (IllegalBlockSizeException | IOException e) {
        throw new RuntimeException(e);
    }

    ByteArrayOutputStream out;
    try {
        out = new ByteArrayOutputStream();
        ObjectOutputStream outer = new ObjectOutputStream(out);

        outer.writeObject(sealed);
        outer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return Base64.encodeBase64URLSafeString(out.toByteArray());
}

From source file:Clases.cCifrado.java

public String Desencriptar(String textoEncriptado) {

    String secretKey = "MARSOFT"; //llave para encriptar datos
    String base64EncryptedString = "";

    try {/*from w  w  w .  j av a  2s .  c o  m*/
        byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("utf-8"));
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);

        byte[] plainText = decipher.doFinal(message);

        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (Exception ex) {
    }
    return base64EncryptedString;
}