Friday, May 23, 2014

Simple SecurePasswordVault in Java

There are some instances, you want to store your passwords in files to be used by the programs or scripts. But storing your passwords in plain text is not a good idea. Use the SecurePasswordVault to encrypt your passwords before storing and get it decrypted when you want to use it.

You can use the SecurePasswordVault described here to store any number of encrypted passwords. Passwords are stored as key value pairs.

Key - any name given by the user for the password
Value - encrypted password

SecurePasswordVault will create a file with the given name in the working directory if it doesn't exist. If a file exist then the information in that file will be read.

Passwords are encrypted using the MAC address of the network card. SecurePasswordVault will use the first network card MAC which is not the loop back interface. So the encrypted file can only be decrypted with that particular MAC address. If you want to reset the pass word details, just delete the password file and run the SecurePasswordVault.

You can download the sample code from the following Github repository
https://github.com/jsdjayanga/secure_password

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package com.wso2.devgov;

import org.bouncycastle.util.encoders.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.*;

/**
* Created by jayanga on 3/31/14.
*/
public class SecurePasswordVault {

    private static final int AES_KEY_LEN = 32;
    private static final int PASSWORD_LEN = 256;
    
    private static boolean initialized;
    private final String secureFile;
    private final byte[] networkHardwareHaddress;
    private Map<String, String> secureDataMap;
    private List<String> secureDataList;

    SecretKeySpec secretKey;

    public SecurePasswordVault(String filename, String[] secureData) throws IOException {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        initialized = false;
        secureFile = filename;
        networkHardwareHaddress = SecurePasswordVault.readNetworkHardwareAddress();
        secureDataMap = new HashMap<String, String>();

        this.secureDataList = new ArrayList<String>(secureData.length);
        Collections.addAll(secureDataList, secureData);

        byte[] key = new byte[AES_KEY_LEN];
        Arrays.fill(key, (byte)0);

        for(int index = 0; index < networkHardwareHaddress.length; index++){
            key[index] = networkHardwareHaddress[index];
        }

        secretKey = new SecretKeySpec(key, "AES");

        if (!isInitialized()){
            readSecureData(secureDataList);
            persistSecureData();
        }

        readSecureDataFromFile();
    }
    
    private boolean isInitialized(){
        if (initialized == true){
            return true;
        }else{
            File file = new File(secureFile);
            if (file.exists()){
                initialized = true;
                return initialized;
            }
        }
        return false;
    }

    private static byte[] readNetworkHardwareAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        if (networkInterfaceEnumeration != null){
            NetworkInterface networkInterface = null;
            while (networkInterfaceEnumeration.hasMoreElements()){
                networkInterface = networkInterfaceEnumeration.nextElement();
                if (!networkInterface.isLoopback()){
                    break;
                }
            }

            if (networkInterface == null){
                networkInterface = networkInterfaceEnumeration.nextElement();
            }

            byte[] hwaddr = networkInterface.getHardwareAddress();

            return hwaddr;
        }else{
            throw new RuntimeException("Cannot initialize. Failed to generate unique id.");
        }
    }

    private byte[] encrypt(String word) {
        byte[] password = new byte[PASSWORD_LEN];
        Arrays.fill(password, (byte)0);

        byte[] pw = new byte[0];

        try {
            pw = word.getBytes("UTF-8");

            for(int index = 0; index < pw.length; index++){
                password[index] = pw[index];
            }

            byte[] cipherText = new byte[password.length];

            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("AES/ECB/NoPadding");

                try {
                    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

                    int ctLen = 0;
                    try {
                        ctLen = cipher.update(password, 0, password.length, cipherText, 0);
                        ctLen += cipher.doFinal(cipherText, ctLen);

                        return cipherText;
                    } catch (ShortBufferException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    }
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String decrypt(byte[] cipherText) {
        byte[] plainText = new byte[PASSWORD_LEN];

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/NoPadding");

            try {
                cipher.init(Cipher.DECRYPT_MODE, secretKey);

                int plainTextLen = 0;
                try {
                    plainTextLen = cipher.update(cipherText, 0, PASSWORD_LEN, plainText, 0);

                    try {
                        plainTextLen += cipher.doFinal(plainText, plainTextLen);
                        String password = new String(plainText);
                        return password.trim();

                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    }
                } catch (ShortBufferException e) {
                    e.printStackTrace();
                }


            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }

    public void readSecureData(List<String> secureDataList) throws IOException {
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        for(int index = 0; index < secureDataList.size(); index++){
            System.out.println("Please enter the value for :" + secureDataList.get(index));

            String value = new String(Base64.encode(encrypt(bufferRead.readLine())));
            secureDataMap.put(secureDataList.get(index), value);
        }
    }

    public String getSecureData(String key) {
        String value = secureDataMap.get(key);
        if (value != null){
            return decrypt(Base64.decode(value.getBytes()));
        }

        throw new RuntimeException("Given key is unknown. [key=" + key + "]");
    }

    private void readSecureDataFromFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(secureFile));

        String line;
        while ((line = br.readLine()) != null){
            int dividerPoint = line.indexOf("=");
            if (dividerPoint > 0){
                secureDataMap.put(line.substring(0, dividerPoint), line.substring(dividerPoint + 1));
            }
        }
    }

    private void persistSecureData() throws IOException {
        FileWriter fileWriter = new FileWriter(secureFile);

        for(String key : secureDataMap.keySet()){
            fileWriter.append(key + "=" + secureDataMap.get(key) + "\n");
        }

        fileWriter.close();
    }
}


Wednesday, January 22, 2014

Create Maven project from command line

This post shows how to create a Maven project from command line. Creating a Maven project from command line is note a difficult task. Following are the steps.

  1. Create a directory "testApp" and move into that directory
  2. Run the following command, which will do some downloading from the repository
    mvn archetype:generate
    
  3. Then you will be asked to select a preferred configuration from the given list. It will prompt with a default archetype "org.apache.maven.archetypes:maven-archetype-quickstart" selected. No need to enter a value. Just press enter for the moment.
  4. It will prompt you to select the version of the archetype. By default the latest is selected. No need to enter a value. Just press enter.
  5. It will prompt you for several other inputs
    • Define value for property 'groupId': : com.example.testapp
      
      • This will be the package id
    • Define value for property 'artifactId': : mytestapp
      
      • This will be the name of the final .jar file and whole project will be created inside a directory having this name
    • Define value for property 'version':  1.0-SNAPSHOT: :
      
      • No need to give any input, just press enter
    • Define value for property 'package':&nbsp; com.example.testapp: :
      
      • No need to give any input, just press enter
    • Confirm properties configuration:
      groupId: com.example.testapp
      artifactId: mytestapp
      version: 1.0-SNAPSHOT
      package: com.example.testapp
       Y: : Y
      
      • Confirm the given information by entering 'Y'
  6.  You will see the following out put or similar
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.example.testapp
    [INFO] Parameter: packageName, Value: com.example.testapp
    [INFO] Parameter: package, Value: com.example.testapp
    [INFO] Parameter: artifactId, Value: mytestapp
    [INFO] Parameter: basedir, Value: /home/<custom-path>/testApp
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] project created from Old (1.x) Archetype in dir: /home/<custom-path>/testApp/mytestapp
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 2:58.495s
    [INFO] Finished at: Wed Jan 22 01:29:20 IST 2014
    [INFO] Final Memory: 13M/981M
    [INFO] ------------------------------------------------------------------------
    
  7. A new directory structure along with a pom.xml file is now created. This directory structure and the configurations inside the pom.xml is selected by the archetype. As we didn't specify any archetype, the default "org.apache.maven.archetypes:maven-archetype-quickstart" is used and project is configured according to that.
  8. At this stage you have success fully created a new Maven project using command line.

How to Install Maven (Apache Maven)

Installing Maven on your system is a trivial task. Fully functional ready to use distributions are available at http://maven.apache.org.

  1. You can download the latest Maven distribution from the following link http://maven.apache.org/download.cgi
  2. Then extract the downloaded tar ball. You can do this by the following command
    tar zxvf apache-maven-<version>-bin.tar.gz
    
  3. Add maven bin directory to the PATH environment variable
    export PATH=<maven-location>/bin:$PATH
    
  4. Set M2_HOME environment variable
    export M2_HOME=<maven-location>
    
Now maven is ready to run on your system

Try the following command from any location to confirm Maven is working properly.


mvn –version

Thursday, January 16, 2014

Address Book (Jaggery Application)


This is a very simple application written in Jaggery. It is basically a address book which supports adding new record to the book and deleting records from the book. This application is purposely restricted to those functionalities to keep the code simple to make it easier for the newbies.

Prerequisites
Jaggery should be downloaded and the server should be running. http://jaggeryjs.org/howto.jag

Step 1
Create directory “addressbook”, inside the 'apps' directory. ({JAGGERY_HOME}/apps/)
So your new directory should look like, {JAGGERY_HOME}/apps/addressbook

Step 2
Create a file called “index.jag” inside the directory “addressbook”

Add the following code snippet to the file “index.jag”
NOTE: This is not a part of the Address Book application. But this will help you to see that your application is working.


1
2
3
<%
    print(“Address Book”);
%>

Wait a while until the server automatically deploy your new application.
Goto the below link via your web browser. It should show “Address Book” in the page.
Link http://localhost:9763/addressbook/index.jag


Step 3
Create a file called “jaggery.conf” inside the directory “addressbook”
This one of the most important files in the Jaggery application. It contains application level configurations. For more information please refer http://jaggeryjs.org/apidocs/jagconf.jag

Add the following basic configurations to the jaggery.conf file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
    "displayName":"Address Book", 
    "welcomeFiles":["index.jag"],
    "urlMappings":[       
        {
            "url":"/records/*",
            "path":"/controller/records.jag"
        }
    ]
}

This is need to see the correct display name in the management console. To see please follow the link below
https://192.168.184.1:9443/admin/carbon/

Step 4
Add the following code to the index.jag file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<html>
    <head>
        <title>
            AddressBook
        </title>
        <link href="css/styles.css" rel="stylesheet"></link>
  
    </head>
    <body onload="AddressBook.viewAllRecords()">
        <div class="main_container">
            <div class="row">
                <div class="header">
                    <span class="title">Address Book</span>
                </div>
            </div>
            <div class="row">
                <div class="inputForm">
                    <form action="" id="addNewRecordForm" name="addNewRecordForm">
                        <table>
                            <tr>
                                <td>Name</td>
                                <td>: <input id="name" type="text" /></td>
                            </tr>
                            <tr>
                                <td>Address</td>
                                <td>: <input id="address" type="text" /></td>
                            </tr>
                            <tr>
                                <td>Telephone</td>
                                <td>: <input id="telephone" type="text" /></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td class="add_record_button"><a class="#" onclick="AddressBook.addNewRecord();">Add Record</a></td>
                            </tr>
                        </table>
                    </form>
                </div>
            </div>
            <div class="row">
                <div id="records">
                </div>
            </div>
            <div class="footer">
                JD&copy
            </div>
        </div>
        <script src="js/jquery.min.js"></script>
        <script src="js/mustache.js"></script>
        <script src="js/addressbook.js"></script>
    </body>
</html>

Step 5
Create a directory called "js", and a file called "addressbook.js" inside it. And copy latest versions of "jquery.min.js" and "mustache.js"

Add the following code in to addressbook.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
AddressBook = new function() {

this.addNewRecord = function () {
    console.log("Function called addNewRecord");

    var name = $("#name").val();
    var address = $("#address").val();
    var telephone = $("#telephone").val();

    if(name == null || name == ""){
        alert("Name is null");
        return false;
    } else if(address == null || address == ""){
        alert("Address is null");
        return false;
    } else if (telephone == null || telephone == ""){
        alert("Telephone is null");
        return false;
    }

    if(!AddressBook.validateTelephone(telephone)){
        return false;
    }

    AddressBook.resetInptForm();

    //console.log("Name:" + name);
    //console.log("Address:" + address);
    //console.log("Telepone:" + telephone);

    var data = {"name":name, "address":address, "telephone":telephone};

    AddressBook.makeRequest("POST", "/addressbook/records/", data, function(hmtl){AddressBook.viewAllRecords();});
}

this.resetInptForm = function(){
    $("#name").val('');
    $("#address").val('');
    $("#telephone").val('');
}

this.validateTelephone = function(telephone){
    var stripped = telephone.replace(/[\(\)\.\-\ ]/g, '');
    if(isNaN(parseInt(stripped))){
        alert("Invalid telephone number");
        return false;
    }else{
        return true;
    }
}

this.makeRequest = function (type, url, data, callback){
    console.log("Function called makeRequest");

    $.ajax({
        type: type,
        url: url,
        data: data,
        dataType: "json",
        success: callback
    });
}

this.viewAllRecords = function () {
    console.log("Function called viewAllRecords");

    // Requsting all the records
    AddressBook.makeRequest("GET", "/addressbook/records/", null, function(html){AddressBook.loadRecords(html);});
}

this.loadRecords = function(data) {
    console.log("Function called loadRecords");

    // Updating the display with new records
    $.get('template/record.html', function(templete) {var html = Mustache.to_html(templete, data); $("#records").html(html);});
}

this.deleteRecord = function(id){

    var answer = confirm("Are you really want to delete?");

    if(answer){
        var data = {"id":id};
        AddressBook.makeRequest("POST", "/addressbook/records/", data, function(hmtl){AddressBook.viewAllRecords();});
    }
}

}

Step 6
Create a directory called "controller", and a file called "records.jag" inside it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%
include("../model/recordQuery.jag");

var verb = request.getMethod();
var name = request.getParameter('name');
var address = request.getParameter('address');
var telephone = request.getParameter('telephone');
var id = request.getParameter('id');

if(verb == "POST" && name != null && address != null && telephone != null) {

    var log = new Log();
    log.debug("Adding new record. [Name=" + name + ", Address=" + address + ", Telephone=" + telephone + "]");

    addRecord(name, address, telephone);

} else if(verb == "POST" && id != null ) {
    var log = new Log();
    log.debug("Deleting record. [Id=" + id + "]");

    deleteRecord(id);

} else if(verb == "GET") {
    listAllRecords();
}

%>

Step 7
Create a directory called "model", and a file called "recordQuery.jag" inside it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<%

function addRecord(name, address, telephone){

    var records = session.get("records");
    if (records == null){
        records = new Array();
        session.put("records", records);
        session.put("id", 0);
    }
    
    var id = session.get("id") + 1;
    session.put("id", id);

    var record = {"id":id, "name":name, "address":address, "telephone":telephone};
    records.push(record);

    //var log = new Log();
    //log.info(session.get("records"));
}

function listAllRecords(){
    var records = session.get("records");

    //var log = new Log();
    //log.info(records);

    if (records != null){
        records.sort(sortRecords);
        print({"records" : records});
    }else {
        print("No records");
    }
}

function sortRecords(first, second){
    if (first.name < second.name){
        return -1;
    }
    else if(first.name > second.name){
        return 1;
    }
    else {
        return 0
    }
}

function deleteRecord(id){
    var records = session.get("records");

    for (var index = 0; index < records.length; index++){
        var record = records[index];
        if(record.id == id){
            var temp_record = records[records.length - 1];
            records[records.length - 1] = records[index];
            records[index] = temp_record;

            records.pop();

            break;
        }
    }
}

%>

Step 8
Create a directory called "template", and a file called "record.html" inside it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<div>
<table class="record_table">
    <tr class="table_header">
        <td>
            Name
        </td>
        <td>
            Address
        </td>
        <td>
            Telephone
        </td>
        <td>
        </td>
    </tr>
{{#records}}
    <tr class="table_row">
        <td class="column_name">
            {{name}}
        </td>

        <td class="column_address">
            {{address}}
        </td>

        <td class="column_telephone">
            {{telephone}}
        </td>

        <td class="column_delete">
            <a href="#" class="delete" onclick="AddressBook.deleteRecord({{id}})">Delete</a>
        </td>
    </tr>

{{/records}}
</table>
</div>

The AddressBook is now ready with adding records and deleting records.
Try yourself to add the update functionality to this.

Thursday, December 26, 2013

Encryption

In Computer Science, Encryption refers to the process of encoding (converting into a coded/unreadable form) some information as it cannot be decoded (convert back into a readable form) by the unwanted parties.

Sender encrypt the information using an encryption algorithm with a encryption key. This produces the encrypted message which is unreadable, generally called cipher-text. When the legitimate receivers receive the message they use a decryption algorithm with a secret decryption key to decrypt the message and extract the original information.


  1. Sender prepare the message.
  2. Encrypt the message using encryption key
  3. Encrypted message is sent to the receiver (message is in unreadable form no one can extract the information directly.)
  4. Receiver receive the message and decrypt the message using decryption key
  5. Original message is produced by the receiver

Assumption: Though the encrypted information is hacked by an adversaries they don't have the secret description key to decrypt the message. So the information is safe.

There are two types of encryption mechanisms
  1. Symmetric Encryption - A single key is used for both encryption and decryption. The key is shared among the senders and receivers. The requirement to have access to the key by both parties is one of the drawbacks of this mechanism.
  2. Asymmetric Encryption (Public Key Encryption) - Two separate keys are used for encryption and decryption. One key is made public and published, this is used to encrypt the message. The other key is kept private (secret) and used to decrypt the message.

Thursday, December 12, 2013

org.apache.axis2.AxisFault: Error in encryption (Illegal key size or default parameters)

This issue comes when your application uses a bigger key size in encryption than the default key size provided by the Java runtime.

Solution:
  1. Download Unlimited Strength Java(TM) Cryptography Extension (JCE) Policy Files for the Java(TM) Platform (based on your JDK version)
  2. Please *.jar files in the following location
    • $JAVA_HOME/jre/lib/security/

[java] Using WS-Security
     [java] 13/12/12 20:12:25 INFO mail.MailTransportSender: MAILTO Sender started
     [java] 13/12/12 20:12:25 INFO jms.JMSSender: JMS Sender started
     [java] 13/12/12 20:12:25 INFO jms.JMSSender: JMS Transport Sender initialized...
     [java] org.apache.axis2.AxisFault: Error in encryption
     [java]     at org.apache.rampart.handler.RampartSender.invoke(RampartSender.java:76)
     [java]     at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
     [java]     at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
     [java]     at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:261)
     [java]     at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:426)
     [java]     at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430)
     [java]     at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
     [java]     at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
     [java]     at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:554)
     [java]     at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:530)
     [java]     at samples.userguide.StockQuoteClient.executeClient(Unknown Source)
     [java]     at samples.userguide.StockQuoteClient.main(Unknown Source)
     [java] Caused by: org.apache.rampart.RampartException: Error in encryption
     [java]     at org.apache.rampart.builder.AsymmetricBindingBuilder.doSignBeforeEncrypt(AsymmetricBindingBuilder.java:612)
     [java]     at org.apache.rampart.builder.AsymmetricBindingBuilder.build(AsymmetricBindingBuilder.java:97)
     [java]     at org.apache.rampart.MessageBuilder.build(MessageBuilder.java:147)
     [java]     at org.apache.rampart.handler.RampartSender.invoke(RampartSender.java:65)
     [java]     ... 11 more
     [java] Caused by: org.apache.ws.security.WSSecurityException: Cannot encrypt data; nested exception is:
     [java]     org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size or default parameters

     [java] Original Exception was java.security.InvalidKeyException: Illegal key size or default parameters
     [java]     at org.apache.ws.security.message.WSSecEncrypt.doEncryption(WSSecEncrypt.java:608)
     [java]     at org.apache.ws.security.message.WSSecEncrypt.doEncryption(WSSecEncrypt.java:461)
     [java]     at org.apache.ws.security.message.WSSecEncrypt.encryptForInternalRef(WSSecEncrypt.java:350)
     [java]     at org.apache.rampart.builder.AsymmetricBindingBuilder.doSignBeforeEncrypt(AsymmetricBindingBuilder.java:598)
     [java]     ... 14 more
     [java] Caused by: org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size or default parameters
     [java] Original Exception was java.security.InvalidKeyException: Illegal key size or default parameters

     [java]     at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1140)
     [java]     at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1081)
     [java]     at org.apache.xml.security.encryption.XMLCipher.encryptElementContent(XMLCipher.java:855)
     [java]     at org.apache.xml.security.encryption.XMLCipher.doFinal(XMLCipher.java:985)
     [java]     at org.apache.ws.security.message.WSSecEncrypt.doEncryption(WSSecEncrypt.java:602)
     [java]     ... 17 more
     [java] Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
     [java]     at javax.crypto.Cipher.a(DashoA13*..)
     [java]     at javax.crypto.Cipher.a(DashoA13*..)
     [java]     at javax.crypto.Cipher.a(DashoA13*..)
     [java]     at javax.crypto.Cipher.init(DashoA13*..)
     [java]     at javax.crypto.Cipher.init(DashoA13*..)
     [java]     at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1137)
     [java]     ... 21 more

Tuesday, October 8, 2013

Factorial

Factorial is the product of all the non-negative integers less  than or equal to the given number n.

Factorial , C++ implementation 

int Factorial(int n)
{
    if (n == 0)
    {
        return 1;
    }
   
    return n * Factorial(n - 1);
}