CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2000
    Posts
    20

    Can anyone please give me a working code of Encryption and Decryption

    Hi!
    I am quite new to Java Security. I will be very grateful if anyone can send me the working code of Encryption and Decryption using Java. Thanks in advance. Ankur.....


  2. #2
    Join Date
    Jul 1999
    Location
    India.
    Posts
    81

    Re: Can anyone please give me a working code of Encryption and Decryption

    function Encrypt(theText) {
    output = new String;
    Temp = new Array();
    Temp2 = new Array();
    TextSize = theText.length;
    for (i = 0; i < TextSize; i++) {
    rnd = Math.round(Math.random() * 122) + 68;
    Temp[i] = theText.charCodeAt(i) + rnd;
    Temp2[i] = rnd;
    }
    for (i = 0; i < TextSize; i++) {
    output += String.fromCharCode(Temp[i], Temp2[i]);
    }
    return output;
    }
    function unEncrypt(theText) {
    output = new String;
    Temp = new Array();
    Temp2 = new Array();
    TextSize = theText.length;
    for (i = 0; i < TextSize; i++) {
    Temp[i] = theText.charCodeAt(i);
    Temp2[i] = theText.charCodeAt(i + 1);
    }
    for (i = 0; i < TextSize; i = i+2) {
    output += String.fromCharCode(Temp[i] - Temp2[i]);
    }
    return output;
    }
    // End -->
    </script>
    </HEAD>


  3. #3
    Join Date
    Jul 1999
    Location
    India.
    Posts
    81

    Re: Can anyone please give me a working code of Encryption and Decryption

    The above one was from a discussion forum and the below one two.
    /*Acme.Crypto.* is available for free download at www.acme.com*/

    /* A small Applet to Encrypt and decrypt using Des3Cipher */

    /* input - Type in some text in the textarea above Then enter an eight character key in the Key textfield and click the Encrypt button. */

    /* Encrypted output in IE 3.02 and I.E 4.0

    ȯ=0yân|A-s_`C_ÝK{BWÐÒ:_øÈ"`^Y¸`U_a EG¯0~5týóÎÆÀe$»7à ¿v_"|QB&ltRëÇÜeQ/P__بšØsö)z+ô_;Rû¾ ?&»tÑ8"0M^Þ0ÐS__:~E;ÌaXÐð坨Êߺ_éE

    */

    /* Encrypted output in HotJava

    ȯ=0yân|A-s_`C_ÝK{BWÐÒ:_øÈ??^Y¸`U_??EG¯?~5týóÎ?Àe$»7Ã?¿v_?|QB&lt?ëÇ?eQ/P__بšØsö)z+ô_;?û¾?Ž&»tÑ8?0M^Þ?ÐS__?~E;Ì?XÐð坨Êߺ_éE

    */

    /* My observation is the encryption is not the same in both cases*/

    /*This code works properly in Netscape navigator and Hot Java Browser */

    /* My Code */

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import Acme.Crypto.*;

    public class ClientApplet3 extends Applet implements ActionListener
    {

    String textToEncrypt;
    byte[] textToDecrypt;
    Font normal;
    Font big;
    Font bigMessage;

    java.awt.Button encryptButton;
    java.awt.Button decryptButton;
    java.awt.Label encryptedLabel;
    java.awt.TextArea encryptedTextArea;
    java.awt.TextArea decryptedTextArea;
    java.awt.Label decryptedLabel;
    java.awt.Button resetButton;
    byte[] desKey=null;

    StringBuffer str1=new StringBuffer();

    public void init()
    {
    super.init();

    setLayout(new BorderLayout());
    Panel topPanel = new Panel();
    topPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
    resetButton = new java.awt.Button("Generate Key");
    topPanel.add(resetButton);
    encryptButton = new java.awt.Button("Encrypt");
    topPanel.add(encryptButton);
    decryptButton = new java.awt.Button("Decrypt");
    topPanel.add(decryptButton);
    add(topPanel,BorderLayout.NORTH);

    Panel tempPanel = new Panel();
    tempPanel.setLayout(new GridLayout(2,1));

    Panel midPanel = new Panel();
    midPanel.setLayout(new BorderLayout(20,0));
    encryptedLabel = new java.awt.Label("Encrypted Text");
    midPanel.add(encryptedLabel,BorderLayout.NORTH);
    encryptedTextArea = new java.awt.TextArea();
    midPanel.add(encryptedTextArea,BorderLayout.CENTER);
    tempPanel.add(midPanel);

    Panel bottomPanel = new Panel();
    bottomPanel.setLayout(new BorderLayout(20,0));
    decryptedLabel = new java.awt.Label("Decrypted Text");
    bottomPanel.add(decryptedLabel,BorderLayout.NORTH);
    decryptedTextArea = new java.awt.TextArea();
    bottomPanel.add(decryptedTextArea,BorderLayout.CENTER);
    tempPanel.add(bottomPanel);

    add(tempPanel,BorderLayout.CENTER);

    Color mint = new Color(128,175,175);

    setBackground(mint);

    normal = new Font(this.getFont().getName(), Font.BOLD, 12);
    big = new Font(this.getFont().getName(), Font.BOLD, 14);
    bigMessage = new Font(this.getFont().getName(), Font.BOLD, 16);
    encryptedLabel.setText("Text To Encrypt");
    decryptedLabel.setFont(normal);
    decryptedLabel.setText("Message");
    decryptedTextArea.setFont(big);
    decryptedTextArea.setText("Type in some text in the textarea above\n");
    decryptedTextArea.append("Then enter an eight character key in the Key textfield\n");
    decryptedTextArea.append("and click the Encrypt button.");

    encryptedTextArea.requestFocus();

    // Code to add the Action Listener

    encryptButton.addActionListener(this);
    decryptButton.addActionListener(this);
    resetButton.addActionListener(this);

    }

    public void actionPerformed(ActionEvent ae)
    {

    if (ae.getActionCommand() == "Encrypt")
    {
    showStatus("encryption Started");
    encryptbutton_Clicked(desKey);

    }
    else if (ae.getActionCommand() == "Generate Key")
    {

    showStatus("Generate Key");

    //Hard Coding the key for testing
    desKey=fromString("d18a17ce851d99dfcb01d6c714e6446");
    showStatus("Key Length :" + desKey.length + "Key in Hex Format:" + keyString(desKey) );
    }
    else if (ae.getActionCommand()== "Decrypt")
    {
    showStatus("Decrypting");
    decrypt(desKey,str1.toString().getBytes());

    }
    }

    void encryptbutton_Clicked(byte[] desKey)
    {
    String textToEncrypt = encryptedTextArea.getText();

    if(textToEncrypt.length()==0)
    {
    decryptedTextArea.setText("Please enter some text to encrypt");
    return ;
    }

    /// A simple Padding Scheme

    // Pad the text if not a mutiple of 8
    // the last charecter indicating the number of charecters padded
    // for none

    int Count = textToEncrypt.length() % 8;

    if (Count != )
    {
    int PaddedChrs=1 ;

    while(Count < 7)
    {
    textToEncrypt += 1;
    Count += 1;
    PaddedChrs += 1;
    }

    textToEncrypt+=PaddedChrs;

    }

    // Convert the clearText to bytes
    byte[] clearText = new byte[8];
    byte[] ciphertext = new byte[8];
    int srcBegin =0;
    int srcEnd =8;

    Des3Cipher des;
    String tempStr =null;

    try
    {
    // Create the cipher

    des = new Des3Cipher(desKey);

    System.out.println("Text Length" + textToEncrypt.length());

    for ( ;srcEnd<=textToEncrypt.length(); )
    {
    clearText=textToEncrypt.substring(srcBegin,srcEnd).getBytes();

    // output to console to check the byte going for a six
    System.out.println("To Encrypt " + new String(clearText));

    srcBegin=srcEnd;
    srcEnd = srcEnd+8;

    des.encrypt(clearText,0, ciphertext,0);

    textToDecrypt= ciphertext;
    tempStr = new String(ciphertext);
    str1.append(tempStr);
    }

    System.out.println("Encrypted String" + str1);
    System.out.println("Encrypted String" + str1.length());

    encryptedTextArea.setText("Cipher Text " + str1.toString());
    encryptedLabel.setText("Encrypted Text");

    encryptButton.setEnabled(false);
    // decryptButton.setEnabled(true);
    // decryptButton.setVisible(true);
    encryptedTextArea.requestFocus();

    }

    catch (Exception e)
    {
    showStatus(e.toString());
    }

    }

    private void decrypt(byte[] sessionKey,byte[] ciphertext)
    {
    try
    {
    Des3Cipher des;
    String textToDecrypt = new String(ciphertext);
    String tempStr ;
    byte[] tempCipherText = new byte[8];
    byte[] decrypted=new byte[8];
    int srcBegin= ;
    int srcEnd=8;
    StringBuffer str = new StringBuffer();

    des = new Des3Cipher(sessionKey);

    for ( ; srcEnd<=textToDecrypt.length(); )
    {
    //textToDecrypt.getBytes(srcBegin,srcEnd,tempCipherText,0);
    tempCipherText=textToDecrypt.substring(srcBegin,srcEnd).getBytes();
    srcBegin=srcEnd;
    srcEnd = srcEnd+8;

    des.decrypt(tempCipherText,0,decrypted,0);

    tempStr = new String(decrypted);
    str.append(tempStr);
    }

    System.out.println("Decrypted Text " + str.toString());
    encryptedTextArea.setText("Deciphered Text " + str.toString());
    encryptedLabel.setText("Deciphered Text");

    }

    catch (Exception e)
    {
    e.printStackTrace();
    }

    }

    public String keyString(byte[] key)
    {
    String returnVal = "";

    for (int i=0; i < key.length; i++) {
    returnVal += Integer.toHexString(key[i]&0xff);
    }

    return returnVal;
    }

    /**
    * Returns a byte array from a string of hexadecimal digits.
    */
    public byte[] fromString(String hex) {
    int len = hex.length();
    byte[] buf = new byte[((len + 1) / 2)];

    int i = 0, j = 0;
    if ((len % 2) == 1)
    buf[j++] = (byte) fromDigit(hex.charAt(i++));

    while (i < len) {
    buf[j++] = (byte) ((fromDigit(hex.charAt(i++)) << 4) |
    fromDigit(hex.charAt(i++)));
    }
    return buf;
    }

    /**
    * Returns the number from to 15 corresponding to the hex digit <i>ch</i>.
    */
    public int fromDigit(char ch) {
    if (ch >= '0' && ch <= '9')
    return ch - '0';
    if (ch >= 'A' && ch <= 'F')
    return ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f')
    return ch - 'a' + 10;

    throw new IllegalArgumentException("invalid hex digit '" + ch + "'");
    }

    }
    Kindly help at the earliest . Is it a problem with IE or the code ?

    Thanx in advance

    Kotesh Babu
    [email protected]

    sol :
    1)____________
    After evaluating your code, all seems to be well in your applet. The problem is that the IE VM uses Microsoft components that convert TextArea text
    into a different form before it can be used. Since the Text is different in the TextArea in IE, your encryption or decryption will not work very well. Your
    best bet is to use HotJava to run your applet or use Appletviewer which is included in the Sun JDK.

    Although most applets will run fine in IE, anything that deals with Java cryptology should only run in a relatively PURE environment, like HotJava of a
    JDK viewer.
    **************************
    Hi dude, well, if you want a basic cryptography method which is bidirectionnal (Read <->
    Write) using a password, you can try this, it's not exhaustive, it's not like a try only like in
    UNIX, neither PGP, but quite useful if you want to encrypt quickly with some safety:

    u take each byte and u XOR it with another Byte.

    i.e 'a' XOR 255 => encrypted 'a'
    encrypted 'a' XOR 255 => 'a'

    You can use a password with positionning byte inside it using modulus and maybe some
    Random generic code add to it to make it harder a bit to encrypt it. For sure the Random
    thing must be writted somewhere, but it makes it sometime less obvious.

    the principle is the same the byte XOR the key

    the key is going weird as you can program it using Password, Random Key, counter, etc.

    I hope that this help you a bit,
    for low security encryption !


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured