Encrypt / Decrypt text

I created MyClass having the capability update a database. A typical application call is like this.
MyClass newObj = new MyClass("uuuu", "pppp", otherparam );
i = newObj.update();
The first two parameters in the constructor are username and password. It is not good to have them in plain text. Please suggest what I can do in Java.
I am thinking .. if I keep a password key between a small group, and use that key to do encrption and decrption. Where is the resource that can help me?

>
This basic mechanics of this are very easy BUT where
do you store you encryption key?
Thank you so much for your interest and thank for your time too.
The key will be stored in the server for business application, certainly. For testing, it is in my own laptop. There is some but not a high risk of losing the database password unless a thief is a hacker (usually he is happy getting money by selling it). But we can change password.
For example, I have:
SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey();
byte[ ] keyArray = new byte[1000];
keyArray = key.getEncoded();
Now I think i know how to store the key ( for example, just hardcoded the value of byte[ ] during initialization )
But I couldn't finger out the method to convert a byte array back SpecialKey key for an application.
For example, the following Encrypter method requires a SecretKey as parameter. How could I make use of the byte[ ] value and convert it to SecretKey key?
DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
catch (javax.crypto.NoSuchPaddingException e) {
catch (java.security.NoSuchAlgorithmException e) {
catch (java.security.InvalidKeyException e) {
}

Similar Messages

  • Hi Freinds......How to Encrypt/Decrypt Text file in j2me

    Hello friendz.,,
    I m having problem with textfile exncryption decryption in j2me..
    Can abybode tell me how to encrypt/decrypt Text file using J2ME API's.......
    PLZ help me .......
    Thanx in advance
    regards,
    Parag

    http://www.mobilefish.com/developer/bouncycastle/bouncycastle.html
    http://www-128.ibm.com/developerworks/library/j-midpds.html

  • How to encrypt the text in password field in Oracle Forms version 6i

    Need help!
    How to encrypt the text in password field in Oracle Forms version 6i?
    one way is to change the settings in the property palette. Can somebody provide me some script to be run while the form is running which will enable the password to be encrypted?
    Thanks!

    Hello,
    Do you mean "hidden" (replaced with stars) or encrypted (that needs to be decrypted ?
    Francois

  • 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 a file

    I would like to encrypt/decrypt a binary file (not text based) in FLEX 3.4 (AIR). I went through the forum, but I did not found any samples on how to do this. Any idea or help is appreciated.
    Thanks in advanced.

    Take a look at Crypto or ASCrypt3
    http://code.google.com/p/as3crypto/
    http://ascrypt3.riaforge.org/index.cfm

  • 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

  • Very urgent!...regarding encryption/decryption

    I have an application developed in java (using JCE1.2.2) for encrypting
    a text file.Iam using Tripel DES algorithm for encryption.So,Using this application I get an encrypted file. Now I want to develop an application in C/C++ using which I can decrypt the java(jce) encrypted file.
    IS THIS POSSIBLE?
    If YES,Pls show me the path ...

    Yes it is.
    First, pick what crypto lib you're going to use in C/C++. Google will show you the way - I see a lot of folk using Cryptix or openSSL. Read its README/tutorial/code smaples.
    Second, figure out how you're going to share your 3DES key. Typically, the code that generates it, also exports it. Read up on Key.getEncoded(). Don't treat your key as if it were a String - it's not. It's a byte[]. Transfer between the two parties is dependent on your app. A shared file, a database, a Socket connection, or even built into the .class files are all options. Note that that last option isn't a very good one.
    Once both sides have the same key, there's only tweaking left. Make sure both sides are using the same Padding and Mode. It's always a good idea to fully specify your crypto, to make that explicit (e.g., instead of using "DESede" for your Cipher string, use "DESede/CBC/PKCS5Padding"). If you don't know what the defaults are on either side, be explicit in both places.
    A final note: if some of the above didn't make immediate sense to you, you need to do a little reading on how crypto works. Cutting and pasting poorly-understood crypto code into your app is a recipe for many frustrating hours at best, and a completely insecure app at worst. It's worth the investment of a little time to understand the subject.
    Good luck!
    Grant

  • Javax.crypto.BadPaddingException in DES encrypt/decrypt algorithm

    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.
    Here's the output -
    Plain Text :debayandas
    Cipher Text :Ɩ2&#65533;Ü°*Yð´4}&#65533;f¥
    Recovered Plain Text :javax.crypto.BadPaddingExceptionAnd here's the J2ME code -
    Declaration part:
    private boolean midletPaused = false;
            private static String algorithm = "DES";
         private static byte[] secretKey = {(byte) 0x2b, (byte) 0x7e, (byte) 0x15, (byte) 0x16,
                                                      (byte) 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6 };
         private static String secretKeyAlgorithm = "DES";
         private static byte[] iv = "DES".getBytes();
         private static byte[] plainText = null;
         private Key key = null;
         private static Cipher cipher = null;
         private static int ciphertextLength = 512;
            private static byte[] cipherText = new byte[ciphertextLength];
            private static int decryptedtextLength = 1024;
            private static byte[] decryptedText = new byte[decryptedtextLength];commandAction:
    public void commandAction(Command command, Displayable displayable) {                                              
            if (displayable == form) {                                          
                if (command == exitCommand) {                                        
                    exitMIDlet();                                          
                } else if (command == okCommand) {
                    plainText=textField.getString().getBytes();
                    encrypt();
                    decrypt();                                                        
        } Encrypt:
    public void encrypt()
                try
                    key = new SecretKeySpec(secretKey,0,secretKey.length,secretKeyAlgorithm);
              cipher = Cipher.getInstance(algorithm);
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    cipher.doFinal(plainText, 0, plainText.length, cipherText, 0);
              System.out.println("Plain Text :"+new String(plainText));
              System.out.println("Cipher Text :"+new String(cipherText));
                catch(Exception e)
                    System.out.println(""+e);
        }Decrypt:
    public void decrypt()
            try
    //            cipher = Cipher.getInstance(algorithm);
                cipher.init(Cipher.DECRYPT_MODE,key);
                cipher.doFinal(cipherText,0,cipherText.length,decryptedText,0);
                System.out.println("Recovered Plain Text :"+new String(decryptedText));
            catch(Exception e)
                System.out.println(""+e);
        }Where am I going wrong?

    debayandas wrote:
    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.How did you get DES in J2ME?
    I am asking as there isn't one default implementation in J2ME and as far as I am aware it is not included in any Configurations or Profiles of J2ME.
    You might be using [Bouncycastle library|http://www.bouncycastle.org/java.html] or any other third party implementation of DES, in which case please refer to the documentation of it to see in which methods throw BadPaddingException and in what circumstances, in order to pinpoint the problem.
    Daniel

  • Encrypt message text friendly

    I have a simple class to make encryption/decryption of string data using a cipher. However, when looking at the crypted text, it's all a bunch of cryptic characters:
    Original string: Hello World!
    Crypted string: ��?H?�s v���?
    The algortihm i'm using is DES provided by javax.crypto. I need to store this text in some email message or other text container and i have problem with certains characters that are not well understood on another machine.
    Is there a way to encrypt the string so that it is text friendly, i.e. that it use only letters and numbers to generate the crypted output?
    Something like the MIME format.

    Not much looked at the different algorithms, but to
    what i see they all crypt with blocks of bytes and
    don't matter in what range the generated bytes are. Cryptography converts streams of bits into other, essentially randomized, streams of bits. If your crypto is correct, there is no order or range-limitation on the ciphertext.
    There must be a way to filter the outputted bytes so
    that a call to encrypt with one of a such algorithm
    would produce the needed result.Nope - not unless your enciphering algorithm is awful.
    Another reason why i'm doing this is to pass encrypted
    portions of url into a browser without falling into
    illegal characters. I've implemented a way to do it by
    converting the generated bytes into hex characters.
    It's not much efficient, cause it takes 2 times the
    original length of the string, but it works fine for
    small strings.Base64 exists precisely to allow for the transfer of random binary data (like ciphertexts) through a text-only medium (like HTTP). The standard procedure is to encrypt- Base64encode - transport - receive - Base64decode - decrypt. Along the way, you can write out your Base64 data and read it, since by definition is consists only of readable characters.
    It will, as floersh notes, enlarge your data by 4/3s along the way.
    Good luck!
    Grant

  • Encryption/Decryption  failure for pdf and MSWord files

    Hi,
    Is there anybody to help me to find out what is wrong with my class (listing below)? I am sucessfuly using this class to encrypt and decrypt txt, html files but for unknown reasons I am unable to use it for e.g. pdf files. The encrypion somehow works but any atempt to decrypt is a failure.
    /* This class accepts an input file, encrypts/decrypts it using DES algorithm and
    writes the encrypted/decrypted output to an output file. DES is used in Cipher
    Block Chaining mode with PKCS5Padding padding scheme. Note that DES is a symmetric
    block cipher that uses 64-bit keys for encryption. A password of length no less
    than 8 is to be passed to the encryptFile/ decryptFile methods. This password is
    used to generate the encryption key. All exception handling is to be done by
    calling methods. These exceptions are thrown by encryptFile/ decryptFile methods.
    The input buffer is 64 bytes, 8 times the key size.
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.*;
    import java.security.spec.*;
    public class Crypto
    public Crypto(FileInputStream inStream_, FileOutputStream outStream_)
    fInputStream_ = inStream_;
    fOutputStream_ = outStream_;
    public void encryptFile(String password_) throws InvalidKeySpecException, InvalidKeyException,
    InvalidAlgorithmParameterException, IllegalStateException, IOException, Exception
    DataOutputStream dataOutStream_ = new DataOutputStream(fOutputStream_);
    // key generation
    SecretKey encryptKey_ = createEncryptionKey(password_);
    // Cipher initialization
    Cipher cipher_= Cipher.getInstance(cipherType);
    cipher_.init(Cipher.ENCRYPT_MODE, encryptKey_);
    // write initialization vector to output
    byte[] initializationVector_ = cipher_.getIV();
    dataOutStream_.writeInt(initializationVector_.length);
    dataOutStream_.write(initializationVector_);
    // start reading from input and writing encrypted data to output
    while (true) {
    inputLength_ = fInputStream_.read(input_);
    if (inputLength_ ==-1) break;
    byte[] output_ = cipher_.update(input_, inputOffset_, inputLength_);
    if (output_ != null)
    dataOutStream_.write(output_);
    // finalize encryption and wrap up
    byte[] output_ = cipher_.doFinal();
    if (output_ != null)
    dataOutStream_.write(output_);
    fInputStream_.close();
    dataOutStream_.flush();
    dataOutStream_.close();
    public void decryptFile(String password_) throws IllegalStateException, IOException, Exception
    DataInputStream dataInStream_ = new DataInputStream(fInputStream_);
    // key generation
    SecretKey encryptKey_ = createEncryptionKey(password_);
    // read initialization vector from input
    int ivSize_ = dataInStream_.readInt();
    byte[] initializationVector_ = new byte[ivSize_];
    dataInStream_.readFully(initializationVector_);
    IvParameterSpec ivParamSpec_= new IvParameterSpec(initializationVector_);
    // Cipher initialization
    Cipher cipher_= Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher_.init(Cipher.DECRYPT_MODE, encryptKey_, ivParamSpec_);
    // start reading from input and writing decrypted data to output
    while (true) {
    inputLength_ = fInputStream_.read(input_);
    if (inputLength_ ==-1) break;
    byte[] output_ = cipher_.update(input_, inputOffset_, inputLength_);
    if (output_ != null)
    fOutputStream_.write(output_);
    // finalize decryption and wrap up
    byte[] output_ = cipher_.doFinal();
    if (output_ != null)
    fOutputStream_.write(output_);
    fInputStream_.close();
    fOutputStream_.flush();
    fOutputStream_.close();
    // the following method creates the encryption key using the supplied password
    private SecretKey createEncryptionKey(String passwd_) throws InvalidKeySpecException,
    InvalidKeyException, NoSuchAlgorithmException
    byte[] encryptionKeyData_ = passwd_.getBytes();
    DESKeySpec encryptionKeySpec_ = new DESKeySpec(encryptionKeyData_);
    SecretKeyFactory keyFactory_ = SecretKeyFactory.getInstance(algorithm_);
    SecretKey encryptionKey_ = keyFactory_.generateSecret(encryptionKeySpec_);
    return encryptionKey_;
    private FileInputStream fInputStream_;
    private FileOutputStream fOutputStream_;
    private final String algorithm_= "DES";
    private final String cipherType= "DES/CBC/PKCS5Padding";
    private byte[] input_ = new byte[64]; // The input buffer size is 64
    private int inputLength_;
    private final int inputOffset_= 0;
    }

    Please can u give me refined code for me///
    at [email protected]
    Hi,
    I found at least one thing wrong. In the decrypt
    method you are reading from 'fInputStream_' rather
    than 'dataInStream'.
    Worked for me on MSWord after changing this!
    Roger
    // start reading from input and writing decrypted
    ted data to output
    while (true) {
    inputLength_ = fInputStream_.read(input_);
    if (inputLength_ ==-1) break;
    byte[] output_ = cipher_.update(input_,
    input_, inputOffset_, inputLength_);
    if (output_ != null)
    fOutputStream_.write(output_);

  • How to resolve bug RC4 encrypt-decrypt on iPAD with AIR15 only

    Hi everybody,
    I have some trouble with AIR15 only, In the past, I created a small game on iPad It could send or receive messge from server. I used lib as3crypto.swc encrypt or decrypt message (RC4). But when I upgrade to AIR15 encrypt-decrypt cannot work ( Another thing about this crash is that it only happens with a release (adhoc or appstore) build but NOT with a debug build). I check so many time but i don't know what is problem here.
    Please help me, thanks so much any advice.
    P/S: My game have many swf files (code and resource). I must combine multiple SWF files into one.
    Class RC4.as
    import com.hurlant.crypto.prng.ARC4;
    import com.hurlant.util.Base64;
    import com.hurlant.util.Hex;
    import flash.utils.ByteArray;
    public class RC4
      private static const key:String = "keytest";
      private static var byteKeys:ByteArray = Hex.toArray(Hex.fromString(key));
      private static var rc4:ARC4 = new ARC4();
      public static function encrypt(clearText:String):String
      var byteText:ByteArray = Hex.toArray(Hex.fromString(clearText));
      rc4.init(byteKeys);
      rc4.encrypt(byteText);
      return Base64.encodeByteArray(byteText);
    public static function decrypt(encryptedText:String):String
      var byteText:ByteArray = Base64.decodeToByteArray(encryptedText);
      rc4.init(byteKeys);
      rc4.decrypt(byteText);
      return Hex.toString(Hex.fromArray(byteText));

    Sorry, exact message is "this movie could not be played".
    There are hundreds of posts about this message but no one states a clear solution to the problem.
    Your help will be much appreciated.
    Thank you.

  • Help ! Need PCI Encryption/Decryption Controller Driver for New HP 355 G2 (AMD) w/Win 7 Pro 64 Bit

    Just rebuilt new HP 355 G2 to Win 7 64 bit.  The ONLY driver I can not locate or get to work is the PCI Encryption/Decryption Controller. I installed all latest drivers for this model/OS from both HP and AMD sites still no luck. AMD autodetect utility and Catalyst software installed all other drivers successfully except this one and when completes says all drivers, including chipset, are installed successfully and current.
    I am at a complete loss where to get this driver from a OEM site, can you help ?
    Device ID's:
    PCI\VEN_1022&DEV_1537&SUBSYS_15371022&REV_00
    PCI\VEN_1022&DEV_1537&SUBSYS_15371022
    PCI\VEN_1022&DEV_1537&CC_108000
    PCI\VEN_1022&DEV_1537&CC_1080
    Thanks !!!
    This question was solved.
    View Solution.

    Hi:
    You need to run this driver and then manually install it.
    http://h20565.www2.hp.com/hpsc/swd/public/detail?swItemId=vc_133833_1
    To manually install the driver go to the device manager and click on the PCI Encryption/Decryption Controller needing the driver.
    Click on the driver tab.  Click on Update Driver.
    Select the Browse my computer for driver software option, and browse to the driver folder that was created when you ran the file.
    That folder will be located in C:\SWSetup\sp66974.
    Make sure the Include Subfolders box is checked, and the driver should install.
    Then reboot.

  • Encrypt/decrypt using update

    Hi,
    can someone give me an encrypt/decrypt pair of code samples that use the cipher.update() call.
    i am trying it like that but apparently it doesn't work
    byte[] temp = new byte[message.length/2];
    byte[] temp2 = new byte[message.length/2];
    System.arraycopy(message, 0, temp, 0, temp.length);
    System.arraycopy(message, temp.length, temp2, 0, temp.length);
    ciphertext = new byte[message.length];
    System.arraycopy(symmetricCipher.update(temp), 0, ciphertext, 0, temp.length);
    System.arraycopy(symmetricCipher.doFinal(temp2), 0, ciphertext, temp.length, temp.length);

    ode]
    >
    I don't see how using the inputstream i would avoid
    the memory error, when passing anything over
    10,000,000. Unless you mean I split the input, and
    write small chunks into disk as I encrypt them?Your basic problem is that you have the data as one large array. I don't know how and why you created this large array; I would not to create it unless there was no other way.
    Since it does not make sense to create one large encrypted byte array and given that you have a byte array then you can use either
    1) Create a ByteArrayInputStream and wrap it in a CipherinputStream. This would allow you to encrypt the array in a sequential manner a few KBytes at a time.
    or
    2) Encrypt the array a few KBytes at a time using a simple update(array, start, length) that returns the encrypted bytes.
    But first, I would try to avoid creating the large 'cleartext' array.

  • 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

  • Encrypt / Decrypt password

    Hi
    I'm new in Java and I need to create a function to encrypt / decrypt passwords using the Blowfish algorithm. I know how to create a key, but I don't know how to recover it to decrypt the password.
    Another question, Is it possible to use public/private keys in this case???.
    Can you give some links or examples please???
    Regards
    J.C.

    This is typically done either one of two ways:
    1) PBE based encryption. This uses a password or pass phrase to derive
    a key to use with a symmetric algorithm.
    2) Asymmetric using something like RSA. Typically RSA is used to wrap
    the actual symmetric key used to do the encryption but for very short
    plaintext it can be used directly on the plaintext. Passwords are a
    good example of short plaintext.
    Obviously symmetric encryption is a great deal faster than asymmetric
    encryption. So if your plaintext was large you would want to use
    symmetric. Also Asymmetric encryption is length dependant. AKA if your
    public key's modulus is 1024 bits then you could encrypt any plaintext
    that was 121 bytes or shorter.
    PBE takes a salt (a random byte array) and an iteration count and
    hashes a passphrase with the salt iteration number of times to generate
    a key that can be reproduced over and over again and used with a
    symmetric algorithm. The issue here is that your salt/ic either need
    to be hard coded and reused or the values for any single encryption
    need to be saved along with the ciphertext. Using the same ic/salt for
    a large number of plaintext to ciphertext operations can lead to a
    weakening of the pass phrase (aka the key) and aids a cryptoanalyst in
    breaking the code. Although it is still difficult it becomes easier
    with each successive encryption.
    Its upto you which route you take but you should note that private keys
    used in asymmetric encryption use PBE to keep them private anyway so in
    a sense if you use asymmetric encryption you are really using both
    asymmetric encryption and PBE...

Maybe you are looking for