Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:BlockChainUnitTest.java

@Test //this anotation is very important
public void TestAddTransactionBlock() {

    try {// ww w .j  a va 2  s.c o m

        Block genericsBlock = new Block(null, m_ownerpair.getPublic());
        genericsBlock.finalize();

        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(2048, random);

        // Generating two key pairs, one for Scrooge and one for Alice
        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey private_key_generic = pair.getPrivate();
        PublicKey public_key_generic = pair.getPublic();

        pair = keyGen.generateKeyPair();
        PrivateKey private_key_alice = pair.getPrivate();
        PublicKey public_key_alice = pair.getPublic();

        // START - ROOT TRANSACTION
        // Generating a root transaction tx out of thin air, so that Scrooge owns a coin of value 10
        // By thin air I mean that this tx will not be validated, I just need it to get a proper Transaction.Output
        // which I then can put in the UTXOPool, which will be passed to the TXHandler
        Transaction tx = new Transaction();
        tx.addOutput(25, public_key_generic);

        // that value has no meaning, but tx.getRawDataToSign(0) will access in.prevTxHash;
        byte[] initialHash = BigInteger.valueOf(1695609641).toByteArray();
        tx.addInput(genericsBlock.getCoinbase().getHash(), 0);

        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(m_ownerpair.getPrivate());
        signature.update(tx.getRawDataToSign(0));
        byte[] sig = signature.sign();

        tx.addSignature(sig, 0);
        tx.finalize();

        BlockChain oBlockChain = new BlockChain(genericsBlock);
        Boolean bret = oBlockChain.addBlock(genericsBlock);
        assertFalse(bret);

        //Add first block
        Block blockFirst = new Block(genericsBlock.getHash(), m_ownerpair.getPublic());
        blockFirst.addTransaction(tx);
        blockFirst.finalize();
        System.out.println("Add a transcation with valid Tx");
        bret = oBlockChain.addBlock(blockFirst);
        assertTrue(bret);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SignatureException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:BlockChainUnitTest.java

@Test //this anotation is very important
public void TestAddDoubleSpendTransactionBlock() {

    try {//from ww w .j av a  2  s  .c om
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(2048, random);

        // Generating two key pairs, one for Scrooge and one for Alice
        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey private_key_generic = pair.getPrivate();
        PublicKey public_key_generic = pair.getPublic();

        pair = keyGen.generateKeyPair();
        PrivateKey private_key_alice = pair.getPrivate();
        PublicKey public_key_alice = pair.getPublic();

        pair = keyGen.generateKeyPair();
        PrivateKey private_key_bob = pair.getPrivate();
        PublicKey public_key_bob = pair.getPublic();

        // START - ROOT TRANSACTION
        // Generating a root transaction tx out of thin air, so that Scrooge owns a coin of value 10
        // By thin air I mean that this tx will not be validated, I just need it to get a proper Transaction.Output
        // which I then can put in the UTXOPool, which will be passed to the TXHandler
        Transaction tx = new Transaction();
        tx.addOutput(10, public_key_generic);

        // that value has no meaning, but tx.getRawDataToSign(0) will access in.prevTxHash;
        byte[] initialHash = BigInteger.valueOf(1695609641).toByteArray();
        tx.addInput(initialHash, 0);

        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(private_key_generic);
        signature.update(tx.getRawDataToSign(0));
        byte[] sig = signature.sign();

        tx.addSignature(sig, 0);
        tx.finalize();

        // START - PROPER TRANSACTION
        Transaction tx2 = new Transaction();

        // the Transaction.Output of tx at position 0 has a value of 10
        tx2.addInput(tx.getHash(), 0);

        // I split the coin of value 10 into 3 coins and send all of them for simplicity to the same address (Alice)
        tx2.addOutput(5, public_key_alice);
        tx2.addOutput(3, public_key_alice);
        tx2.addOutput(2, public_key_alice);

        // There is only one (at position 0) Transaction.Input in tx2
        // and it contains the coin from Scrooge, therefore I have to sign with the private key from Scrooge
        signature.initSign(private_key_generic);
        signature.update(tx2.getRawDataToSign(0));
        sig = signature.sign();
        tx2.addSignature(sig, 0);
        tx2.finalize();

        // START - PROPER TRANSACTION
        Transaction tx3 = new Transaction();

        // the Transaction.Output of tx at position 0 has a value of 10
        tx3.addInput(tx.getHash(), 0);

        // I split the coin of value 10 into 3 coins and send all of them for simplicity to the same address (Alice)
        tx3.addOutput(5, public_key_bob);
        tx3.addOutput(3, public_key_bob);
        tx3.addOutput(2, public_key_bob);

        // There is only one (at position 0) Transaction.Input in tx2
        // and it contains the coin from Scrooge, therefore I have to sign with the private key from Scrooge
        signature.initSign(private_key_generic);
        signature.update(tx3.getRawDataToSign(0));
        sig = signature.sign();
        tx3.addSignature(sig, 0);
        tx3.finalize();

        Block genericsBlock = new Block(null, m_ownerpair.getPublic());
        genericsBlock.finalize();

        BlockChain oBlockChain = new BlockChain(genericsBlock);

        //Add first block
        Block blockFirst = new Block(genericsBlock.getHash(), m_ownerpair.getPublic());
        blockFirst.addTransaction(tx);
        blockFirst.addTransaction(tx2);
        blockFirst.addTransaction(tx3);
        blockFirst.finalize();
        Boolean bret = oBlockChain.addBlock(blockFirst);
        assertFalse(bret);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SignatureException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:BlockChainUnitTest.java

@Test //this anotation is very important
public void TestCreateBlockAfterTransaction() {

    try {//from   w ww. jav a  2 s  .  co m

        Block genericsBlock = new Block(null, m_ownerpair.getPublic());
        genericsBlock.finalize();

        BlockChain oBlockChain = new BlockChain(genericsBlock);
        Boolean bret = oBlockChain.addBlock(genericsBlock);
        assertFalse(bret);

        BlockHandler blockHdlr = new BlockHandler(oBlockChain);
        bret = blockHdlr.processBlock(genericsBlock);
        assertFalse(bret);

        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(2048, random);

        // Generating two key pairs, one for Scrooge and one for Alice
        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey private_key_generic = pair.getPrivate();
        PublicKey public_key_generic = pair.getPublic();

        pair = keyGen.generateKeyPair();
        PrivateKey private_key_alice = pair.getPrivate();
        PublicKey public_key_alice = pair.getPublic();

        // START - ROOT TRANSACTION
        // Generating a root transaction tx out of thin air, so that Scrooge owns a coin of value 10
        // By thin air I mean that this tx will not be validated, I just need it to get a proper Transaction.Output
        // which I then can put in the UTXOPool, which will be passed to the TXHandler
        Transaction tx = new Transaction();
        tx.addOutput(25, public_key_generic);

        // that value has no meaning, but tx.getRawDataToSign(0) will access in.prevTxHash;
        byte[] initialHash = BigInteger.valueOf(1695609641).toByteArray();
        tx.addInput(genericsBlock.getCoinbase().getHash(), 0);

        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(m_ownerpair.getPrivate());
        signature.update(tx.getRawDataToSign(0));
        byte[] sig = signature.sign();

        tx.addSignature(sig, 0);
        tx.finalize();
        System.out.println("process valid Tx");
        blockHdlr.processTx(tx);

        //Add first block
        Block blockFirst = blockHdlr.createBlock(public_key_alice);
        assertNotNull(blockFirst);
        //the new block show countain the valid Tx
        assertNotSame(blockFirst.getTransactions().size(), 0);
        assertSame(blockFirst.getTransaction(0).getHash(), tx.getHash());

        //Add second block
        Block blockSecond = blockHdlr.createBlock(public_key_alice);
        assertNotNull(blockSecond);
        //the new block show countain the valid Tx
        assertSame(blockSecond.getTransactions().size(), 0);
        ByteArrayWrapper first = new ByteArrayWrapper(blockFirst.getHash());
        assertTrue(first.equals(new ByteArrayWrapper(blockSecond.getPrevBlockHash())));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SignatureException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:BlockChainUnitTest.java

@Test //this anotation is very important
public void TestAddSpentTransactionBlock() {

    try {//from  w  w w.  j av a  2s.  com

        Block genericsBlock = new Block(null, m_ownerpair.getPublic());
        genericsBlock.finalize();

        BlockChain oBlockChain = new BlockChain(genericsBlock);
        BlockHandler blkHandler = new BlockHandler(oBlockChain);

        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(2048, random);

        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey private_key_alice = pair.getPrivate();
        PublicKey public_key_alice = pair.getPublic();

        pair = keyGen.generateKeyPair();
        PrivateKey private_key_bob = pair.getPrivate();
        PublicKey public_key_bob = pair.getPublic();

        Signature signature = Signature.getInstance("SHA256withRSA");

        // START - PROPER TRANSACTION
        Transaction tx2 = new Transaction();

        // the Transaction.Output of tx at position 0 has a value of 10
        tx2.addInput(genericsBlock.getCoinbase().getHash(), 0);

        // I split the coin of value 10 into 3 coins and send all of them for simplicity to the same address (Alice)
        tx2.addOutput(5, public_key_alice);
        tx2.addOutput(10, public_key_alice);
        tx2.addOutput(10, public_key_alice);

        // There is only one (at position 0) Transaction.Input in tx2
        // and it contains the coin from Scrooge, therefore I have to sign with the private key from Scrooge
        signature.initSign(this.m_ownerpair.getPrivate());
        signature.update(tx2.getRawDataToSign(0));
        byte[] sig = signature.sign();
        tx2.addSignature(sig, 0);
        tx2.finalize();

        // START - PROPER TRANSACTION
        Transaction tx3 = new Transaction();

        // the Transaction.Output of tx at position 0 has a value of 10
        tx3.addInput(tx2.getHash(), 0);

        // I split the coin of value 10 into 3 coins and send all of them for simplicity to the same address (Alice)
        tx3.addOutput(1, public_key_bob);
        tx3.addOutput(1, public_key_bob);
        tx3.addOutput(3, public_key_bob);

        // There is only one (at position 0) Transaction.Input in tx2
        // and it contains the coin from Scrooge, therefore I have to sign with the private key from Scrooge
        signature.initSign(private_key_alice);
        signature.update(tx3.getRawDataToSign(0));
        sig = signature.sign();
        tx3.addSignature(sig, 0);
        tx3.finalize();

        blkHandler.processTx(tx2);
        blkHandler.processTx(tx3);

        System.out.println("UTXO size in stage 1 is " + oBlockChain.getMaxHeightUTXOPool().getAllUTXO().size());

        //Add first block
        Block blockFirst = blkHandler.createBlock(public_key_bob);
        assertFalse(blockFirst == null);
        System.out.println("UTXO size in stage 2 is " + oBlockChain.getMaxHeightUTXOPool().getAllUTXO().size());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SignatureException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:BlockChainUnitTest.java

@Test //this anotation is very important
public void TestProcessMultipleBlocksOnGenericsBlock()
        throws NoSuchProviderException, InvalidKeyException, SignatureException {
    try {//  w  w w .j  a  v  a  2 s  .  co m
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(2048, random);

        Block genericsBlock = new Block(null, m_ownerpair.getPublic());
        genericsBlock.finalize();
        BlockChain oBlockChain = new BlockChain(genericsBlock);
        BlockHandler blkHandler = new BlockHandler(oBlockChain);
        System.out.println("[MultipleBlocks] create initial block chain");

        KeyPair pair = keyGen.generateKeyPair();
        Block second = blkHandler.createBlock(pair.getPublic());
        System.out.println("[MultipleBlocks] create second block node");

        KeyPair pair1 = keyGen.generateKeyPair();
        Block forkBlock = new Block(genericsBlock.getHash(), pair1.getPublic());
        forkBlock.finalize();
        Boolean bret = blkHandler.processBlock(forkBlock);
        assertTrue(bret);
        System.out.println("[MultipleBlocks] process another block node 1");

        KeyPair pair2 = keyGen.generateKeyPair();
        Block forkBlock2 = new Block(genericsBlock.getHash(), pair2.getPublic());
        forkBlock2.finalize();
        bret = blkHandler.processBlock(forkBlock2);
        assertTrue(bret);
        System.out.println("[MultipleBlocks] process another block node 2");

        // START - PROPER TRANSACTION
        Transaction tx2 = new Transaction();
        tx2.addInput(genericsBlock.getCoinbase().getHash(), 0);

        Signature signature = Signature.getInstance("SHA256withRSA");

        KeyPair Alice = keyGen.generateKeyPair();
        tx2.addOutput(5, Alice.getPublic());
        tx2.addOutput(10, Alice.getPublic());
        tx2.addOutput(10, Alice.getPublic());
        signature.initSign(m_ownerpair.getPrivate());
        signature.update(tx2.getRawDataToSign(0));
        byte[] sigtx2 = signature.sign();
        tx2.addSignature(sigtx2, 0);
        tx2.finalize();
        blkHandler.processTx(tx2);

        KeyPair pair3 = keyGen.generateKeyPair();
        Block second2 = blkHandler.createBlock(pair3.getPublic());
        assertSame(second2.getTransactions().size(), 1);
        System.out.println("[MultipleBlocks] createBlock over maxheight, poolsize is "
                + oBlockChain.getMaxHeightUTXOPool().getAllUTXO().size());

        // START - PROPER TRANSACTION
        Transaction tx3 = new Transaction();

        tx3.addInput(tx2.getHash(), 0);
        tx3.addInput(tx2.getHash(), 1);
        tx3.addInput(tx2.getHash(), 2);

        KeyPair pair4 = keyGen.generateKeyPair();
        tx3.addOutput(6, pair4.getPublic());
        tx3.addOutput(8, pair4.getPublic());
        tx3.addOutput(11, pair4.getPublic());
        signature.initSign(Alice.getPrivate());
        signature.update(tx3.getRawDataToSign(0));
        byte[] sig = signature.sign();
        tx3.addSignature(sig, 0);
        signature.update(tx3.getRawDataToSign(1));
        sig = signature.sign();
        tx3.addSignature(sig, 1);
        signature.update(tx3.getRawDataToSign(2));
        sig = signature.sign();
        tx3.addSignature(sig, 2);
        tx3.finalize();
        blkHandler.processTx(tx3);

        KeyPair pair5 = keyGen.generateKeyPair();
        Block second3 = blkHandler.createBlock(pair5.getPublic());
        assertSame(oBlockChain.getMaxHeightUTXOPool().getAllUTXO().size(), 6);
        System.out.println("UTXO pool size " + oBlockChain.getMaxHeightUTXOPool().getAllUTXO().size());

        //check if the previous block is equal
        ByteArrayWrapper tmp2 = new ByteArrayWrapper(second2.getHash());
        assertTrue(tmp2.equals(new ByteArrayWrapper(second3.getPrevBlockHash())));

        //check if the highest is current block
        ByteArrayWrapper highest = new ByteArrayWrapper(oBlockChain.getMaxHeightBlock().getHash());
        assertTrue(highest.equals(new ByteArrayWrapper(second3.getHash())));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(BlockChainUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:TestSendMail.java

License:Apache License

public void testSend() {
    try {//ww  w  .j  ava  2s .c  om
        Security.removeProvider(new BouncyCastleProvider().getName());
        Security.addProvider(new BouncyCastleProvider());
        //log.info("Lista de proveedores disponible:"+Arrays.asList(Security.getProviders()));
        org.apache.xml.security.Init.init();
        Properties configuracion = new Properties();
        configuracion.put("HOST_SMTP", "192.168.10.7");

        SendMailUtil.init(configuracion); //benito.galan@avansi.com.do
        MultiPartEmail mail = SendMailUtil.getCurrentInstance().buildMessage("Ejemplo de Firma",
                "rquintero@viavansi.com", "", "<p>rub&eacute;n</p> ", "certificadoavansicxa", "avansicxa");
        mail.setDebug(true);
        // Enviamos 
        String id = mail.send();
        System.out.println(id);
        mail.getMimeMessage().writeTo(System.out);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:GetPinBlock.java

public String encrypt3DES(String pin, String cardNum, String encriptionKey) throws Exception {

    byte[] cipherText = null;
    try {//from w w  w. j a  va2  s. c o  m
        String convertedPin = "04TTTTFFFFFFFFFF".replaceAll("TTTT", pin);
        byte[] convertedPinByteArray = hexStringToByteArray(convertedPin);

        String convertedCardNum = "0000".concat(cardNum.substring(3, 15));
        byte[] convertedCardByteArray = hexStringToByteArray(convertedCardNum);
        //    System.out.println(convertedCardNum);

        byte[] messByteArr = new byte[convertedPinByteArray.length];
        int i = 0;
        for (byte b : convertedCardByteArray)
            messByteArr[i] = (byte) (b ^ convertedPinByteArray[i++]);
        //   System.out.println(byteArrToHexString(messByteArr));

        byte[] keyByteArr = hexStringToByteArray(encriptionKey);

        final SecretKey key = new SecretKeySpec(keyByteArr, "DESede");
        Cipher cipher;

        Security.addProvider(new BouncyCastleProvider());
        cipher = Cipher.getInstance("DESede/ECB/Nopadding");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        cipherText = cipher.doFinal(messByteArr);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        cipherText = null;
    }
    return byteArrToHexString(cipherText);

}

From source file:NaverShopnGetModel.java

public String run() {
    String response_type = "FALSE";
    try {//ww  w  .j  a v a 2  s . c om
        SimpleCryptLib SimpleCryptLib = new SimpleCryptLib();
        Security.addProvider(new BouncyCastleProvider());

        String accessLicense = "0100010000f3814c41974dc3e7f98d1cd213fa8b84c396872ff6c1abb57f0d2516f31cfb43";
        String secretKey = "AQABAADKObge3IgWtlgfbo1TaLqHKpjfyGNKYuZbfOZB8m+WJA==";

        String serviceName = "ProductService"; // 
        String id = "eugink";
        String password = "asdf0101";
        String timestamp = null;
        String signature = null;
        String data = null;

        byte[] encryptKey = null;

        String encryptedData = null;
        String decryptedData = null;
        String hashedData = null;

        String operationName = "GetModelList";
        //String orderID = "200087036";      

        //timestamp create
        timestamp = SimpleCryptLib.getTimestamp();
        System.out.println("timestamp:" + timestamp);

        //generateSign
        data = timestamp + serviceName + operationName;
        signature = SimpleCryptLib.generateSign(data, secretKey);

        //generateKey
        encryptKey = SimpleCryptLib.generateKey(timestamp, secretKey);

        //encrypt
        encryptedData = SimpleCryptLib.encrypt(encryptKey, password.getBytes("UTF-8"));

        //decrypt
        decryptedData = new String(SimpleCryptLib.decrypt(encryptKey, encryptedData), "UTF-8");

        //sha256
        hashedData = SimpleCryptLib.sha256(password);

        NaverShopnGetModel NaverShopnGetModel = new NaverShopnGetModel();
        System.out.println("NaverShopnGetModel.getYesterday():" + NaverShopnGetModel.getYesterday());
        System.out.println("NaverShopnGetModel.getYesterday():" + NaverShopnGetModel.getToday());

        System.out.println("accessLicense : [" + accessLicense + "]");
        System.out.println("secretKey : [" + secretKey + "]");
        System.out.println("serviceName : [" + serviceName + "]");
        System.out.println("operationName : [" + operationName + "]");
        System.out.println("timestamp : [" + timestamp + "]");
        System.out.println("signature : [" + signature + "]");
        System.out.println("encryptKey : [" + new String(Hex.encode(encryptKey)) + "]");
        System.out.println("encryptedData : [" + encryptedData + "]");
        System.out.println("decryptedData : [" + decryptedData + "]");
        System.out.println("sha256Data : [" + hashedData + "]");

        System.out.println("NaverShopnGetModel.getYesterday():" + NaverShopnGetModel.getYesterday());
        System.out.println("NaverShopnGetModel.getToday():" + NaverShopnGetModel.getToday());
        String modellist = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:shop=\"http://shopn.platform.nhncorp.com/\">"
                + "<soap:Header/>" + "<soap:Body>" + "<shop:GetModelListRequest>"
                + "<shop:RequestID>njoyny2</shop:RequestID>" + "<shop:AccessCredentials>"
                + "<shop:AccessLicense>" + accessLicense + "</shop:AccessLicense>" + "<shop:Timestamp>"
                + timestamp + "</shop:Timestamp>" + "<shop:Signature>" + signature + "</shop:Signature>"
                + "</shop:AccessCredentials>" + "<shop:Version>1.0</shop:Version>"
                + "<ModelName></ModelName>" + "</shop:GetModelListRequest>" + "</soap:Body>"
                + "</soap:Envelope>";
        System.out.println("#######################################################");
        System.out.println(modellist);
        System.out.println("#######################################################");
        //Create socket
        String hostname = "sandbox.api.naver.com";
        //String hostname = "api.naver.com";
        int port = 80;
        InetAddress addr = InetAddress.getByName(hostname);
        Socket sock = new Socket(addr, port);

        //Send header 
        String path = "/ShopN/ProductService";
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
        // You can use "UTF8" for compatibility with the Microsoft virtual machine.
        wr.write("POST " + path + " HTTP/1.0 \r\n");
        wr.write("Host: sandbox.api.naver.com \r\n");
        //wr.write("Host: api.naver.com \r\n");
        //wr.write("Content-Length: " + xmldata.length() + "\r\n");
        wr.write("Content-Length: " + modellist.length() + "\r\n");
        wr.write("Content-Type: text/xml; charset=\"UTF-8\"\r\n");
        wr.write("SOAPAction: \"http://sandbox.api.naver.com/ShopN/ProductService\" \r\n");
        //wr.write("SOAPAction: \"http://api.naver.com/Checkout/MallService2\" \r\n");
        wr.write("\r\n");

        //Send data
        //wr.write(xmldata);
        wr.write(modellist);
        wr.flush();
        // InputStream test = new InputStream(sock.getInputStream(),"UTF-8");   

        // Response
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
        String line = "";
        String line_total = "";
        String tmp = "";
        String tmp2 = "";
        String newxml = "";

        while ((line = rd.readLine()) != null) {
            if (line.startsWith("<?xml")) {
                line = line.replaceAll("&#xd;", " ");
                line_total = line_total + line;
                System.out.println(line);
            }

        }

        StringBuffer sf = new StringBuffer();
        /* while((line = rd.readLine()) != null){
           if (line.startsWith("<?xml")){
              sf.append(line+"\n");        //   .
           }
        }*/

        //char[] bufferResult = new char[1048576];
        /* char[] bufferResult = new char[60000000];
         int index = -1;
         while((index = rd.read(bufferResult)) != -1) {
                
        sf.append(bufferResult, 135, index); //response   133 135 
                
         }*/

        //line_total = sf.toString().trim();        
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

        line_total = line_total.replaceAll("n:", "");
        //System.out.println(sf.toString().trim());   

        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%" + line_total + "%%%%%%%%%%%%%%%%%%%%%%%%%%");

        //xml2
        InputStream in = new ByteArrayInputStream(line_total.getBytes("UTF-8"));

        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(in);

        System.out.println("%%%%%%%%%%%%%%%%2222%%%%%%%%%%%%%%%%%");

        Element element = document.getRootElement();
        List envel_list = element.getChildren();
        List body_list = null;
        List body_list1 = null;
        List result_list = null;
        List result_list1 = null;
        List result_list2 = null;
        List result_list3 = null;
        List result_list4 = null;
        List result_list5 = null;
        List info_list = null;
        List contr_group_list = null;
        List contr_info_list = null;

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        CallableStatement cStmt = null;

        //conn.setAutoCommit(false);

        long UNIT_ID = 0;
        long cnt = 0;
        long interface_seq = 0;
        long DEL_QTY = 0;
        long ITEM_ID = 0;
        String ITEM_NAME = null;

        System.out.println("GetModeListResponse.size:" + envel_list.size());
        Element envel_el = (Element) envel_list.get(0);
        body_list = envel_el.getChildren();

        //System.out.println("+++++++11+++++++++++el.getName() : " + envel_el.getChildren());

        //System.out.println("body_list.size:"+body_list.size());
        Element body_el = (Element) body_list.get(0);
        result_list = body_el.getChildren();

        System.out.println(body_list);
        System.out.println("###################################");

        System.out.println(result_list);
        System.out.println("###################################");

        Element body_el1 = (Element) result_list.get(5);
        result_list1 = body_el1.getChildren();

        System.out.println(body_el1);
        System.out.println("###################################");

        System.out.println(result_list1);
        System.out.println("###################################");

        Element body_el2 = (Element) result_list1.get(0);
        result_list2 = body_el2.getChildren();
        System.out.println(body_el2);
        System.out.println("###################################");

        System.out.println(result_list2);
        System.out.println("###################################");

        System.out.println("Code:" + body_el2.getChildText("Code"));
        //                         
        //System.out.println("body_list.size:"+body_list.size());

        //System.out.println("++++++++22++++++++++el.getName() : " + body_el.getChildren());
        /*for (int h = 0; h < result_list.size(); h++) {
                
           Element body_el1 = (Element) result_list.get(h);
                
           result_list1 = body_el1.getChildren("Category");
           //System.out.println("result_list1.size:"+result_list1.size());
                
                   
           //System.out.println("++++++++33++++++++++el.getName() : " + body_el1.getChildren());
           for (int i = 0; i < result_list1.size(); i++) {
                
              Element body_el2 = (Element) result_list1.get(i);
              System.out.println("CategoryName:"+body_el2.getChildText("CategoryName"));
              System.out.println("Id:"+body_el2.getChildText("Id"));
              System.out.println("Name:"+body_el2.getChildText("Name"));
              System.out.println("Last:"+body_el2.getChildText("Last"));
        // 
                               StringBuffer setOrder = new StringBuffer();
                               setOrder.append(" insert  \n");
                               setOrder.append(" into mirus_navershopnctg(  \n");
                               setOrder.append("     CategoryName, Id, Name, Last, insert_date ,modify_date \n");
                               setOrder.append(" ) values (  \n");
                               setOrder.append("     ?, ?, ?, ?, sysdate,null  \n");
                               setOrder.append(" )  \n");
                
                               pstmt = conn.prepareStatement(setOrder.toString());
                                       
                               System.out.println("query:"+setOrder.toString());
                
                               int insert_cnt = 0;
                
                               try {
                                       pstmt.clearParameters();
                
                                       //
                                       pstmt.setString(1, body_el2.getChildText("CategoryName") );                           // CategoryName
                                       pstmt.setLong( 2, Long.parseLong(body_el2.getChildText("Id")));     // Id
                                       pstmt.setString(3 , body_el2.getChildText("Name"));                                 //Name
                                       pstmt.setString(4 , body_el2.getChildText("Last"));   // Last
                
                                       pstmt.executeUpdate();
                
                                       System.out.println("\n+ insert_cnt ["+i+"]\n");
                
                
                                   } catch(Exception e) {
                                         response_type="FALSE";
                                           e.printStackTrace();
                                           conn.rollback();
                                           break;
                                   }
                          conn.commit();
                
                                   if(pstmt != null) {try{ pstmt.close(); } catch(Exception ex){ response_type="FALSE";}}
                      
                
                   
           }
        }
                       */

    } catch (Exception e) {
        System.out.println("run() : " + e.getMessage());
        response_type = "FALSE";
    } finally {
    }

    return response_type;
}

From source file:createSod.java

License:Open Source License

/**
 * @param args//from   w  w  w  .ja  v a2 s .  c  o m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:NaverShopnGetArea.java

public String run() {
    String response_type = "FALSE";
    try {//w ww  . ja  va  2  s .c  o  m
        SimpleCryptLib SimpleCryptLib = new SimpleCryptLib();
        Security.addProvider(new BouncyCastleProvider());

        String accessLicense = "0100010000f3814c41974dc3e7f98d1cd213fa8b84c396872ff6c1abb57f0d2516f31cfb43";
        String secretKey = "AQABAADKObge3IgWtlgfbo1TaLqHKpjfyGNKYuZbfOZB8m+WJA==";

        String serviceName = "ProductService"; // 
        String id = "eugink";
        String password = "asdf0101";
        String timestamp = null;
        String signature = null;
        String data = null;

        byte[] encryptKey = null;

        String encryptedData = null;
        String decryptedData = null;
        String hashedData = null;

        String operationName = "GetOriginAreaList";
        //String orderID = "200087036";      

        //timestamp create
        timestamp = SimpleCryptLib.getTimestamp();
        System.out.println("timestamp:" + timestamp);

        //generateSign
        data = timestamp + serviceName + operationName;
        signature = SimpleCryptLib.generateSign(data, secretKey);

        //generateKey
        encryptKey = SimpleCryptLib.generateKey(timestamp, secretKey);

        //encrypt
        encryptedData = SimpleCryptLib.encrypt(encryptKey, password.getBytes("UTF-8"));

        //decrypt
        decryptedData = new String(SimpleCryptLib.decrypt(encryptKey, encryptedData), "UTF-8");

        //sha256
        hashedData = SimpleCryptLib.sha256(password);

        NaverShopnGetArea NaverShopnGetArea = new NaverShopnGetArea();
        System.out.println("NaverShopnGetArea.getYesterday():" + NaverShopnGetArea.getYesterday());
        System.out.println("NaverShopnGetArea.getYesterday():" + NaverShopnGetArea.getToday());

        System.out.println("accessLicense : [" + accessLicense + "]");
        System.out.println("secretKey : [" + secretKey + "]");
        System.out.println("serviceName : [" + serviceName + "]");
        System.out.println("operationName : [" + operationName + "]");
        System.out.println("timestamp : [" + timestamp + "]");
        System.out.println("signature : [" + signature + "]");
        System.out.println("encryptKey : [" + new String(Hex.encode(encryptKey)) + "]");
        System.out.println("encryptedData : [" + encryptedData + "]");
        System.out.println("decryptedData : [" + decryptedData + "]");
        System.out.println("sha256Data : [" + hashedData + "]");

        System.out.println("NaverShopnGetArea.getYesterday():" + NaverShopnGetArea.getYesterday());
        System.out.println("NaverShopnGetArea.getToday():" + NaverShopnGetArea.getToday());
        String ctglist = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:shop=\"http://shopn.platform.nhncorp.com/\">"
                + "<soap:Header/>" + "<soap:Body>" + "<shop:GetOriginAreaListRequest>" + "<!--Optional:-->"
                + "<shop:RequestID>njoyny2</shop:RequestID>" + "<shop:AccessCredentials>"
                + "<shop:AccessLicense>" + accessLicense + "</shop:AccessLicense>" + "<shop:Timestamp>"
                + timestamp + "</shop:Timestamp>" + "<shop:Signature>" + signature + "</shop:Signature>"
                + "</shop:AccessCredentials>" + "<shop:Version>2.0</shop:Version>" + "<!--Optional:-->"
                + "<OriginAreaName> </OriginAreaName>" +
                //"<CategoryId></CategoryId>" +
                "</shop:GetOriginAreaListRequest>" + "</soap:Body>" + "</soap:Envelope>";

        //Create socket
        String hostname = "sandbox.api.naver.com";
        //String hostname = "api.naver.com";
        int port = 80;
        InetAddress addr = InetAddress.getByName(hostname);
        Socket sock = new Socket(addr, port);

        //Send header 
        String path = "/ShopN/ProductService";
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
        // You can use "UTF8" for compatibility with the Microsoft virtual machine.
        wr.write("POST " + path + " HTTP/1.0 \r\n");
        wr.write("Host: sandbox.api.naver.com \r\n");
        //wr.write("Host: api.naver.com \r\n");
        //wr.write("Content-Length: " + xmldata.length() + "\r\n");
        wr.write("Content-Length: " + ctglist.length() + "\r\n");
        wr.write("Content-Type: text/xml; charset=\"UTF-8\"\r\n");
        wr.write("SOAPAction: \"http://sandbox.api.naver.com/ShopN/ProductService\" \r\n");
        //wr.write("SOAPAction: \"http://api.naver.com/Checkout/MallService2\" \r\n");
        wr.write("\r\n");

        //Send data
        //wr.write(xmldata);
        wr.write(ctglist);
        wr.flush();
        // InputStream test = new InputStream(sock.getInputStream(),"UTF-8");   

        // Response
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
        String line = "";
        String line_total = "";
        String tmp = "";
        String tmp2 = "";
        String newxml = "";

        while ((line = rd.readLine()) != null) {
            if (line.startsWith("<?xml")) {
                line = line.replaceAll("&#xd;", " ");
                line_total = line_total + line;
                System.out.println(line);
            }

        }

        StringBuffer sf = new StringBuffer();
        /* while((line = rd.readLine()) != null){
           if (line.startsWith("<?xml")){
              sf.append(line+"\n");        //   .
           }
        }*/

        //char[] bufferResult = new char[1048576];
        /* char[] bufferResult = new char[60000000];
         int index = -1;
         while((index = rd.read(bufferResult)) != -1) {
                
        sf.append(bufferResult, 135, index); //response   133 135 
                
         }*/

        //line_total = sf.toString().trim();        
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

        line_total = line_total.replaceAll("n:", "");
        //System.out.println(sf.toString().trim());   

        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%" + line_total + "%%%%%%%%%%%%%%%%%%%%%%%%%%");

        //xml2
        InputStream in = new ByteArrayInputStream(line_total.getBytes("UTF-8"));

        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(in);

        System.out.println("%%%%%%%%%%%%%%%%2222%%%%%%%%%%%%%%%%%");

        Element element = document.getRootElement();
        List envel_list = element.getChildren();
        List body_list = null;
        List body_list1 = null;
        List result_list = null;
        List result_list1 = null;
        List result_list2 = null;
        List result_list3 = null;
        List result_list4 = null;
        List result_list5 = null;
        List info_list = null;
        List contr_group_list = null;
        List contr_info_list = null;

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        CallableStatement cStmt = null;

        //conn.setAutoCommit(false);

        long UNIT_ID = 0;
        long cnt = 0;
        long interface_seq = 0;
        long DEL_QTY = 0;
        long ITEM_ID = 0;
        String ITEM_NAME = null;

        System.out.println("GetOriginAreaListResponse.size:" + envel_list.size());
        Element envel_el = (Element) envel_list.get(0);
        body_list = envel_el.getChildren();

        //System.out.println("+++++++11+++++++++++el.getName() : " + envel_el.getChildren());

        //System.out.println("body_list.size:"+body_list.size());
        Element body_el = (Element) body_list.get(0);
        result_list = body_el.getChildren();

        System.out.println(body_list);
        System.out.println("###################################");

        System.out.println(result_list);
        System.out.println("###################################");

        Element body_el1 = (Element) result_list.get(5);
        result_list1 = body_el1.getChildren();

        System.out.println(body_el1);
        System.out.println("###################################");

        System.out.println(result_list1);
        System.out.println("###################################");

        Element body_el2 = (Element) result_list1.get(0);
        result_list2 = body_el2.getChildren();
        System.out.println(body_el2);
        System.out.println("###################################");

        System.out.println(result_list2);
        System.out.println("###################################");

        System.out.println("Code:" + body_el2.getChildText("Code"));
        //                         
        //System.out.println("body_list.size:"+body_list.size());

        //System.out.println("++++++++22++++++++++el.getName() : " + body_el.getChildren());
        /*for (int h = 0; h < result_list.size(); h++) {
                
           Element body_el1 = (Element) result_list.get(h);
                
           result_list1 = body_el1.getChildren("Category");
           //System.out.println("result_list1.size:"+result_list1.size());
                
                   
           //System.out.println("++++++++33++++++++++el.getName() : " + body_el1.getChildren());
           for (int i = 0; i < result_list1.size(); i++) {
                
              Element body_el2 = (Element) result_list1.get(i);
              System.out.println("CategoryName:"+body_el2.getChildText("CategoryName"));
              System.out.println("Id:"+body_el2.getChildText("Id"));
              System.out.println("Name:"+body_el2.getChildText("Name"));
              System.out.println("Last:"+body_el2.getChildText("Last"));
        // 
                               StringBuffer setOrder = new StringBuffer();
                               setOrder.append(" insert  \n");
                               setOrder.append(" into mirus_navershopnctg(  \n");
                               setOrder.append("     CategoryName, Id, Name, Last, insert_date ,modify_date \n");
                               setOrder.append(" ) values (  \n");
                               setOrder.append("     ?, ?, ?, ?, sysdate,null  \n");
                               setOrder.append(" )  \n");
                
                               pstmt = conn.prepareStatement(setOrder.toString());
                                       
                               System.out.println("query:"+setOrder.toString());
                
                               int insert_cnt = 0;
                
                               try {
                                       pstmt.clearParameters();
                
                                       //
                                       pstmt.setString(1, body_el2.getChildText("CategoryName") );                           // CategoryName
                                       pstmt.setLong( 2, Long.parseLong(body_el2.getChildText("Id")));     // Id
                                       pstmt.setString(3 , body_el2.getChildText("Name"));                                 //Name
                                       pstmt.setString(4 , body_el2.getChildText("Last"));   // Last
                
                                       pstmt.executeUpdate();
                
                                       System.out.println("\n+ insert_cnt ["+i+"]\n");
                
                
                                   } catch(Exception e) {
                                         response_type="FALSE";
                                           e.printStackTrace();
                                           conn.rollback();
                                           break;
                                   }
                          conn.commit();
                
                                   if(pstmt != null) {try{ pstmt.close(); } catch(Exception ex){ response_type="FALSE";}}
                      
                
                   
           }
        }
                       */

    } catch (Exception e) {
        System.out.println("run() : " + e.getMessage());
        response_type = "FALSE";
    } finally {
    }

    return response_type;
}