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:com.cloud.server.ConfigurationServerImpl.java

private void updateSSOKey() {
    try {/*from  w w w  .  j  a v a 2  s. c om*/
        String encodedKey = null;

        // Algorithm for SSO Keys is SHA1, should this be configurable?
        KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = generator.generateKey();
        encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());

        _configDao.update(Config.SSOKey.key(), Config.SSOKey.getCategory(), encodedKey);
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating sso key", ex);
    }
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a string using a random session key
 *
 * @param plaintext/*from   w ww.java2  s  .co  m*/
 * @return encrypted String
 * @throws Exception
 * @author Peli
 */
public String encryptWithSessionKey(String plaintext) throws CryptoHelperException {
    if (debug) {
        Log.i(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }
    byte[] cipherSessionKey = {};
    byte[] ciphertext = {};

    // First create a session key
    SecretKey sessionKey = null;
    byte[] sessionKeyEncoded = null;
    String sessionKeyString = null;
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256); // needs 96 bytes
        //keygen.init(128); // needs 64 bytes
        sessionKey = keygen.generateKey();
        sessionKeyEncoded = sessionKey.getEncoded();
        sessionKeyString = new String(sessionKeyEncoded);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
    }

    // Convert this to a Pbe key
    PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(sessionKeyString.toCharArray());
    SecretKey sessionPbeKey = null;
    try {
        sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "setPassword(): " + e.toString());
    }

    // Encrypt the session key using the master key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
    }

    // Now encrypt the text using the session key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, sessionPbeKey, pbeParamSpec);
        ciphertext = pbeCipher.doFinal(plaintext.getBytes());
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey2(): " + e.toString());
    }

    String stringCipherVersion = "A";
    String stringCipherSessionKey = toHexString(cipherSessionKey);
    String stringCiphertext = toHexString(ciphertext);
    if (debug) {
        Log.i(TAG, "Length: " + stringCipherSessionKey.length() + ", " + stringCipherSessionKey);
    }

    StringBuilder sb = new StringBuilder(
            stringCipherVersion.length() + stringCipherSessionKey.length() + stringCiphertext.length());
    sb.append(stringCipherVersion);
    sb.append(stringCipherSessionKey);
    sb.append(stringCiphertext);
    return sb.toString();
}

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

protected final SecuredCEK secureCEK(SecretKey toBeEncrypted, EncryptionMaterials materials,
        Provider cryptoProvider) {
    Key kek;/* w  w  w  .ja  v  a2 s . c  o  m*/
    if (materials.getKeyPair() != null) {
        // Do envelope encryption with public key from key pair
        kek = materials.getKeyPair().getPublic();
    } else {
        // 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:ropes.Crypto.java

/**
* If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). 
* We have the password from initializing the class. pass the iv and salt here which is
* obtained when encrypting the file initially.
*   /*from   w ww.ja v  a 2s  . c o  m*/
* @param initvec
* @param salt
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public void setupDecrypt(String initvec, String salt) {
    try {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        SecretKey secret = null;

        // since we pass it as a string of input, convert to a actual byte buffer here
        mSalt = Hex.decodeHex(salt.toCharArray());
        Db("got salt " + Hex.encodeHexString(mSalt));

        // get initialization vector from passed string
        mInitVec = Hex.decodeHex(initvec.toCharArray());
        Db("got initvector :" + Hex.encodeHexString(mInitVec));

        /* Derive the key, given password and salt. */
        // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
        // The end user must also install them (not compiled in) so beware.
        // see here:
        // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

        tmp = factory.generateSecret(spec);
        secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        /* Decrypt the message, given derived key and initialization vector. */
        mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));

    } catch (DecoderException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a file using a random session key
 *
 * @param contentResolver is used to be able to read the stream
 * @param fileUri         is the stream or file to read from
 * @return Uri to the created plaintext file
 * @throws Exception/*  www. ja v a  2 s  .  c  om*/
 * @author Peli
 */
public Uri encryptFileWithSessionKey(ContentResolver contentResolver, Uri fileUri)
        throws CryptoHelperException {
    if (debug) {
        Log.d(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }

    String outputPath = "";
    try {
        InputStream is;
        if (fileUri.getScheme().equals("file")) {
            is = new java.io.FileInputStream(fileUri.getPath());
            outputPath = fileUri.getPath() + OISAFE_EXTENSION;
        } else {
            is = contentResolver.openInputStream(fileUri);
            outputPath = getTemporaryFileName();
        }

        FileOutputStream os = new FileOutputStream(outputPath);

        byte[] cipherSessionKey = {};
        //         byte[] ciphertext = {};

        // First create a session key
        SecretKey sessionKey = null;
        byte[] sessionKeyEncoded = null;
        //         String sessionKeyString = null;
        try {
            KeyGenerator keygen;
            keygen = KeyGenerator.getInstance("AES");
            keygen.init(256); // needs 96 bytes
            //keygen.init(128); // needs 64 bytes
            sessionKey = keygen.generateKey();
            sessionKeyEncoded = sessionKey.getEncoded();
            //            sessionKeyString = new String(sessionKeyEncoded);
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "generateMasterKey(): " + e.toString());
            return null;
        }

        // Encrypt the session key using the master key
        try {
            pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
            cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
            status = true;
        } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
                | InvalidKeyException e) {
            Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
        }
        if (!status) {
            return null;
        }
        status = false;

        String stringCipherVersion = "A";
        byte[] bytesCipherVersion = stringCipherVersion.getBytes();
        os.write(bytesCipherVersion, 0, bytesCipherVersion.length);

        os.write(cipherSessionKey, 0, cipherSessionKey.length);

        if (debug) {
            Log.d(TAG, "bytesCipherVersion.length: " + bytesCipherVersion.length);
        }
        if (debug) {
            Log.d(TAG, "cipherSessionKey.length: " + cipherSessionKey.length);
        }

        Trivium tri = new Trivium();
        try {
            tri.setupKey(Trivium.MODE_ENCRYPT, sessionKeyEncoded, 0);
            tri.setupNonce(sessionKeyEncoded, 10);

            // Create the byte array to hold the data
            final int bytesLen = 4096; // buffer length
            byte[] bytesIn = new byte[bytesLen];
            byte[] bytesOut = new byte[bytesLen];

            int offset = 0;
            int numRead = 0;
            while ((numRead = is.read(bytesIn, 0, bytesLen)) >= 0) {
                tri.process(bytesIn, 0, bytesOut, 0, numRead);

                os.write(bytesOut, 0, numRead);
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < is.available()) {
                throw new IOException("Could not completely read file ");
            }

            // Close the input stream and return bytes
            is.close();
            os.close();

            // Securely delete the original file:
            SecureDelete.delete(new File(fileUri.getPath()));
            status = true;

        } catch (ESJException e) {
            Log.e(TAG, "Error encrypting file", e);
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found", e);
    } catch (IOException e) {
        Log.e(TAG, "IO Exception", e);
    }

    if (status == false) {
        return null;
    }
    return Uri.fromFile(new File(outputPath)); //Uri.parse("file://" + outputPath); // TODO: UUEncode
}

From source file:servlets.SecretKeyProvider.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w  w .  j  a v  a  2 s . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String opcion = request.getParameter("opcion");

    switch (opcion) {
    case "public":
        InputStream is = getServletContext().getResourceAsStream("/WEB-INF/server1024.publica");
        IOUtils.copy(is, response.getOutputStream());
        break;

    case "secret": {
        try {
            SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
            request.getSession().setAttribute("clave", secretKey);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC

            byte[] bufferPriv = new byte[5000];
            InputStream in = getServletContext().getResourceAsStream("/WEB-INF/server1024.privada");
            int chars = in.read(bufferPriv, 0, 5000);
            in.close();

            byte[] bufferPriv2 = new byte[chars];
            System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars);

            // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8
            PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2);
            PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec);

            // PASO 3a: Poner cifrador en modo CIFRADO
            cifrador.init(Cipher.ENCRYPT_MODE, clavePrivada2); // Cifra con la clave publica

            byte[] bufferCifrado = cifrador.doFinal(secretKey.getEncoded());

            String mandar = new String(Base64.encodeBase64(bufferCifrado));
            response.getWriter().print(mandar);

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    }
}

From source file:com.denel.facepatrol.MainActivity.java

private void encryptfile(Context mcontext, SecretKey key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    // This will probably change when I will the database will be downloaded from the server
    boolean db_file_exists = mcontext.getDatabasePath(dbname).exists();
    InputStream fis = null;/*from  www  .  j av  a  2  s . co  m*/
    File infile = mcontext.getDatabasePath(dbname);
    // check if database file exists to prevent downloading the file each start
    if (db_file_exists) {
        fis = new FileInputStream(infile);
    } else {
        fis = mcontext.getAssets().open(dbname);
    }
    // This stream write the encrypted text. This stream will be wrapped by another stream. 
    FileOutputStream fos = new FileOutputStream(mcontext.getDatabasePath(dbname_en).getAbsolutePath());
    // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 
    SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES");
    // Create cipher 
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream 
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes 
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    } // Flush and close streams. 
    cos.flush();
    cos.close();
    fis.close();
    // delete the decrypted file
    if (infile.exists()) {
        infile.delete();
    }
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private void encryptAndWriteAESKey(SecretKey aeskey, File dest)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
    Cipher keyc;//  w  w w .j a  v a2 s  .  co  m
    AssetManager am = getAssets();
    InputStream in = am.open("mouflon_key.pub");
    byte[] readFromFile = new byte[in.available()];
    //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value
    in.read(readFromFile);
    keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something.
    KeyFactory kf = KeyFactory.getInstance("RSA");
    KeySpec ks = new X509EncodedKeySpec(readFromFile);
    RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks);
    keyc.init(Cipher.ENCRYPT_MODE, key);
    //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded());
    FileOutputStream out = new FileOutputStream(dest);
    CipherOutputStream outcipher = new CipherOutputStream(out, keyc);
    outcipher.write(aeskey.getEncoded());
    outcipher.close();
    out.close();
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Common payload content encryption method which is called after sanity
 * checks, and after any content signing is performed.
 * /*from w  w w.  j ava2s  .c o m*/
 * @throws Exception 
 */
private void doEncryption() throws Exception {
    // Make the one-time symmetric key, and encrypt the payload content using it.
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(AESKEYSIZE);
    SecretKey key = kgen.generateKey();
    String cipherData = doAESEncryption(key);

    // Start constructing the XML Encryption "EncryptedData" element. The main 
    // payload encryption is AES-256/CBC
    //
    StringBuilder sb = new StringBuilder(
            "<xenc:EncryptedData xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\">");
    sb.append("<xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>");

    // And then the KeyInfo which is the symmetric key byte[] encrypted for each
    // reader certificate.
    //
    sb.append("<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">");
    byte[] keyMaterial = key.getEncoded();
    for (X509Certificate x : readerCerts) {
        sb.append(doRSASymmetricKeyEncryption(x, keyMaterial));
    }
    sb.append("</ds:KeyInfo>");
    sb.append(cipherData);
    sb.append("</xenc:EncryptedData>");

    // Set the payloadBody to the EncryptedData, and the "encrypted" flag to "true".
    // Note that "base64" and "compressed" apply to the *cleartext*, and so are not
    // altered by this operation. The same goes for the mime type. Receiving systems
    // that decrypt the payload will need these other data set correctly in order to
    // convert the encrypted and possibly otherwise-processed content into something
    // they can use.
    //
    payloadBody = sb.toString();
    encrypted = true;

    // Make sure we overwrite the key byte[] before we leave, and mark the
    // one-time secret key null.
    //
    for (int i = 0; i < keyMaterial.length; i++) {
        keyMaterial[i] = 0;
    }
    key = null;
}

From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) {
    SecretKey tempKey = null;
    IvParameterSpec tempIvSpec = null;
    if (encrySrvConfig.getEncryptSalt() == null) {
        throw new IllegalArgumentException(
                "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString());
    }//ww  w .j  av  a  2s .  c om
    if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) {
        LOG.debug("Set the Encryption service password and encrypt salt");
        String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true);
        final Random random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        String encodedSalt = Base64.getEncoder().encodeToString(salt);
        encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd)
                .setEncryptSalt(encodedSalt).build();
        updateEncrySrvConfig(newPwd, encodedSalt);
        initializeConfigDataTree(encrySrvConfig, dataBroker);
    }
    final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt());
    try {
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod());
        final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt,
                encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength());
        tempKey = keyFactory.generateSecret(spec);
        tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType());
        tempIvSpec = new IvParameterSpec(enryptionKeySalt);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOG.error("Failed to initialize secret key", e);
    }
    key = tempKey;
    ivspec = tempIvSpec;
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create encrypt cipher.", e);
    }
    this.encryptCipher = cipher;
    cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create decrypt cipher.", e);
    }
    this.decryptCipher = cipher;
}