Encryption of a string

Can any one help me coding a string to be encrypted and decrypted as and when required.

The JCE starting point is http://java.sun.com/products/jce/

Similar Messages

  • I need a function that will go through and encrypt all the strings

    I want to use one way enryption and need a function that will
    go through and encrypt all the strings in my password column in sql
    server 2003.
    I also need a function that compares a test password string
    is equal to the hash value in the database. Can anyone give me some
    advice in this?

    Apparently it's not as simple as I thought. My first instinct
    was
    update yourtable set password = '#hash(password)#'
    but that will crash
    This is inefficient, but you only have to do it once.
    query1
    select id, password thepassword
    from yourtable
    cfloop query="query1"
    update yourtable
    set password = '#hash(thepassword)#'
    where id = #id#

  • How to encrypt with a string as input,but not a key object

    As far as I know,when encrypt or decrypt ,a key must first be got,and the key is first generate by a tool or from SecurityRandom,that means I can not generate the same key with the same input.Does there is a method which can generate a same with the same input string?
    There is a need to transfer file between to site,and the customer wish to encrypt these files during transfering,and they want to store a string into each database at each site,when sending and receiving files,get the string from the database to encrypt or decrypt the file,they alse want to have a control of the string,they can change the string randomly if they wish as long as long keep each string is equal,how to realize this?

    I think what you are looking for is a password based encryption (PBE). An example of using the same is mentioned in JCE reference guide. Below is the relevant code/docs from the rference guide.
    Using Password-Based Encryption
    In this example, we prompt the user for a password from which we derive an encryption key.
    It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.
    For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.
    The following method is an example of how to collect a user password as a char array:
         * Reads user password from given input stream.
        public char[] readPasswd(InputStream in) throws IOException {
            char[] lineBuffer;
            char[] buf;
            int i;
            buf = lineBuffer = new char[128];
            int room = buf.length;
            int offset = 0;
            int c;
    loop:   while (true) {
                switch (c = in.read()) {
                  case -1:
                  case '\n':
                    break loop;
                  case '\r':
                    int c2 = in.read();
                    if ((c2 != '\n') && (c2 != -1)) {
                        if (!(in instanceof PushbackInputStream)) {
                            in = new PushbackInputStream(in);
                        ((PushbackInputStream)in).unread(c2);
                    } else
                        break loop;
                  default:
                    if (--room < 0) {
                        buf = new char[offset + 128];
                        room = buf.length - offset - 1;
                        System.arraycopy(lineBuffer, 0, buf, 0, offset);
                        Arrays.fill(lineBuffer, ' ');
                        lineBuffer = buf;
                    buf[offset++] = (char) c;
                    break;
            if (offset == 0) {
                return null;
            char[] ret = new char[offset];
            System.arraycopy(buf, 0, ret, 0, offset);
            Arrays.fill(buf, ' ');
            return ret;
        }In order to use Password-Based Encryption (PBE) as defined in PKCS #5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption:
        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;
        // Salt
        byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        // Iteration count
        int count = 20;
        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);
        // Prompt user for encryption password.
        // Collect user password as char array (using the
        // "readPasswd" method from above), and convert
        // it into a SecretKey object, using a PBE key
        // factory.
        System.out.print("Enter encryption password:  ");
        System.out.flush();
        pbeKeySpec = new PBEKeySpec(readPasswd(System.in));
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        // Our cleartext
        byte[] cleartext = "This is another example".getBytes();
        // Encrypt the cleartext
        byte[] ciphertext = pbeCipher.doFinal(cleartext);Hope this helps
    Sai Pullabhotla

  • What about encrypt some text/string

    What about encrypt a string. I'm troubled to use javax.crypt or java.security. Is anyone would show me how? Just give some example ho to use it. Thank you for all.

    I've try something like this :
    static JFrame Frame;
    static JPanel Panel;
    static JLabel Judul;
    static JTextArea Terang, Sandi;
    static JButton OK;
    static Insets lokasi;
    static Cipher ecipher,dcipher;
    try {
    // Generate a DES key
    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    SecretKey key = keyGen.generateKey();
    //Terang.setText(key.toString());
    ecipher = Cipher.getInstance("DES");
    dcipher = Cipher.getInstance("DES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    ecipher.init(Cipher.DECRYPT_MODE, key);
    // Encode the string into bytes using utf-8
    String str="AMRI SHODIQ";
    byte[] utf8 = str.getBytes("UTF8");
    Terang.setText(utf8.toString());
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    Sandi.setText(enc.toString());
    byte[] dec = dcipher.doFinal(Sandi.getText().getBytes());
    str =new String(utf8, "UTF8");
    Terang.setText(str);
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (javax.crypto.BadPaddingException e) {
    The compiling was going well but the the result is not what i expected to have. Please give me a favour correcting this code

  • Cipher - encrypt large String variable

    Hello,
    I have a jUnit test for a simple Cipher encryption/decryption.
    I want to write a test to encrypt large data.
    Do I have to change the encryption variable type from String to a Stream class?
    Anyone have suggestion?
    package no.ssb.cipher;
    import org.junit.*;
    import static org.junit.Assert.*;
    * Unit test for simple App.
    public class SimpleStringCipherTest {
    private SimpleStringCipher simpleStringCipher;
    * Create the test case
    * @param testName name of the test case
    @Before
    public void setUp()
    simpleStringCipher = new SimpleStringCipher("tvnw63ufg9gh5392");
    @Test
    public void testBasicEncyption() throws Exception {         
    String plainText = "2010 starts new decade.";
    String encrypted = simpleStringCipher.encrypt(plainText);
    System.out.println("Encrypted: " + encrypted);
    assertTrue(!plainText.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test
    public void testEncryptionIsNotURLSafe() throws Exception{
    String plainText = "2010 starts new decade.";
    String expectedValue = "abe6vPUFQ4xSMezuFF2HBNC3dW98iifMeM027PKKnNw=";
    String encrypted = simpleStringCipher.encrypt(plainText);
    assertTrue(!plainText.equals(encrypted));
    assertTrue(expectedValue.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test(expected=IllegalArgumentException.class)
    public void testInvalidSecretKey() throws Exception{
    SimpleStringCipher invalidCipher = new SimpleStringCipher("tull");
    @Test(expected=Exception.class)
    public void testDecryptInvalidEncryptedString() throws Exception {
    simpleStringCipher.decrypt("abe6vPUFQ4xSMezuFF2HBNC3dW98jjfMeM027PKKnNw");
    }

    Sorry, I am beginner and new in Cipher.
    Hope my following question make more sense.
    In production we have an error when decrypting
    large data.
    My existing unit test is shown and class I am testing
    How can I write a new test, simulating the production error we have?
    1.@Test
    2.public void testBasicEncyption() throws Exception {
    3.String plainText = "text to be encrypted."
    4.String encrypted = simpleStringCipher.encrypt(plainText);
    5.System.out.println("Encrypted: " + encrypted);
    6.assertTrue(!plainText.equals(encrypted));
    7.String decrypted = simpleStringCipher.decrypt(encrypted);
    8.assertEquals(plainText, decrypted);
    * Class to test *
    package no.ssb.cipher;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    public class SimpleStringCipher {
    private static byte[] linebreak = {}; // Remove Base64 encoder default
    // linebreak
    private String secret; // secret key length must
    // be 16
    private SecretKey key;
    private Cipher cipher;
    private Base64 coder;
    public SimpleStringCipher(String secretKey) {
    if(secretKey.length()!=16){
    throw new IllegalArgumentException("secretKey must be 16 digits");
    this.secret = secretKey;
    try {
    key = new SecretKeySpec(secretKey.getBytes(), "AES");
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    coder = new Base64(32, linebreak, false);
    } catch (Throwable t) {
    t.printStackTrace();
    public synchronized String encrypt(String plainText)
    throws Exception {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(plainText.getBytes());
    return new String(coder.encode(cipherText));
    public synchronized String decrypt(String codedText)
    throws Exception {
    byte[] encypted = coder.decode(codedText.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encypted);
    return new String(decrypted);
    Edited by: 999969 on Apr 14, 2013 10:38 PM

  • Byte to String conversion for encryption and decryption

    Hi Friends ,
    I am trying to encrypt a password string and then decrypt it .
    The thing is i need to convert the encrypted String which is a byte array to a string . While decrypting i need to convert the encrypted string to a Byte .
    I tried using String.getBytes() for converting a string to byte array , but this is giving an exception
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipherPlease find below my code
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    * @author rajeshreddy
    public class Encrypt
        public static void main(String[] args)
            try
            BASE64Encoder en = new BASE64Encoder();
            BASE64Decoder en1 = new BASE64Decoder();
                String password = "S_@!et";
                KeyGenerator kg = KeyGenerator.getInstance("DESede");
                Key key = kg.generateKey();
                Cipher cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                // Encrypt password
                byte[] encrypted = cipher.doFinal(password.getBytes());
                String e = new String(encrypted);
                byte[] toDecrypt  = e.getBytes();
                // Create decryption cipher
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] decrypted = cipher.doFinal(toDecrypt);
                // Convert byte[] to String
                String decryptedString = new String(decrypted);
                System.out.println("password: " + password);
                System.out.println("encrypted: " + encrypted);
                System.out.println("decrypted: " + decryptedString);
            } catch (Exception ex)
                ex.printStackTrace();
    }I cab use sun.misc.BASE64Decoder and sun.misc.BASE64Encoder which avoids this error, but this packages are sun proprietery packages so there is a chance of removing these in future releases.
    Please suggest me the best way to tackle this

    1) The "Jakarta Commons Codec" project has Base64 and Hex encoders that are well tested and well regarded. Google is your friend.
    2) Since this is a new project, you should use AES rather than DESede.
    3) The defaults when generating the Cipher object using
    Cipher cipher = Cipher.getInstance("DESede");
                is for ECB block mode with PKCS5 padding. ECB is not a good block mode since it allows some limited forgery though splicing of ciphertext. Use one of the feedback modes such as CBC.
    4) Why are you encrypting passwords rather than just hashing them? While there are situations where encryption rather than hashing is required, it is not the norm and does normally require justification.
    5) Converting encrypted or hashed data to a String is not normally required. What are you doing with that requires this?
    Edited by: sabre150 on Dec 29, 2008 7:44 AM

  • String encryption problem

    Hallo,
    I need to encrypt password with MD5 algorithm. I'm using following method:
    public static byte[] encryptStr(byte[] chars){
    MessageDigest digest=null;
    try {
    digest = MessageDigest.getInstance("MD5");
    digest.reset();
    digest.update(chars);
    return digest.digest();
    } catch (NoSuchAlgorithmException ex) {
    Logger.getLogger(RzJUtils.class.getName()).log(Level.SEVERE, null, ex);
    return null;
    My application communicates with a servlet, so I have to send encrypted password to serwlet. But if I use the method in sending desktop application I get as encryption result following string: &#65533; &#65533;o,H&#65533;0&#65533;3&#65533;
    &#65533;
    If I use the same method serverside (in servlet) I get following string: — •o,H&#263;&#351;0&#272;3 
    Î
    I've tried with convertion between different charsets but without success. Why are the results different? Is there a way to get eqaul results in desktop application and in servlet?
    with regards
    Rafal Ziolkowski

    Of course, what you get isn't a String at all, it's a byte array. If you want to display it I suggest you do so in hex. You can do this easily enough with something like:
    private String toHex(byte[] bytes) {
       StringBuilder sb = new StringBuilder(bytes.length * 2);
       for (byte b : bytes)
            sb.append(String.format("%02x" b & 255);
       return sb,toString();
    }That gets rid of problems w.r.t character encoding (at least, of the digest).
    Incidentally it's confusing to call a digest "encryption".

  • Simple String Encryption

    HI,
    I have been serching around on here for encyption methods but there seems to be soo many i not sure which ones would be good for me.
    All i want to do is encypt and decrypt a String record. The encryption doesnt have to be particulary safe but must work for all possible charaters. Basically i am saving records to a text file and i dont want someone to be able to open the text file and read the contents.
    I would like to make it as simple as possible so i can just use it like:
    String record = "This is the record";
    // Encrypted Record
    String encRecord = Encryption.encrypt(record);
    // Decripted Record
    String decRecord = Encryption.decrypt(record);Can anyone stear me in the right direction or give me some sample code i can study.
    Thank you in advance
    ed

    Here is simple encryption routine that I just wrote that I bet would keep someone
    stumped for a while.
    * This is a simple encryption class that uses simple character substitution.
    * To keep the pattern from being obvious the shift factor is a function of the current character's
    * position in the source string. This makes sure that all letters aren't encrypted to the same value.
    * Usage: To encrypt a string just pass it to the encrypt method.
    *         String encryptedString = Encryptor.encrypt("Some string.");
    *        To decrypt a string just pass the encrypted string to the decrypt method.
    *         String decryptedString = Encryptor.decrypt(encryptedString);
    class Encryptor
      static final byte [] shiftFactor = {2,5,7,9,13,17,19};
      static final int modulo = shiftFactor.length;
      static public String encrypt(String s)
         char [] ba = s.toCharArray();
         for (int i = 0; i < ba.length; i++)
              ba[i] += shiftFactor[i%modulo];
        return new String(ba);
      static public String decrypt(String s)
         char [] ba = s.toCharArray();
         for (int i = 0; i < ba.length; i++)
              ba[i] -= shiftFactor[i%modulo];
         return new String(ba);
      public static void main(String [] args)
         String [] test = {"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz,./<>?;':\"[]{}-=_+!@#$%^&*()`~",
                           "Now is the time for all good men \n to come to the aid of their country."};
        for (int i = 0; i < test.length; i++)
              System.out.println(test);
              String encrypted = Encryptor.encrypt(test[i]);
              System.out.println(encrypted);
              System.out.println(Encryptor.decrypt(encrypted) + "\n");

  • Encrypting String with MD5, then storing as String

    Hello.
    I believe I have a way to do this but I want to verify that:
    1) It is doing the action that I want
    2) There is no easier/simpler way with less lines
    What I am looking to do is take a String that is passed to the method, encrypt it using MD5 algorithm, and then store the result back into String form.
    In the following code encyptedPassword is the String to-be encrypted and this.encryptedPassword is the String for where I would like to save the result.
    try
                MessageDigest md=MessageDigest.getInstance("MD5");
                md.reset();
                md.update(encryptedPassword.getBytes());
                byte raw[]=md.digest();
                for(int x=0; x<raw.length;x++)
                    this.encryptedPassword+=(char)raw[x];
            catch(NoSuchAlgorithmException e)
                e.printStackTrace();
            }

    You will have to hex-encode or base-64-encode the encrypted data. String is not a container for binary data, and encrypted data is binary data.

  • How Can i use the key file Generated by RSACryptoServiceProvider to encrypt with php?

    I need to be able to encrypt data in PHP using a public key generate by .NET(RSACryptoServiceProvider).  I will then decrypt the data later in C# using the private key.
    Code Snippet
    <RSAKeyValue><Modulus>xU5JyaPNDKXI/h/uo5Vk89wZSz3zsB1+c+1IMYIQa+mCmuRCRPuoBI7ODSV2ndP6grfhdrWEzhpZtkI3SThbBh/3t+tfZ2PF8Iyv9ECN07V64nPCiJGhAnfENE+J9UD9Kw5czXHgZcBbpM5N0VfXmLSleaS65DDoNPtoStVy7ss=</Modulus><Exponent>AQAB</Exponent><P>4ScAjVrPZii/6lICAP2yDQiNEmNL74+5AcxNVDI0IombfDPIygrqEWmuDu0pngApQak7XnEnLbaDChILFiHPZQ==</P><Q>4FaYlse+cjrlPD/jk+GsTJeuP7yuQx8ztjVnQWVh6GKQP+uk1dAl6kcZOfLNR6LWwE3CSygt8PthTEw96Zbabw==</Q><DP>XvXtNLE9UjATqYeHEtXtV7Pok/3PVC3A8PIzFzTJaluxeXP51sU9rbRt1hvO9rXIsMnooU+GH7Cfmgq8JEyERQ==</DP><DQ>HXkC/vwq9xLpvuqd2XXSjxV2XQVK16Knxo5pjFvnawJX9S3eMADymj7Q/534firUj9snZXxX3MsJ015I3AFnnQ==</DQ><InverseQ>AM0fVCE3n2FKf2zb3CcDEge1Ko35VvMEL+LXgR87QwO2HScZSuLevGLi2SSAkB1vu8RSNzB028SZReeOZWnq4Q==</InverseQ><D>fI+GKdRNOTTYhQZnw8Im74T+OvArjf2wvUMJlqfD8jyDBYIhDCfL1MTK9KW4Er+moSuxHR5Pb0ZXaKa4/HKlk0aJ1jB2C+jg7zTSuPRNuS16BpVHaJYsQurCwZwElXMum+GxeXK/h3wXWq5HwebjqZr0aLUMZKRcweDPRoVFiRE=</D></RSAKeyValue>
    As you see this code snippet is a xml format private key. at .net platform,which can use encrypt or dencrypt.
    i have try the Extension Crypt RSA ( http://pear.php.net/reference/Crypt_RSA-1.0.0/elementindex_Crypt_RSA.html ) to help me encrypt data by php.but it haven't return a currect result. the data encrypted by php cann't dencrypt by c#.
    does the RSA algorithm provider by Crypt_RSA can give a stand result as c#?
    BTW :i just use the xmlkeystring like this.
    Code Snippet
    <?php
    require_once("Crypt/RSA.php");
    require_once("includes/Utils.class.php");
        $public_key_string = simplexml_load_string("<RSAKeyValue><Modulus>xU5JyaPNDKXI/h/uo5Vk89wZSz3zsB1+c+1IMYIQa+mCmuRCRPuoBI7ODSV2ndP6grfhdrWEzhpZtkI3SThbBh/3t+tfZ2PF8Iyv9ECN07V64nPCiJGhAnfENE+J9UD9Kw5czXHgZcBbpM5N0VfXmLSleaS65DDoNPtoStVy7ss=</Modulus><Exponent>AQAB</Exponent><P>4ScAjVrPZii/6lICAP2yDQiNEmNL74+5AcxNVDI0IombfDPIygrqEWmuDu0pngApQak7XnEnLbaDChILFiHPZQ==</P><Q>4FaYlse+cjrlPD/jk+GsTJeuP7yuQx8ztjVnQWVh6GKQP+uk1dAl6kcZOfLNR6LWwE3CSygt8PthTEw96Zbabw==</Q><DP>XvXtNLE9UjATqYeHEtXtV7Pok/3PVC3A8PIzFzTJaluxeXP51sU9rbRt1hvO9rXIsMnooU+GH7Cfmgq8JEyERQ==</DP><DQ>HXkC/vwq9xLpvuqd2XXSjxV2XQVK16Knxo5pjFvnawJX9S3eMADymj7Q/534firUj9snZXxX3MsJ015I3AFnnQ==</DQ><InverseQ>AM0fVCE3n2FKf2zb3CcDEge1Ko35VvMEL+LXgR87QwO2HScZSuLevGLi2SSAkB1vu8RSNzB028SZReeOZWnq4Q==</InverseQ><D>fI+GKdRNOTTYhQZnw8Im74T+OvArjf2wvUMJlqfD8jyDBYIhDCfL1MTK9KW4Er+moSuxHR5Pb0ZXaKa4/HKlk0aJ1jB2C+jg7zTSuPRNuS16BpVHaJYsQurCwZwElXMum+GxeXK/h3wXWq5HwebjqZr0aLUMZKRcweDPRoVFiRE=</D></RSAKeyValue>");
        $key =new Crypt_RSA_Key(base64_decode($public_key_string->Modulus),base64_decode($public_key_string->Exponent),"public");
        echo "<pre>";
        print_r($key);
        echo "</pre>";
        $rsa_obj = new Crypt_RSA();
        //try encrypt data
        echo "encrypted result is:<br/>".$rsa_obj->encrypt("this is a smple text.",$key)
        ?>
    but the encrypted data cann't decrypt by c#?where is the problem?what should i do with php codes?

    thank you for your reply, i also found this article by google.but this does not meet scene,  thank you all the same.
    i have already solved the problem now,i'd like to post the Solution .infact it's so easy to use rsakey file generated by .net .
    -------------rsa.class.php-------------------
    Code Snippet
    <?php
     * Some constants
    define("BCCOMP_LARGER", 1);
    class RSA
      * PHP implementation of the RSA algorithm
      * (C) Copyright 2004 Edsko de Vries, Ireland
      * Licensed under the GNU Public License (GPL)
      * This implementation has been verified against [3]
      * (tested Java/PHP interoperability).
      * References:
      * [1] "Applied Cryptography", Bruce Schneier, John Wiley & Sons, 1996
      * [2] "Prime Number Hide-and-Seek", Brian Raiter, Muppetlabs (online)
      * [3] "The Bouncy Castle Crypto Package", Legion of the Bouncy Castle,
      *      (open source cryptography library for Java, online)
      * [4] "PKCS #1: RSA Encryption Standard", RSA Laboratories Technical Note,
      *      version 1.5, revised November 1, 1993
      * Functions that are meant to be used by the user of this PHP module.
      * Notes:
      * - $key and $modulus should be numbers in (decimal) string format
      * - $message is expected to be binary data
      * - $keylength should be a multiple of 8, and should be in bits
      * - For rsa_encrypt/rsa_sign, the length of $message should not exceed
      *   ($keylength / 8) - 11 (as mandated by [4]).
      * - rsa_encrypt and rsa_sign will automatically add padding to the message.
      *   For rsa_encrypt, this padding will consist of random values; for rsa_sign,
      *   padding will consist of the appropriate number of 0xFF values (see [4])
      * - rsa_decrypt and rsa_verify will automatically remove message padding.
      * - Blocks for decoding (rsa_decrypt, rsa_verify) should be exactly
      *   ($keylength / 8) bytes long.
      * - rsa_encrypt and rsa_verify expect a public key; rsa_decrypt and rsa_sign
      *   expect a private key.
      * rsa encrypt data
      * @param binary string $message
      * @param unknown_type $public_key
      * @param numbers $modulus
      * @param numbers $keylength
      * @return binary data
     function rsa_encrypt($message, $public_key, $modulus, $keylength)
      $padded = RSA::add_PKCS1_padding($message, true, $keylength / 8);
      $number = RSA::binary_to_number($padded);
      $encrypted = RSA::pow_mod($number, $public_key, $modulus);
      $result = RSA::number_to_binary($encrypted, $keylength / 8);
      return $result;
     function rsa_decrypt($message, $private_key, $modulus, $keylength)
      $number = RSA::binary_to_number($message);
      $decrypted = RSA::pow_mod($number, $private_key, $modulus);
      $result = RSA::number_to_binary($decrypted, $keylength / 8);
      return RSA::remove_PKCS1_padding($result, $keylength / 8);
     function rsa_sign($message, $private_key, $modulus, $keylength)
      $padded = RSA::add_PKCS1_padding($message, false, $keylength / 8);
      $number = RSA::binary_to_number($padded);
      $signed = RSA::pow_mod($number, $private_key, $modulus);
      $result = RSA::number_to_binary($signed, $keylength / 8);
      return $result;
     function rsa_verify($message, $public_key, $modulus, $keylength)
      return RSA::rsa_decrypt($message, $public_key, $modulus, $keylength);
     function rsa_kyp_verify($message, $public_key, $modulus, $keylength)
      $number = RSA::binary_to_number($message);
      $decrypted = RSA::pow_mod($number, $public_key, $modulus);
      $result = RSA::number_to_binary($decrypted, $keylength / 8);
      return RSA::remove_KYP_padding($result, $keylength / 8);
      * The actual implementation.
      * Requires BCMath support in PHP (compile with --enable-bcmath)
     // Calculate (p ^ q) mod r
     // We need some trickery to [2]:
     //   (a) Avoid calculating (p ^ q) before (p ^ q) mod r, because for typical RSA
     //       applications, (p ^ q) is going to be _WAY_ too large.
     //       (I mean, __WAY__ too large - won't fit in your computer's memory.)
     //   (b) Still be reasonably efficient.
     // We assume p, q and r are all positive, and that r is non-zero.
     // Note that the more simple algorithm of multiplying $p by itself $q times, and
     // applying "mod $r" at every step is also valid, but is O($q), whereas this
     // algorithm is O(log $q). Big difference.
     // As far as I can see, the algorithm I use is optimal; there is no redundancy
     // in the calculation of the partial results.
     function pow_mod($p, $q, $r)
      // Extract powers of 2 from $q
      $factors = array();
      $div = $q;
      $power_of_two = 0;
      while(bccomp($div, "0") == BCCOMP_LARGER)
       $rem = bcmod($div, 2);
       $div = bcdiv($div, 2);
       if($rem) array_push($factors, $power_of_two);
       $power_of_two++;
      // Calculate partial results for each factor, using each partial result as a
      // starting point for the next. This depends of the factors of two being
      // generated in increasing order.
      $partial_results = array();
      $part_res = $p;
      $idx = 0;
      foreach($factors as $factor)
       while($idx < $factor)
        $part_res = bcpow($part_res, "2");
        $part_res = bcmod($part_res, $r);
        $idx++;
       array_push($partial_results, $part_res);
      // Calculate final result
      $result = "1";
      foreach($partial_results as $part_res)
       $result = bcmul($result, $part_res);
       $result = bcmod($result, $r);
      return $result;
     // Function to add padding to a decrypted string
     // We need to know if this is a private or a public key operation [4]
     function add_PKCS1_padding($data, $isPublicKey, $blocksize)
      $pad_length = $blocksize - 3 - strlen($data);
      if($isPublicKey)
       $block_type = "\x02";
       $padding = "";
       for($i = 0; $i < $pad_length; $i++)
        $rnd = mt_rand(1, 255);
        $padding .= chr($rnd);
      else
       $block_type = "\x01";
       $padding = str_repeat("\xFF", $pad_length);
      return "\x00" . $block_type . $padding . "\x00" . $data;
     // Remove padding from a decrypted string
     // See [4] for more details.
     function remove_PKCS1_padding($data, $blocksize)
      assert(strlen($data) == $blocksize);
      $data = substr($data, 1);
      // We cannot deal with block type 0
      if($data{0} == '\0')
      die("Block type 0 not implemented.");
      // Then the block type must be 1 or 2
      assert(($data{0} == "\x01") || ($data{0} == "\x02"));
      // Remove the padding
      $offset = strpos($data, "\0", 1);
      return substr($data, $offset + 1);
     // Remove "kyp" padding
     // (Non standard)
     function remove_KYP_padding($data, $blocksize)
      assert(strlen($data) == $blocksize);
      $offset = strpos($data, "\0");
      return substr($data, 0, $offset);
     // Convert binary data to a decimal number
     function binary_to_number($data)
      $base = "256";
      $radix = "1";
      $result = "0";
      for($i = strlen($data) - 1; $i >= 0; $i--)
       $digit = ord($data{$i});
       $part_res = bcmul($digit, $radix);
       $result = bcadd($result, $part_res);
       $radix = bcmul($radix, $base);
      return $result;
     // Convert a number back into binary form
     function number_to_binary($number, $blocksize)
      $base = "256";
      $result = "";
      $div = $number;
      while($div > 0)
       $mod = bcmod($div, $base);
       $div = bcdiv($div, $base);
       $result = chr($mod) . $result;
      return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
    ?>
    -------------RSAProcessor.class.php------------------------
    Code Snippet
    <?php
    require_once("rsa.class.php");
    class RSAProcessor
     private $public_key = null;
     private $private_key = null;
     private $modulus = null;
     private $key_length = "1024";
     public function __construct($xmlRsakey=null,$type=null)
             $xmlObj = null;
       if($xmlRsakey==null)
               $xmlObj = simplexml_load_file("xmlfile/RSAKey.xml");
              elseif($type==RSAKeyType::XMLFile)
               $xmlObj = simplexml_load_file($xmlRsakey);
              else
               $xmlObj = simplexml_load_string($xmlRsakey);
             $this->modulus = RSA::binary_to_number(base64_decode($xmlObj->Modulus));
       $this->public_key = RSA::binary_to_number(base64_decode($xmlObj->Exponent));
       $this->key_length = strlen(base64_decode($xmlObj->Modulus))*8;
      * get public key
      * @return string public key
     public function getPublicKey()
      //return base64_encode(RSA::number_to_binary($this->public_key,($this->key_length)/8));
      return $this->public_key;
     public function getPrivateKey()
      //return base64_encode(RSA::number_to_binary($this->private_key,($this->key_length)/8));
      return $this->private_key;
     public function getKeyLength()
      return $this->key_length;
     public function getModulus()
      return $this->modulus;
      * encrypt data
      * @param string $data
      * @return base64 encoded  binary string
     public function encrypt($data)
      return base64_encode(RSA::rsa_encrypt($data,$this->public_key,$this->modulus,$this->key_length));
     public function dencrypt($data)
      return RSA::rsa_decrypt($data,$this->private_key,$this->modulus,$this->key_length);
     public function sign($data)
      return RSA::rsa_sign($data,$this->private_key,$this->modulus,$this->key_length);
     public function verify($data)
      return RSA::rsa_verify($data,$this->public_key,$this->modulus,$this->key_length);
    class RSAKeyType
     const XMLFile = 0;
     const XMLString = 1;
    ?>
    -------------- encrypt data with public key-----------------
    Code Snippet
    <?php
    require_once("RSAProcessor.class.php");
    $processor = new RSAProcessor
    ("<RSAKeyValue><Modulus>m6ljoeWhmnd0oRnsVEH5iNw3B8+vKVu7v7CVfMyf6bnKEzHa62TRmT/baJiSevoI/vgm2ph/s1JrQQTaGiErHicigwSC
    Aw7+i05WFbnz7tOyiiJJVMfsdd+v7Xan9Hiud05FzxoMbM8vpiMHPEIDbGJ1MiXyupTVkz2WcMHyBoJ4S189opktZ43pviUhy0PeuWkyoU7zR54akPmK
    Yg+z5Zr1r7K8lUZ1a3TThfJGxTQR/uZMtZz/q8QF0AANVQ/eyahTv9icBzBoDuncS0Y5l3vqogW1C/ltJvhJpvSn/OgjbRjuixCAptOUmRd13sDWU95/
    x0bMq+Lg68lj2OjJ1Q==</Modulus><Exponent>AQAB</Exponent><P>zfvdBsMLlmo+4PAUYLgSV2xyyVa7ZqFjkJaAE4EbYuH24EoZjrzeiJR++D
    FUT/GUhjfZ5eZ/5e29dXwk0sKUw6nHzBdBtOPp5fr4t5SKLEcWY+J+zLUSOlhG9NUkohFf6+Miy2Y7BLpXVrcl6UwXV0ak8KkTPB2l/aIMwYj5dgc=</
    P><Q>wXV0sA3nDzoSDQA/4QSu/WIlBhkA3jZ7K7G9Z9rpP1A0vH+bZeyCIyo52u8ahGuYbubaizF1XMp+Xv3Mh2KmRbt7+UptwEwbFAUiiad2a312mqm
    j7IJd7gRjGkyzKEm+6fpNeY3NFLNVNhccBqzhNkRoM22xnvQcImD10XVAakM=</Q><DP>wd1HdCLEWCfc0DYE59a2pINUMXyo2foRTDbpifHcRZ+ojAY
    Rsc6+nsssCQnccXVMNVqBgSgEvfGYe+eAfMBX5SN5APPuioJrVGF2DsoFlZC+WPoGH0JYSoNlHO8yEDrMDaXzzH2GFHgQ1XOAged0nFbHzB1FFjJNVL5
    cxRXWu6c=</DP><DQ>QDKuCk5SwubOXqoaiJ15RHRxPNjHRPZnYVSWOgSXKn9/QJ5H/0bA2NKGaHS4JAFgkEzjcRV0kNpRnUwztymxa6qPtWZRjWK0Ca
    y6jVuZHIqB9UkeMLoCWZ3zFSMmwNPYGuUJGLFJwPjR6iU5E64C/nMs8QQR0WHIhFAQwvVZ7uk=</DQ><InverseQ>JckMSlJR10VZdnp83VPjrZ/Z+63
    CGu3tWHm7f4DJ8IwjJWr8FlCpbSwiP6a4e9Upv6bUn/tOj2gY6MMq5G5yTKm2SCRvpUKRu4NCmWAt7vlFv0Z6pkXlTOpzvVjv3v16+dIZOA5Zn+v7+r1
    xbdYdH20KRAbiBO3MfQP7s+VJJvM=</InverseQ><D>W1xrBr2hQOj1wgxWAgoK7IHbprEFrK+TnWmGA46SGPsbmHJ9fAVbY6fwHg7Wgmk4WHXLUCeLY
    /Nu0eWIISfwh60Oe3ls2WC2k4qxyeSvQDBuLNb81U7WAUT9m9E1uK4QMCP3oxs1ybM80zTh7UMNgVK0WG+fbFUomVffcWTTqW+Fu12PEIO+UR/85oq+x
    qVlTzYAEzt1OE9IhkYiRzi99ePXeH2gFltzJ/fb/7jLsDTkhM2eiYTGyOTZmBnen6c6a8b9LFTY4Bc0bGpk5ezHkub6F8p2ZgL/JgIOJMyRZICjDjs+9
    k9PTmMTFsCF6xzHY15Fg25xIDYzIyx1rrRUjQ==</D></RSAKeyValue>",RSAKeyType::XMLString);
    $rs =  $processor->encrypt("Hello,It's Works.");
    echo $rs;
    ?>
    with the front codes.you can easy to encrypt data by public key generate by .net programe.

  • Help for a newbie on encryption/decryption

    I want to start with a text file.
    Read in a line of ascii characters, encrypt it using some algorithm and output it as a new set of ascii characters.
    What algorithm should I use?

    thanks a lot. I got the encryption/decryption working pretty easily.
    However, I ran into problem when I got to storing keys:
    I stored it fine with this code
              try {
                   KeyGenerator keyGen = KeyGenerator.getInstance("DES");
                   desKey = keyGen.generateKey();
                   cipher = Cipher.getInstance("DES");
                   KeyStore keyStore = KeyStore.getInstance("JKS");
                   String password = "lemein";
                   char passwd[] = password.toCharArray();
                   keyStore.load(null, passwd); //initialize keyStore
                   Certificate[] chain = new Certificate[1];
                   String alias = "test";
                   keyStore.setKeyEntry(alias, desKey, passwd, null);
                   String fileName = "data/gkey.txt";
                   FileOutputStream f = new FileOutputStream(fileName);
                   keyStore.store(f, passwd); // <----------exception happens here
              } catch (Exception e)
              {     e.printStackTrace();
    I got problem when I retrieve it with this code
              KeyGenerator kg = null;
              Key key = null;
              cipher = null;
              Security.addProvider(new com.sun.crypto.provider.SunJCE());
              byte[] result = null;
              try {
                   KeyStore keyStore = KeyStore.getInstance("JKS");
                   keyStore.load(new FileInputStream("data/gkey.txt"), "lemein".toCharArray());
                   key = keyStore.getKey("test", "lemein".toCharArray());
                   cipher = Cipher.getInstance("DES");
                   byte[] data = "Hello World!".getBytes();
                   System.out.println("Original data : " + new String(data));
                   cipher.init(Cipher.ENCRYPT_MODE, key);
                   result = cipher.doFinal(data);
                   System.out.println("Encrypted data: " + new String(result));
              } catch (Exception e) {
                   e.printStackTrace();
    I get the error:
    java.security.UnrecoverableKeyException: DerInputStream.getLength(): lengthTag=75, too big.
         at sun.security.provider.KeyProtector.recover(Unknown Source)
         at sun.security.provider.JavaKeyStore.engineGetKey(Unknown Source)
         at java.security.KeyStore.getKey(Unknown Source)
    Any idea what the problem is?
    Thanks

  • Encrypt/decrypt AES 256, vorsalt error

    Hiyas.
    So I'm trying to get encrypt/decrypt to work for AES 256, with both 32byte key and 32byte IVorSalt. (Yup-new java security files v6 installed)
    'IF' I 32byte key but dont use a IV at all, I get a nice looking AES 256 result. (I can tell it's AES 256 by looking the length of the encrypted string)
    'IF' I use a 32byte key and 16bit salt, I get a AES 128 result (I know- as per docs theyre both s'posed to the same size, but the docs are wrong).
    But when i switch to using both a 32byte key AND a 32byte salt I get the error below.
    An error occurred while trying to encrypt or decrypt your input string: Bad parameters: invalid IvParameterSpec: com.rsa.jsafe.crypto.JSAFE_IVException: Invalid IV length. Should be 16.
    Has anyone 'EVER' gotten encrypt to work for them using AES 256 32byte key and 32byte salt? Is this a bug in CF? Or Java? Or I am doing something wrong?
    <!--- ////////////////////////////////////////////////////////////////////////// Here's the Code ///////////////////////////////////////////////////////////////////////// --->
    <cfset theAlgorithm  = "Rijndael/CBC/PKCS5Padding" />
    <cfset gKey = "hzj+1o52d9N04JRsj3vTu09Q8jcX+fNmeyQZSDlZA5w="><!--- these 2 are the same --->
    <!---<cfset gKey = ToBase64(BinaryDecode("8738fed68e7677d374e0946c8f7bd3bb4f50f23717f9f3667b2419483959039c", "Hex"))>--->
    <cfset theIV    = BinaryDecode("7fe8585328e9ac7b7fe8585328e9ac7b7fe8585328e9ac7b7fe8585328e9ac7b","hex")>
    <!---<cfset theIV128    = BinaryDecode("7fe8585328e9ac7b7fe8585328e9ac7b","hex")>--->
    <cffunction    name="DoEncrypt" access="public" returntype="string" hint="Fires when the application is first created.">
        <cfargument    name="szToEncrypt" type="string" required="true"/>
        <cfset secretkey = gKey>               
        <cfset szReturn=encrypt(szToEncrypt, secretkey, theAlgorithm, "Base64", theIV)>
        <cfreturn szReturn>
    </cffunction>   
    <cffunction    name="DoDecrypt" access="public" returntype="string" hint="Fires when the application is first created.">
        <cfargument    name="szToDecrypt" type="string" required="true"/>
        <cfset secretkey = gKey>   
        <cfset szReturn=decrypt(szToDecrypt, secretkey, theAlgorithm, "Base64",theIV)>       
        <cfreturn szReturn>
    </cffunction>
    <cfset szStart = form["toencrypt"]>
    <cfset szStart = "Test me!">
    <cfset szEnc = DoEncrypt(szStart)>
    <cfset szDec = DoDecrypt(szEnc)>
    <cfoutput>#szEnc# #szDec#</cfoutput>

    Hi edevmachine,
    This Bouncy Castle Encryption CFC supports Rijndael w/ 256-bit block size. (big thanks to Jason here and all who helped w/ that, btw!)
    Example:
    <cfscript>
      BouncyCastleCFC = new path.to.BouncyCastle();
      string = "ColdFusion Rocks!"; 
      key = binaryEncode(binaryDecode(generateSecretKey("Rijndael", 256), "base64"), "hex");//the CFC takes hex'd key
      ivSalt = binaryEncode(binaryDecode(generateSecretKey("Rijndael", 256), "base64"), "hex");//the CFC takes hex'd ivSalt
      encrypted = BouncyCastleCFC.doEncrypt(string, key, ivSalt);
      writeOutput(BouncyCastleCFC.doDecrypt(encrypted, key, ivSalt));
    </cfscript>
    Related links for anyone interested in adding 256-bit block size Rijndael support into ColdFusion:
    - An explanation of how to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files into ColdFusion
    - An explanation of how to install the Bouncy Castle Crypto package into ColdFusion (near bottom, under the "Installing additional security providers" heading)
    - An explanation of how to connect the Bouncy Castle classes together
    - Bouncy Castle's doc for the Rijndael Engine
    And here is the full CFC as posted in the StackOverflow discussion:
    <cfcomponent displayname="Bounce Castle Encryption Component" hint="This provides bouncy castle encryption services" output="false">
    <cffunction name="createRijndaelBlockCipher" access="private">
        <cfargument name="key" type="string" required="true" >
        <cfargument name="ivSalt" type="string" required="true" >
        <cfargument name="bEncrypt" type="boolean" required="false" default="1">
        <cfargument name="blocksize" type="numeric" required="false" default=256>
        <cfscript>
        // Create a block cipher for Rijndael
        var cryptEngine = createObject("java", "org.bouncycastle.crypto.engines.RijndaelEngine").init(arguments.blocksize);
        // Create a Block Cipher in CBC mode
        var blockCipher = createObject("java", "org.bouncycastle.crypto.modes.CBCBlockCipher").init(cryptEngine);
        // Create Padding - Zero Byte Padding is apparently PHP compatible.
        var zbPadding = CreateObject('java', 'org.bouncycastle.crypto.paddings.ZeroBytePadding').init();
        // Create a JCE Cipher from the Block Cipher
        var cipher = createObject("java", "org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher").init(blockCipher,zbPadding);
        // Create the key params for the cipher    
        var binkey = binarydecode(arguments.key,"hex");
        var keyParams = createObject("java", "org.bouncycastle.crypto.params.KeyParameter").init(BinKey);
        var binIVSalt = Binarydecode(ivSalt,"hex");
        var ivParams = createObject("java", "org.bouncycastle.crypto.params.ParametersWithIV").init(keyParams, binIVSalt);
        cipher.init(javaCast("boolean",arguments.bEncrypt),ivParams);
        return cipher;
        </cfscript>
    </cffunction>
    <cffunction name="doEncrypt" access="public" returntype="string">
        <cfargument name="message" type="string" required="true">
        <cfargument name="key" type="string" required="true">
        <cfargument name="ivSalt" type="string" required="true">
        <cfscript>
        var cipher = createRijndaelBlockCipher(key=arguments.key,ivSalt=arguments.ivSalt);
        var byteMessage = arguments.message.getBytes();
        var outArray = getByteArray(cipher.getOutputSize(arrayLen(byteMessage)));
        var bufferLength = cipher.processBytes(byteMessage, 0, arrayLen(byteMessage), outArray, 0);
        var cipherText = cipher.doFinal(outArray,bufferLength);
        return toBase64(outArray);
        </cfscript>
    </cffunction>
    <cffunction name="doDecrypt" access="public" returntype="string">
        <cfargument name="message" type="string" required="true">
        <cfargument name="key" type="string" required="true">
        <cfargument name="ivSalt" type="string" required="true">
        <cfscript>
        var cipher = createRijndaelBlockCipher(key=arguments.key,ivSalt=arguments.ivSalt,bEncrypt=false);
        var byteMessage = toBinary(arguments.message);
        var outArray = getByteArray(cipher.getOutputSize(arrayLen(byteMessage)));
        var bufferLength = cipher.processBytes(byteMessage, 0, arrayLen(byteMessage), outArray, 0);
        var originalText = cipher.doFinal(outArray,bufferLength);
        return createObject("java", "java.lang.String").init(outArray);
        </cfscript>
    </cffunction>
    <cfscript>
    function getByteArray(someLength)
        byteClass = createObject("java", "java.lang.Byte").TYPE;
        return createObject("java","java.lang.reflect.Array").newInstance(byteClass, someLength);
    </cfscript>
    </cfcomponent>
    Thanks!,
    -Aaron

  • TRIPLEDES Encrypt/Decrypt in Oracle

    We are having issues in oracle encryption/decryption.
    In our web application,We receive a number as input from the user which is encrypted & encoded using DES3 in .NET.
    This encrypted value is stored in the oracle database. We need to decrypt it in oracle8.1.7 to get
    the original number entered by the user.
    We are using the following code and facing issues.
    declare
    decrypted_string VARCHAR2(2048);
    input_string VARCHAR2(2048);
    begin
    DBMS_OBFUSCATION_TOOLKIT.DES3Decrypt (input_string=> hextoraw('a403de8264ec0b60a09c6d115768aff0'),
    key_string=>hextoraw('6d6f68616d6d6164616c6c616d6261647368616831323334'),
    Decrypted_string=>decrypted_string);
    dbms_output.PUT_LINE('vr_decrypted is:' || decrypted_string);
    end;
    We have taken the string 'hello ho'.
    This text is encrypted and encode ni .NET in DES3 which is the input string 'a403de8264ec0b60a09c6d115768aff0'.
    and the key is the encoded format of the key used to encrypt the input string.
    we are not getting the decrypted value as expected. thats 'hello ho'

    If I understand what you are trying to accomplish correctly, a better approach might be to protect your data by encrypting the network traffic between the middle tier and the db.  This would ensure the entire sqlnet exchange has been protected and not just any one piece of data.  Once the data has been safely moved to the db tier, you can then use the DB Crypto package to encrypt any individual data you want stored in tables protected.  Doing it this way will prevent you from having extra Forms application code and prevent you from writing your own risky security routine in Java.
    Refer to the Oracle Net Services documentation for information on how to encrypt the net traffic between client and db. Remember that the "client" in this case is the middle tier Forms environment and not the end-user.  Here are some helpful references:
    http://docs.oracle.com/cd/B28359_01/network.111/b28530/toc.htm
    http://docs.oracle.com/cd/B28359_01/network.111/b28316/toc.htm

  • Encrypt / Decrypt in J2SE 1.3.1

    Hi,
    I need to encrypt / decrypt a string.
    For this, i use JCE (J2SE 1.4) (Cipher class)
    The problem it's, i have to use J2SE 1.3.1.
    I am looking for some class i can use for encrypt and decrypt a string.
    Do you know what class can i use for my goal ???
    Thanks so much ...
    Omar

    J2SE is Java 2 Standard Edition
    JRE is Java Runtime Environment (that is what the client has)
    JDK is Java Development Environment (it includes JRE plus the development tools)
    If you have J2SE 1.4 and need to make sure that your
    program will run with J2SE 1.3.1, you need to add the
    option "-target 1.3" to the compile command on the
    command line:
    #javac -target 1.3 MyClass.java
    This makes sure that the class file is compatible with
    J2SE 1.3. If your program uses the JCE, you need to
    make sure that the end user has the JCE installed,
    because it is not automatically included with J2SE
    1.3. This is not correct. "-target" option tells compiller to use features specific for the concrete targets. And the default target for javac from 1.4 actually "1.2" (it was "1.1" in 1.3 and befofe). This is from javac changes documentation from JSDK 1.4
    The javac byte-code compiler has a new -source option that enables support for compiling source code containing assertions. Also, default compilation is for -target 1.2. Previously, the default was 1.1. The compiler now correctly detects unreachable empty statements, as discussed in bug 4083890. Javac also recognizes the new -Xswitchcheck option that checks switch blocks for fall-through cases and provides a warning message for any that are found.
    So, to make shure if your app going to work on 1.3 you no need to recompile it but you have to run it in 1.3 JRE and see if it work or not. Because JCE (Java Cryptography Extention) wasn't included into JRE 1.3 you have to install it in there. I recommend to use BouncyCastle or Sun's reference implementation.
    Use the Cipher class, if your end user has the JCE
    installed, it will work all fine.
    If you wanted to you could also use BouncyCastle
    instead of JCE, but it is not necessary.BouncyCastle is cleanroom JCE implementation and JCE provider! It have much more algorithms implemented and they are faster comparing with Sun's JCE provider.

  • Error in running encryption/decryption using DES in Websphere Dev't Client

    Hello!
    I have a code used to encrypt / decrypt a string (password). I have already tested it using Netbeans and it is working. But when I tried to add the java code to an existing web project using Websphere Development Client,, javax.crypto.* is not recognized. Then I imported JCE.jar.
    The java code contains no errors then, but when I started to run the project, it gives an Error 500. And below is the Console's error message:
    E SRVE0026E: [Servlet Error]-[javax.crypto.spec.PBEKeySpec: method <init>&#40;[C[BI&#41;V not found]: java.lang.NoSuchMethodError: javax.crypto.spec.PBEKeySpec: method <init>([C[BI)V not found[/b]
    Have I missed something to add? Or other things that I should do upon importing this jar file?
    Please help.
    Advance thanks for your reply.
    misyel

    I dont know what version of Java that my Websphere's using. But I am very sure that it is outdated. I am using Websphere 5.0. For Netbeans, it is JDK1.5.
    I imported the JCE from JDK 1.5 on Websphere.
    I think the code works perfectly fine. Actually it was my friend's code for encryption but they are using Eclipse for development (almost the same from Websphere but somehow different from it.)
    My idea is that I cant match the versions of the jarfiles used in my project. As much as I wanted to change the imported jar files, I couldn't for when I replaced the existing jar files, more and more errors occur.
    can we have any alternative ways of importing the jar files? or is there any other code that might help that will not use the JCE.jar?
    I really appreciate your response. thanks
    misyel

Maybe you are looking for

  • Stock at a certain date.

    Hi, how can I find the quantity of stock at a certain date ? Yours truly

  • Same account different device but contacts don't s...

    Hi there i recently got skype on my laptop but before that i have been using my phone to skype. I have logged into skype with my account that I use on my phone but the contacts won't show up can I please get help please? that would be much appreciate

  • Conditional Pivots

    Dear all, I've got currently a quite tricky problem with a Pivot-Table. I'm using the Pivot on the basis of an Analysis Services Cube. My idea is to have 2 dimensions on the x-axis and a KPI on the y value. The trick is, that the dimension on the x-a

  • FI - How to reverse Park Invoice created by FV60 (No deletion, only reverse)

    Hello FI Guru, I'm a developper, not a functional For a client, I have created a tool to allow the Park Invoice for every invoices coming from vendor. For invoices without PO, the park invoice is created by transaction FV60, but some times the user h

  • HTTP and RFC Adapter are not Required Sender

    Hi All, I have one dought.... Why Plain HTTP and RFC Adapter are not Required Sender Communication Channel and Sender Agreements... I Know this two Adapter are in ABAP Stack.... Please clarify my dought... Regards