Example usage for javax.crypto Cipher unwrap

List of usage examples for javax.crypto Cipher unwrap

Introduction

In this page you can find the example usage for javax.crypto Cipher unwrap.

Prototype

public final Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
        throws InvalidKeyException, NoSuchAlgorithmException 

Source Link

Document

Unwrap a previously wrapped key.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    Key sharedKey = kg.generateKey();

    String password = "password";
    byte[] salt = "salt1234".getBytes();
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey passwordKey = kf.generateSecret(keySpec);
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
    c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
    byte[] wrappedKey = c.wrap(sharedKey);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, sharedKey);
    byte[] input = "input".getBytes();
    byte[] encrypted = c.doFinal(input);

    c = Cipher.getInstance("PBEWithMD5AndDES");

    c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
    Key unwrappedKey = c.unwrap(wrappedKey, "DESede", Cipher.SECRET_KEY);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.DECRYPT_MODE, unwrappedKey);
    System.out.println(new String(c.doFinal(encrypted)));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    SecureRandom random = new SecureRandom();

    KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "BC");
    fact.initialize(1024, random);//from   ww w  .  j a  va  2s .  c  o m

    KeyPair keyPair = fact.generateKeyPair();
    Key wrapKey = createKeyForAES(256, random);
    cipher.init(Cipher.WRAP_MODE, wrapKey);

    byte[] wrappedKey = cipher.wrap(keyPair.getPrivate());
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "RSA", Cipher.PRIVATE_KEY);
    System.out.println(keyPair.getPrivate().equals(key));

}

From source file:RSATest.java

public static void main(String[] args) {
    try {/*from   ww w  .  j  a  va  2 s .  c  o m*/
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.kactech.otj.Utils.java

public static String open(byte[] encryptedEnvelope, PrivateKey privateKey)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String str;/*from  w  w  w.j av  a 2  s.  c o m*/
    byte[] by;
    ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope);
    buff.order(ByteOrder.BIG_ENDIAN);
    int envType = buff.getShort();// expected 1(asymmetric)
    if (envType != 1)
        throw new UnsupportedOperationException("unexpected envelope type " + envType);
    int arraySize = buff.getInt();// can result in negative integer but not expecting it here
    if (arraySize != 1)//TODO
        throw new UnsupportedOperationException("current code doesn't support multi-nym response");
    byte[] encKeyBytes = null;
    byte[] vectorBytes = null;
    for (int i = 0; i < arraySize; i++) {
        int nymIDLen = buff.getInt();
        by = new byte[nymIDLen];
        buff.get(by);
        String nymID;
        try {
            nymID = new String(by, 0, by.length - 1, Utils.US_ASCII);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } // take nymID W/O trailing \0
          //TODO nymID matching!
        int keyLength = buff.getInt();
        encKeyBytes = new byte[keyLength];
        buff.get(encKeyBytes);
        int vectorLength = buff.getInt();
        vectorBytes = new byte[vectorLength];
        buff.get(vectorBytes);

    }
    byte[] encryptedMsg = new byte[buff.remaining()];
    buff.get(encryptedMsg);

    Cipher cipher;
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY);
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes));
    by = cipher.doFinal(encryptedMsg);
    try {
        str = new String(by, 0, by.length - 1, Utils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } // w/o trailing \0
    return str;
}

From source file:eu.peppol.security.OxalisCipherConverter.java

/**
 * Creates an instance of OxalisCipher:/*w  w w  .j  a v a2  s.co m*/
 * <ol>
 *     <li>Decodes the supplied hex string representation of a wrapped key into an array of bytes representation</li>
 *     <li>Creates a cipher, which is initialized with a private key</li>
 *     <li>Unwraps (decrypts) the secret key represented by an array of bytes into a SecretKey</li>
 *     <li>Creates an OxalisCipher using the unwrapped SecretKey</li>
 * </ol>
 * @param wrappedSymmetricKeyAsHexString
 * @param privateKey
 * @return
 */
public OxalisCipher createCipherFromWrappedHexKey(String wrappedSymmetricKeyAsHexString,
        PrivateKey privateKey) {

    // 1) Decodes the hex string representation of a wrapped key
    byte[] encodedBytes = encodedBytesFromHexString(wrappedSymmetricKeyAsHexString);

    try {
        // 2) Creates the Cipher using supplied private key
        Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM);
        cipher.init(Cipher.UNWRAP_MODE, privateKey);

        // 3) Unwraps (decrypts) the secret key using our private key
        SecretKey secretKey = (SecretKey) cipher.unwrap(encodedBytes, OxalisCipher.SYMMETRIC_KEY_ALGORITHM,
                Cipher.SECRET_KEY);

        // 4) creates the Oxalis cipher
        OxalisCipher oxalisCipher = new OxalisCipher(secretKey);
        return oxalisCipher;

    } catch (NoSuchAlgorithmException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    } catch (NoSuchPaddingException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    } catch (InvalidKeyException e) {
        throw new UnwrapSymmetricKeyException(wrappedSymmetricKeyAsHexString, e);
    }
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException {
    secureRandom = new SecureRandom();
    this.vaultPath = vaultPath;
    this.encryptionMode = encryptionMode;

    File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    if (!headerFile.exists()) {
        try {//w ww  .ja  va  2  s. c o  m
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(AES_KEY_SIZE_BIT);
            Key encryptionKey = keyGenerator.generateKey();

            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt);

            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase);
        } catch (Exception e) {
            Util.log("Cannot create vault header!");
            e.printStackTrace();
        }
    }

    try {
        FileInputStream headerInputStream = new FileInputStream(headerFile);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        e.printStackTrace();
    }

    try {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
        SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(),
                vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
        Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
        c.init(Cipher.UNWRAP_MODE, keyFromPassphrase,
                new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));

        vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(),
                KEY_ALGORITHM, Cipher.SECRET_KEY);
    } catch (InvalidKeyException e) {
        throw new InvalidKeyException("Passphrase is wrong!");
    } catch (Exception e) {
        Util.log("Cannot decrypt AES key");
        e.printStackTrace();
    }
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

@Override
public boolean changePassphrase(String oldPassphrase, String newPassphrase) {
    SecretKeyFactory secretKeyFactory;

    File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW");
    if (!headerFileNew.exists()) {
        try {/*from w  ww  .  j a  v  a2 s.  c  o m*/
            // Decrypt AES encryption key
            secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(),
                            vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
            Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
            c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase,
                    new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));
            Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM,
                    Cipher.SECRET_KEY);

            // Create new vault nonce and salt
            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt);

            // Create new key for AES key encryption
            SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey,
                    newKeyFromPassphrase);

        } catch (Exception e) {
            Util.log("Error while reading or creating new vault header!");
            return false;
        }
    } else {
        Util.log("New header file already exists. Cannot change passphrase!");
        return false;
    }

    // Try to parse new header file
    try {
        FileInputStream headerInputStream = new FileInputStream(headerFileNew);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        headerFileNew.delete();
        return false;
    }

    // Delete old header file and replace with new header file
    if (!headerFileOld.delete()) {
        headerFileNew.delete();
        Util.log("Cannot delete old vault header!");
        return false;
    }
    try {
        org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld);
    } catch (IOException e) {
        Util.log("Cannot replace old vault header!");
        return false;
    }

    headerFileNew.delete();
    return true;
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

/**
 * Reads the encrypted masterkey from the given input stream and decrypts it with the given password.
 * /*from  w ww  . ja  v a2s.  c  o m*/
 * @throws DecryptFailedException If the decryption failed for various reasons (including wrong password).
 * @throws WrongPasswordException If the provided password was wrong. Note: Sometimes the algorithm itself fails due to a wrong
 *             password. In this case a DecryptFailedException will be thrown.
 * @throws UnsupportedKeyLengthException If the masterkey has been encrypted with a higher key length than supported by the system. In
 *             this case Java JCE needs to be installed.
 */
@Override
public void decryptMasterKey(InputStream in, CharSequence password)
        throws DecryptFailedException, WrongPasswordException, UnsupportedKeyLengthException, IOException {
    try {
        // load encrypted masterkey:
        final KeyFile keyfile = objectMapper.readValue(in, KeyFile.class);

        // check, whether the key length is supported:
        final int maxKeyLen = Cipher.getMaxAllowedKeyLength(AES_KEY_ALGORITHM);
        if (keyfile.getKeyLength() > maxKeyLen) {
            throw new UnsupportedKeyLengthException(keyfile.getKeyLength(), maxKeyLen);
        }

        // derive key:
        final SecretKey kek = scrypt(password, keyfile.getScryptSalt(), keyfile.getScryptCostParam(),
                keyfile.getScryptBlockSize(), AES_KEY_LENGTH_IN_BITS);

        // decrypt and check password by catching AEAD exception
        final Cipher decCipher = aesKeyWrapCipher(kek, Cipher.UNWRAP_MODE);
        SecretKey primary = (SecretKey) decCipher.unwrap(keyfile.getPrimaryMasterKey(), AES_KEY_ALGORITHM,
                Cipher.SECRET_KEY);
        SecretKey secondary = (SecretKey) decCipher.unwrap(keyfile.getHMacMasterKey(), HMAC_KEY_ALGORITHM,
                Cipher.SECRET_KEY);

        // everything ok, assign decrypted keys:
        this.primaryMasterKey = primary;
        this.hMacMasterKey = secondary;
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalStateException("Algorithm should exist.", ex);
    } catch (InvalidKeyException e) {
        throw new WrongPasswordException();
    }
}

From source file:net.sourceforge.msscodefactory.cfensyntax.v2_2.CFEnSyntaxSMWar.CFEnSyntaxSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w w  w . j  a v  a  2s .c  om
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFEnSyntaxSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFEnSyntaxSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFEnSyntaxSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
            return;
        }
    }

    CFEnSyntaxAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
        return;
    }

    ICFEnSyntaxSecUserObj secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

    ICFEnSyntaxClusterObj secCluster = schemaObj.getClusterTableObj()
            .readClusterByIdIdx(auth.getSecClusterId());
    if (secCluster == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "secCluster");
    }
    String clusterDescription = secCluster.getRequiredDescription();

    ICFEnSyntaxSchema dbSchema = null;
    try {
        dbSchema = CFEnSyntaxSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();

        String deviceName = request.getParameter("DeviceName");
        if ((deviceName == null) || (deviceName.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFEnSyntaxSecDeviceObj secDev = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(secUser.getRequiredSecUserId(), deviceName);
        if (secDev != null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name \"" + deviceName + "\" already in use.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String publicKey = request.getParameter("PublicKey");
        if ((publicKey == null) || (publicKey.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        byte wrapped[] = Base64.decodeBase64(publicKey);

        Cipher cipher = Cipher.getInstance("AES");
        if (cipher == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "cipher");
        }

        Key key = cipher.unwrap(wrapped, "AES", Cipher.PUBLIC_KEY);
        if ((key == null) || (!(key instanceof PublicKey))) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be a valid Client AES Key.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFEnSyntaxClusterObj systemCluster = schemaObj.getClusterTableObj()
                .readClusterByUDomainNameIdx("system");
        ICFEnSyntaxTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFEnSyntaxSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFEnSyntaxSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFEnSyntaxSecSessionEditObj editSystemSession = (ICFEnSyntaxSecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFEnSyntaxAuthorization secAuth = new CFEnSyntaxAuthorization();
        secAuth.setSecCluster(systemCluster);
        secAuth.setSecTenant(systemTenant);
        secAuth.setSecSession(systemSession);
        schemaObj.setAuthorization(secAuth);

        secDev = schemaObj.getSecDeviceTableObj().newInstance();
        ICFEnSyntaxSecDeviceEditObj editDev = secDev.beginEdit();
        editDev.setRequiredContainerSecUser(secUser);
        editDev.setRequiredDevName(deviceName);
        editDev.setOptionalPubKey(publicKey);
        secDev = editDev.create();
        editDev.endEdit();

        if (null == secUser.getOptionalLookupDefDev()) {
            ICFEnSyntaxSecUserEditObj editSecUser = secUser.beginEdit();
            editSecUser.setOptionalLookupDefDev(secDev);
            editSecUser.update();
            editSecUser.endEdit();
        }

        editSystemSession = (ICFEnSyntaxSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setOptionalFinish(Calendar.getInstance());
        editSystemSession.update();
        editSystemSession.endEdit();

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFEnSyntaxSMWarSecurityMainHtml");

    } catch (InvalidKeyException e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<p style=\"text-align:center\">Public Key must be a valid Client AES Key.");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        schemaObj.setAuthorization(auth);
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFEnSyntaxSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java

@Override
public SecretKey decryptSecretKey(String algorithmUsedToEncryptTheKey, String algorithmKeyIsUsedFor, Key key,
        String keyToDecrypt) throws NetInfCheckedSecurityException {
    try {//from   ww  w  .ja  va2 s  . c o m
        LOG.debug("Decrypting SecretKey.");
        LOG.trace("Used algorithm for encryption: " + algorithmUsedToEncryptTheKey);
        LOG.trace("Used algorithm of encrypted key: " + algorithmKeyIsUsedFor);
        LOG.trace("Used key: " + key);
        LOG.trace("Used key to be decrypted: " + keyToDecrypt);
        Cipher cipher = Cipher.getInstance(algorithmUsedToEncryptTheKey);
        cipher.init(Cipher.UNWRAP_MODE, key);
        return (SecretKey) cipher.unwrap(Base64.decodeBase64(keyToDecrypt), algorithmKeyIsUsedFor,
                Cipher.SECRET_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-algorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new NetInfCheckedSecurityException("Unknown cipher-padding: " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new NetInfCheckedSecurityException("Invalid Key. " + e.getMessage());
    }
}