Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator generateKey.

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 192 bit key that is
 * encrypted using a 3DES key.  Then reverse by decrypting 
 * EncryptedKey by hand/*from  w  ww .  j av a2 s .c o m*/
 */

public void testAES192ElementAES256KWCipher() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding && haveKeyWraps) {

        source = toString(d);

        // Set up a Key Encryption Key
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        Key kek = keyFactory.generateSecret(keySpec);

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(192);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_192);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, null);

        EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee);

        if (encryptedData == null) {
            System.out.println("ed is null");
        } else if (encryptedData.getKeyInfo() == null) {
            System.out.println("ki is null");
        }
        EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0);

        if (ek != null) {
            XMLCipher keyCipher = XMLCipher.getInstance();
            keyCipher.init(XMLCipher.UNWRAP_MODE, kek);
            key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm());
        }

        // Create a new cipher just to be paranoid
        XMLCipher cipher3 = XMLCipher.getInstance();
        cipher3.init(XMLCipher.DECRYPT_MODE, key);
        dd = cipher3.doFinal(ed, ee);

        target = toString(dd);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES192ElementAES256KWCipher skipped as necessary algorithms not available");
    }
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

/**
 * Builds the SOAP envelope with encrypted Body and adds encrypted key.
 * <p/>/*from  w w w .j a  v a  2 s . c  o m*/
 * This function performs several steps:
 * <p/>
 * <ul>
 * <li>    First step: set the encoding namespace in the SOAP:Envelope </li>
 * <li>    Second step: generate a symmetric key (session key) for
 * the selected symmetric encryption algorithm, and set the cipher
 * into encryption mode.
 * </li>
 * <li> Third step: get the data to encrypt.
 * We always encrypt the complete first child element of
 * the SOAP Body element
 * </li>
 * <li>    Forth step: encrypt data, and set neccessary attributes in
 * <code>xenc:EncryptedData</code>
 * </li>
 * <li>    Fifth step: get the certificate that contains the public key for
 * the    public key algorithm that will encrypt the generated symmetric
 * (session) key. Up to now we support RSA 1-5 as public key
 * algorithm.
 * </li>
 * <li>    Sixth step: setup the <code>wsse:Security</code> header block </li>
 * </ul>
 *
 * @param doc    the SOAP envelope as <code>Document</code> with
 *               plaintext Body
 * @param crypto an instance of the Crypto API to handle keystore and
 *               Certificates
 * @return the SOAP envelope with encrypted Body as <code>Document
 *         </code>
 * @throws WSSecurityException
 * @deprecated replaced by
 *             {@link WSSecEncrypt#build(Document, Crypto, WSSecHeader)}
 */
public Document build(Document doc, Crypto crypto) throws WSSecurityException {
    doDebug = log.isDebugEnabled();

    if (keyIdentifierType == WSConstants.EMBEDDED_KEYNAME
            || keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        return buildEmbedded(doc);
    }

    long t0 = 0, t1 = 0, t2 = 0, t3 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    if (doDebug) {
        log.debug("Beginning Encryption...");
    }

    /*
     * Second step: generate a symmetric key (session key) for
     * this alogrithm, and set the cipher into encryption mode.
     */
    // This variable is made a classs attribute :: SecretKey symmetricKey = null;
    this.encryptionKey = this.symmetricKey;
    if (encryptionKey == null) {
        KeyGenerator keyGen = getKeyGenerator();
        this.encryptionKey = keyGen.generateKey();
    }
    Vector encDataRefs = doEncryption(doc, this.encryptionKey);

    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    /*
     * At this point data is encrypted with the symmetric key and can be
     * referenced via the above Id
     */

    /*
     * Fifth step: get the certificate that contains the public key for the
     * public key algorithm that will encrypt
     * the generated symmetric (session) key.
     * Up to now we support RSA 1-5 as public key algorithm
     */
    X509Certificate remoteCert = null;
    if (useThisCert != null) {
        remoteCert = useThisCert;
    } else {
        X509Certificate[] certs = crypto.getCertificates(user);
        if (certs == null || certs.length <= 0) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound",
                    new Object[] { user, "encryption" });
        }
        remoteCert = certs[0];
    }
    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
    }
    Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
    try {
        cipher.init(Cipher.ENCRYPT_MODE, remoteCert);
    } catch (InvalidKeyException e) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e);
    }
    byte[] encKey = this.encryptionKey.getEncoded();
    if (doDebug) {
        log.debug("cipher blksize: " + cipher.getBlockSize() + ", symm key length: " + encKey.length);
    }
    if (cipher.getBlockSize() < encKey.length) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyTransp",
                new Object[] { "public key algorithm too weak to encrypt symmetric key" });
    }
    byte[] encryptedKey = null;
    try {
        encryptedKey = cipher.doFinal(encKey);
    } catch (IllegalStateException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    } catch (IllegalBlockSizeException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    } catch (BadPaddingException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    }
    Text keyText = WSSecurityUtil.createBase64EncodedTextNode(doc, encryptedKey);

    /*
     * Now we need to setup the wsse:Security header block
     * 1) get (or create) the wsse:Security header block
     * 2) create the xenc:EncryptedKey element. This already includes
     *    the ExcrpytionMethod element with attributes that define
     *    the key transport encryption algorithm
     * 3) Generate ds:KeyInfo element, this wraps the wsse:SecurityTokenReference
     * 4) set up the SecurityTokenReference, either with KeyIdentifier or
     *    X509IssuerSerial. The SecTokenRef defines how to get to security
     *    token used to encrypt the session key (this security token usually
     *    contains a public key)
     * 5) Create the CipherValue element structure and insert the encrypted
     *    session key
     * 6) The last step sets up the reference list that pints to the encrypted
     *    data that was encrypted with this encrypted session key :-)
     */
    Element wsseSecurity = insertSecurityHeader(doc);
    Element xencEncryptedKey = createEncryptedKey(doc, keyEncAlgo);
    if (parentNode == null) {
        WSSecurityUtil.prependChildElement(wsseSecurity, xencEncryptedKey);
    } else {
        WSSecurityUtil.prependChildElement(parentNode, xencEncryptedKey);
    }
    SecurityTokenReference secToken = new SecurityTokenReference(doc);

    switch (keyIdentifierType) {
    case WSConstants.X509_KEY_IDENTIFIER:
        secToken.setKeyIdentifier(remoteCert);
        // build a key id class??
        break;

    case WSConstants.SKI_KEY_IDENTIFIER:
        secToken.setKeyIdentifierSKI(remoteCert, crypto);
        break;

    case WSConstants.THUMBPRINT_IDENTIFIER:
        secToken.setKeyIdentifierThumb(remoteCert);
        break;

    case WSConstants.ISSUER_SERIAL:
        XMLX509IssuerSerial data = new XMLX509IssuerSerial(doc, remoteCert);
        X509Data x509Data = new X509Data(doc);
        x509Data.add(data);
        secToken.setX509IssuerSerial(x509Data);
        break;

    case WSConstants.BST_DIRECT_REFERENCE:
        Reference ref = new Reference(doc);
        String certUri = wssConfig.getIdAllocator().createId("EncCertId-", remoteCert);
        ref.setURI("#" + certUri);
        BinarySecurity bstToken = null;
        bstToken = new X509Security(doc);
        ((X509Security) bstToken).setX509Certificate(remoteCert);
        bstToken.setID(certUri);
        ref.setValueType(bstToken.getValueType());
        secToken.setReference(ref);
        WSSecurityUtil.prependChildElement(wsseSecurity, bstToken.getElement());
        break;

    default:
        throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
    }
    KeyInfo keyInfo = new KeyInfo(doc);
    keyInfo.addUnknownElement(secToken.getElement());
    xencEncryptedKey.appendChild(keyInfo.getElement());

    Element xencCipherValue = createCipherValue(doc, xencEncryptedKey);
    xencCipherValue.appendChild(keyText);
    createDataRefList(doc, xencEncryptedKey, encDataRefs);
    log.debug("Encryption complete.");
    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
        tlog.debug("EncryptBody: symm-enc " + (t1 - t0) + " cert " + (t2 - t1) + " key-encrypt " + (t3 - t2));
    }
    return doc;
}

From source file:com.example.android.fingerprintdialog.MainActivity.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint./*from   ww w.  j  a v a 2 s .  c  o  m*/
 */
@TargetApi(VERSION_CODES.M)
public void createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        mKeyStore.load(null);

        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        // Require the user to authenticate with a fingerprint to authorize every use
                        // of the key
                        .setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException
            | CertificateException | NoSuchProviderException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloud.migration.Db20to21MigrationUtil.java

private void updateSSOKey() {
    try {/*w w  w .j  av  a  2 s. c o  m*/
        String encodedKey = null;

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

        _configDao.update("security.singlesignon.key", encodedKey);
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating sso key", ex);
    }
}

From source file:com.owncloud.android.ui.activity.FingerprintActivity.java

@TargetApi(Build.VERSION_CODES.M)
protected void generateKey() {
    try {//from  w  w w. ja v a 2 s.  c o m
        keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    } catch (Exception e) {
        Log_OC.e(TAG, "Error getting KeyStore", e);
    }

    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        return;
    }

    try {
        keyStore.load(null);
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException
            | IOException e) {
        return;
    }
}

From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with device credentials within the last X seconds.
 */// w  w  w  .  j a v  a2 s . c  o m
private void createKey() {
    // Generate a key to decrypt payment credentials, tokens, etc.
    // This will most likely be a registration step for the user when they are setting up your app.
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");

        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                        // Require that the user has unlocked in the last 30 seconds
                        .setUserAuthenticationValidityDurationSeconds(AUTHENTICATION_DURATION_SECONDS)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | KeyStoreException | CertificateException | IOException e) {
        throw new RuntimeException("Failed to create a symmetric key", e);
    }
}

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.
 * //w  w w  . j  a  va  2s  . co  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.sakaiproject.tool.rutgers.LinkTool.java

/**
 * Generate a random salt, and write it to a file
 * //from   w  ww .ja va  2s .co  m
 * @param dirname
 *        writes to file saltname in this 
 *        directory. dirname assumed to end in /
 */

private void gensalt(String dirname) {
    try {
        // Generate a key for the HMAC-SHA1 keyed-hashing algorithm
        KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = keyGen.generateKey();
        writeKey(key, dirname + saltname);
    } catch (Exception e) {
        M_log.debug("Error generating salt", e);
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);/* w ww .j a  v a2s.c o m*/
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry,
                context.getBean(WebSocketPskFrameProcessor.class));

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

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

/**
 * encrypt a string using a random session key
 *
 * @param plaintext/*from   w  w w .  j a v a2 s  .  com*/
 * @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();
}