Example usage for org.bouncycastle.jce.spec IESParameterSpec IESParameterSpec

List of usage examples for org.bouncycastle.jce.spec IESParameterSpec IESParameterSpec

Introduction

In this page you can find the example usage for org.bouncycastle.jce.spec IESParameterSpec IESParameterSpec.

Prototype

public IESParameterSpec(byte[] derivation, byte[] encoding, int macKeySize) 

Source Link

Document

Set the IES engine parameters.

Usage

From source file:com.aelitis.azureus.core.security.impl.CryptoHandlerECC.java

License:Open Source License

public byte[] encrypt(byte[] other_public_key, byte[] data, String reason)

        throws CryptoManagerException {
    try {/*from  ww  w. j  ava  2s. co m*/
        IEKeySpec key_spec = new IEKeySpec(getMyPrivateKey(reason),
                CryptoECCUtils.rawdataToPubkey(other_public_key));

        byte[] d = new byte[16];
        byte[] e = new byte[16];

        RandomUtils.nextSecureBytes(d);
        RandomUtils.nextSecureBytes(e);

        IESParameterSpec param = new IESParameterSpec(d, e, 128);

        InternalECIES cipher = new InternalECIES();

        cipher.internalEngineInit(Cipher.ENCRYPT_MODE, key_spec, param, null);

        byte[] encrypted = cipher.internalEngineDoFinal(data, 0, data.length);

        byte[] result = new byte[32 + encrypted.length];

        System.arraycopy(d, 0, result, 0, 16);
        System.arraycopy(e, 0, result, 16, 16);
        System.arraycopy(encrypted, 0, result, 32, encrypted.length);

        return (result);

    } catch (CryptoManagerException e) {

        throw (e);

    } catch (Throwable e) {

        throw (new CryptoManagerException("Encrypt failed", e));
    }
}

From source file:com.aelitis.azureus.core.security.impl.CryptoHandlerECC.java

License:Open Source License

public byte[] decrypt(byte[] other_public_key, byte[] data, String reason)

        throws CryptoManagerException {
    try {/*from ww w . j  a v a  2s .c o m*/
        IEKeySpec key_spec = new IEKeySpec(getMyPrivateKey(reason),
                CryptoECCUtils.rawdataToPubkey(other_public_key));

        byte[] d = new byte[16];
        byte[] e = new byte[16];

        System.arraycopy(data, 0, d, 0, 16);
        System.arraycopy(data, 16, e, 0, 16);

        IESParameterSpec param = new IESParameterSpec(d, e, 128);

        InternalECIES cipher = new InternalECIES();

        cipher.internalEngineInit(Cipher.DECRYPT_MODE, key_spec, param, null);

        return (cipher.internalEngineDoFinal(data, 32, data.length - 32));

    } catch (CryptoManagerException e) {

        throw (e);

    } catch (Throwable e) {

        throw (new CryptoManagerException("Decrypt failed", e));
    }
}

From source file:org.certificateservices.custom.c2x.its.crypto.DefaultCryptoManager.java

License:Open Source License

/**
 * Help method to perform a ECIES encryption to a recipient of a symmetric key. 
 * /*from   w  w w .  j  a v  a 2s  .co m*/
 * @param publicKeyAlgorithm the algorithm used.
 * @param encryptionKey the public encryption key of the recipient
 * @param symmetricKey the symmetric key to encrypt
 * @return a EciesNistP256EncryptedKey to be included in a SecureMessage header.
 * 
 * @throws InvalidKeyException if supplied key was corrupt.
 * @throws InvalidAlgorithmParameterException if algorithm was badly specified.
 * @throws IllegalBlockSizeException if encrypted data was corrupt.
 * @throws BadPaddingException if encrypted data was corrupt.
 * @throws IllegalArgumentException if arguments where invalid or algorithm not supported.
 * @throws InvalidKeySpecException if supplied key specification was faulty.
 * @throws IOException if communication problem occurred with underlying systems.
 */

protected EciesNistP256EncryptedKey eCEISEncryptSymmetricKey(PublicKeyAlgorithm publicKeyAlgorithm,
        PublicKey encryptionKey, Key symmetricKey)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
        BadPaddingException, IllegalArgumentException, InvalidKeySpecException, IOException {
    if (publicKeyAlgorithm != PublicKeyAlgorithm.ecies_nistp256) {
        throw new IllegalArgumentException(
                "Unsupported encryption public key algorithm: " + publicKeyAlgorithm);
    }
    byte[] keyData = symmetricKey.getEncoded();

    IESCipher eCIESCipher = new ECIES();
    eCIESCipher.engineInit(Cipher.ENCRYPT_MODE, encryptionKey, new IESParameterSpec(null, null, 128),
            secureRandom);

    byte[] encryptedData = eCIESCipher.engineDoFinal(keyData, 0, keyData.length);
    byte[] v = new byte[ECIES_NIST_P256_V_LENGTH];
    System.arraycopy(encryptedData, 0, v, 0, ECIES_NIST_P256_V_LENGTH);

    EccPoint p = new EccPoint(publicKeyAlgorithm);
    p.deserialize(new DataInputStream(new ByteArrayInputStream(v)));

    byte[] c = new byte[publicKeyAlgorithm.getRelatedSymmetricAlgorithm().getKeyLength()];
    byte[] t = new byte[EciesNistP256EncryptedKey.OUTPUT_TAG_LENGTH];
    System.arraycopy(encryptedData, ECIES_NIST_P256_V_LENGTH, c, 0,
            publicKeyAlgorithm.getRelatedSymmetricAlgorithm().getKeyLength());
    System.arraycopy(encryptedData,
            ECIES_NIST_P256_V_LENGTH + publicKeyAlgorithm.getRelatedSymmetricAlgorithm().getKeyLength(), t, 0,
            EciesNistP256EncryptedKey.OUTPUT_TAG_LENGTH);
    return new EciesNistP256EncryptedKey(publicKeyAlgorithm, p, c, t);
}

From source file:org.certificateservices.custom.c2x.its.crypto.DefaultCryptoManager.java

License:Open Source License

/**
 * Help method to perform a ECIES decryption of a symmetric key. 
 * /*from   www .  j  a va  2 s .  co m*/
 * @param eciesNistP256EncryptedKey the EciesNistP256EncryptedKey header value from the SecuredMessage
 * @param decryptionKey the receiptients private key
 * @return a decrypted symmetric key.
 * 
 * @throws InvalidKeyException if supplied key was corrupt.
 * @throws InvalidAlgorithmParameterException if algorithm was badly specified.
 * @throws IllegalBlockSizeException if encrypted data was corrupt.
 * @throws BadPaddingException if encrypted data was corrupt.
 * @throws IllegalArgumentException if arguments where invalid or algorithm not supported.
 * @throws InvalidKeySpecException if supplied key specification was faulty.
 * @throws IOException if communication problem occurred with underlying systems.
 */

protected Key eCEISDecryptSymmetricKey(EciesNistP256EncryptedKey eciesNistP256EncryptedKey,
        PrivateKey decryptionKey)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
        BadPaddingException, IllegalArgumentException, InvalidKeySpecException, IOException {
    if (eciesNistP256EncryptedKey.getPublicKeyAlgorithm() != PublicKeyAlgorithm.ecies_nistp256) {
        throw new IllegalArgumentException("Unsupported encryption public key algorithm: "
                + eciesNistP256EncryptedKey.getPublicKeyAlgorithm());
    }

    IESCipher eCIESCipher = new ECIES();
    eCIESCipher.engineInit(Cipher.DECRYPT_MODE, decryptionKey, new IESParameterSpec(null, null, 128),
            secureRandom);

    byte[] encryptedData = new byte[ECIES_NIST_P256_V_LENGTH
            + eciesNistP256EncryptedKey.getPublicKeyAlgorithm().getRelatedSymmetricAlgorithm().getKeyLength()
            + EciesNistP256EncryptedKey.OUTPUT_TAG_LENGTH];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dis = new DataOutputStream(baos);

    eciesNistP256EncryptedKey.getV().serialize(dis);
    baos.close();
    System.arraycopy(baos.toByteArray(), 0, encryptedData, 0, ECIES_NIST_P256_V_LENGTH);
    System.arraycopy(eciesNistP256EncryptedKey.getC(), 0, encryptedData, ECIES_NIST_P256_V_LENGTH,
            eciesNistP256EncryptedKey.getPublicKeyAlgorithm().getRelatedSymmetricAlgorithm().getKeyLength());
    System.arraycopy(eciesNistP256EncryptedKey.getT(), 0, encryptedData,
            ECIES_NIST_P256_V_LENGTH + eciesNistP256EncryptedKey.getPublicKeyAlgorithm()
                    .getRelatedSymmetricAlgorithm().getKeyLength(),
            EciesNistP256EncryptedKey.OUTPUT_TAG_LENGTH);

    byte[] decryptedData = eCIESCipher.engineDoFinal(encryptedData, 0, encryptedData.length);

    return new SecretKeySpec(decryptedData, "AES");
}

From source file:servTTP.servTTP.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w.j a  va  2 s  . c om*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet servTTP</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet servTTP at " + request.getContextPath() + "</h1><br><br>");

        KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC");
        out.println("<br> passou0");
        ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
        g.initialize(parameterSpec, new SecureRandom());

        KeyPair aKeyPair = g.generateKeyPair();
        PublicKey aPub = aKeyPair.getPublic();
        PrivateKey aPriv = aKeyPair.getPrivate();

        KeyPair bKeyPair = g.generateKeyPair();
        PublicKey bPub = bKeyPair.getPublic();
        PrivateKey bPriv = bKeyPair.getPrivate();
        out.println("<br> passou1");
        javax.crypto.Cipher c1 = javax.crypto.Cipher.getInstance("ECIES", "BC");
        out.println("<br> passou2");
        javax.crypto.Cipher c2 = javax.crypto.Cipher.getInstance("ECIES", "BC");

        IEKeySpec c1Key = new IEKeySpec(aPriv, bPub);
        IEKeySpec c2Key = new IEKeySpec(bPriv, aPub);

        byte[] derivation = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // #1
        byte[] encoding = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; // #2
        int macKeySizeInBits = 128;
        IESParameterSpec param = new IESParameterSpec(derivation, encoding, macKeySizeInBits);

        c1.init(javax.crypto.Cipher.ENCRYPT_MODE, c1Key, param); // #3
        c2.init(javax.crypto.Cipher.DECRYPT_MODE, c2Key, param); // #4

        byte[] message = "hello world -- a nice day today".getBytes();
        byte[] out1 = c1.doFinal(message, 0, message.length);
        out.println("<br><br>length: " + out1.length);
        out.println(new String(out1));
        out.println("<br><br>");
        byte[] out2 = c2.doFinal(out1, 0, out1.length);
        out.println(new String(out2));

        /*
         X9ECParameters ecParams = NISTNamedCurves.getByName("B-163");
         BigInteger privKey = new BigInteger("38e1", 16);
         ECPoint pubKey = ecParams.getG().multiply(privKey);
                 
         out.println("Available curves:<br>");
                 
         int counter = 0;
         for ( Enumeration e = NISTNamedCurves.getNames(); e.hasMoreElements(); ){
         if (counter == 3) {
        counter = -1;
        out.println( e.nextElement().toString() );
        out.println("<br>");
         }else{
        out.print( e.nextElement().toString() + "    ");
        out.println("<br>");
         }
          counter++;
        }
        ECPoint pMsg = ecParams.getG().multiply(
        new BigInteger(Integer.toHexString(2), 16));
                
        out.println("<br>");
        out.println("<br>");
        out.println("--------------------------------------------------------------------------------------------------------------------------------------------------");
                
        out.println("<br>");
        out.println("Selected curve:");
                
        out.println("Curve:     " + ecParams.getCurve().getFieldSize());
        out.println("<br>");
                
        out.println("--------------------------------------------------------------------------------------------------------------------------------------------------");
        out.println("<br>");
        out.println("Point:     " + "X: " + pMsg.getX().toBigInteger().toString(16) + "<br>" + "           Y: " + pMsg.getY().toBigInteger().toString(16));
        out.println("<br>");
                
        out.println("--------------------------------------------------------------------------------------------------------------------------------------------------");
                
        ECPoint one;
        ECPoint two;
                
        BigInteger random = new BigInteger(16, new SecureRandom());*/

        /* g^r */
        // one = ecParams.getG().multiply(random);

        /* pk^r+m */
        // two = pMsg.add(pubKey.multiply(random));

        //encryptedData edM = new encryptedData(one, two);
        /*
        out.println("<br><br>Encrypted:<br><br>");
                
        out.println("One:      " + "X: " + one.getX().toBigInteger().toString(16) + "<br>" + "           Y: " + one.getY().toBigInteger().toString(16) + "<br>");
        out.println("Two:      " + "X: " + two.getX().toBigInteger().toString(16) + "<br>" + "           Y: " + two.getY().toBigInteger().toString(16) + "<br>");
                
        out.println("--------------------------------------------------------------------------------------------------------------------------------------------------");
                
        ECPoint decrypted = two.eData.subtract(two.gInR.multiply(privKey));
                
        out.println("Decrypted: " + "X: " + decrypted.getX().toBigInteger().toString(16) + "<br>" + "           Y: " + decrypted.getY().toBigInteger().toString(16) + "<br>");
                
        */

        /*
        KeyPairGenerator kpg;
        kpg = KeyPairGenerator.getInstance("EC","SunEC");
                
                
        Cipher cipher = Cipher.getInstance("DES");
        out.println("provider=" + cipher.getProvider());
                
                
        ECGenParameterSpec ecsp;
        ecsp = new ECGenParameterSpec("secp192r1");
        kpg.initialize(ecsp);
                
                
                
        KeyPair kp = kpg.genKeyPair();
        PrivateKey privKey = kp.getPrivate();
        PublicKey pubKey = kp.getPublic();
        out.println("privKey = "+ privKey);
        out.println("<br><br>publicKey = " + pubKey.toString() + "<br><br>");
                
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);*/

        out.println("passou");

        /*
        Global global = new Global();
        out.println("passou1");
        Context context  = createAndInitializeContext(global);
        out.println("passou2");
        Scriptable scope = context.initStandardObjects(global);
        out.println("passou3");
        URL url = new URL("http://localhost:8080/sjcl/sjcl.js");
        out.println("passou4");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        out.println("passou5");
        compileAndExec(in, "classpath:" + url.toString(), context, scope);
        out.println("passou6");
        in.close();
        out.println("passou7");
        exec("var p = {mode : 'ccm',iv : '9VJFbwZs/HhyN81aKrKLZA',salt : 'FVj3L6Omt14'}; var result = sjcl.encrypt('password', 'data', p, {})", "start", context,scope);
        out.println("passou8");
        Object result = scope.get("result", scope);
        out.println("resultado = " + result);
        if (result != Scriptable.NOT_FOUND) {
        String json =  Context.toString(result);
        out.println(json);
        } 
        exec("var rp = {}; var result = sjcl.decrypt('Siva', {iv : '9VJFbwZs/HhyN81aKrKLZA',salt : 'FVj3L6Omt14' ,ct : 'zi1SfGfSZMY5Rcdx+DOzfiM'}, {}, rp)", "start", context,scope);
        //exec("var rp = {}; var result = sjcl.decrypt('password', "+result+" , {}, rp);", "start", context,scope);
        result = scope.get("result", scope);
        if (result != Scriptable.NOT_FOUND) {
        String json =  Context.toString(result);
        out.println(json);
        }  */
    } catch (Exception e) {
        out.println("catch");
    }
    out.println("</body>");
    out.println("</html>");

}