Encrypt & Decrypt with DESede

Hi all!
please help me.
When I encrypt with DESede and write to file, but that file was cut comparing the first file which wasn't encrypt. I don't understand, help me.
//Read key from file
ObjectInputStream inKey = new ObjectInputStream(new FileInputStream("c:/security/key/3desKey.key"));
Key key = (Key)inKey.readObject();
//Encrypt
Cipher cipher3DES = Cipher.getInstance("DESede");
cipher3DES.init(Cipher.ENCRYPT_MODE,key);
FileInputStream fis = new FileInputStream(pathData);
CipherInputStream encryptData = new CipherInputStream(fis,cipher3DES);
//Write to file
FileOutputStream fos = new FileOutputStream("c:/security/dataOut/encrypt3DESdata.en");
byte[] buffer = new byte[2048];
int i ;
while((i=encryptData.read(buffer))!=-1){
fos.write(buffer,0,i);
i = encryptData.read(buffer);
fos.flush();
//Check capacity of file was encrypted.
FileInputStream fisTest = new FileInputStream("c:/security/dataOut/encrypt3DESdata.en");
System.out.println(fisTest.available()); //It was limited !!!
fos.close();
System.out.println("Write data which is encrypted success !");

Sorry, I have solved this problem, Thank you.

Similar Messages

  • Encrypt/decrypt with des_cbc

    Hi:
    I have source code in c which can do encrypt and descrypt with des_cbc, now I want to implement the
    java version with javax.crypto.*, but it tells java.security.InvalidKeyException
    can anyone find the error for me?
    I think the problem is at Cipher.getInstance(...), ...
    java code: suppose the String data contains the encypted string.
    /* get key factory */
    keyFactory=KeyFactory.getInstance("RSA","SunRsaSign");
    //cipher=Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher=Cipher.getInstance("DES/CBC/NoPadding");
    System.out.println("get cipher");
    /* get private key */
    FileInputStream keyfis=new FileInputStream("/home/roger/private.der");
    byte[] encKey=new byte[keyfis.available()];
    keyfis.read(encKey);
    keyfis.close();
    PKCS8EncodedKeySpec privKeySpec=new PKCS8EncodedKeySpec(encKey);
    prvKey=keyFactory.generatePrivate(privKeySpec);
    cipher.init(Cipher.DECRYPT_MODE, prvKey);
    System.out.println("cipher inited");
    byte[] recoveredtext = cipher.doFinal(data.getBytes());
    return new String(recoveredtext );
    the src to generate key:
    #!/bin/sh
    if [ "$1" = "" ]; then
    openssl genrsa -out temp.pem;
    else
    openssl genrsa -out temp.pem -rand $1 $2;
    fi
    openssl pkcs8 -topk8 -inform PEM -outform PEM -in temp.pem -out private.pem -v2 des3
    openssl pkcs8 -topk8 -inform PEM -outform DER -in temp.pem -out private.der -nocrypt
    openssl rsa -inform PEM -in temp.pem -outform PEM -out public.pem -pubout
    openssl rsa -inform PEM -pubin -in public.pem -outform DER -out public.der
    rm temp.pem

    the script above generated keys (private.der and public.der) can really be used to do Signature.sign()
    and veirfy(), which can get from file like this
    /* get private key */
    FileInputStream keyfis=new FileInputStream("/home/roger/ssdk/private.der");
    byte[] encKey=new byte[keyfis.available()];
    keyfis.read(encKey);
    keyfis.close();
    PKCS8EncodedKeySpec privKeySpec=new PKCS8EncodedKeySpec(encKey);
    prvKey=keyFactory.generatePrivate(privKeySpec);
    /* get public key */
    keyfis=new FileInputStream("/home/roger/ssdk/public.der");
    encKey=new byte[keyfis.available()];
    keyfis.read(encKey);
    keyfis.close();
    X509EncodedKeySpec pubKeySpec=new X509EncodedKeySpec(encKey);
    pubKey=keyFactory.generatePublic(pubKeySpec);
    then be used like this:
    sig.initVerify(pubKey);
    sig.update(data.getBytes());
    byte[] signature=HexToBytes(sigHex);
    return signature==null ? false : sig.verify(signature);
    of do sign()
    but when used to do encrypt / decrypt, as I quoted above, it can not pass the cipher.init(...) with InValidKeyException
    Can anyone throw a light ?
    does it because the key is not a sunJCE provided format? (cause it is ssl)
    great thanks

  • Socket DESede encrypt/decrypt

    I have set up a class that contains methods to enrypt and decrypt a byte[] with DESede. This works great. I then created a socket client/server and sent this encypted byte array over the net. I get this error:
    javax.crypto.BadPaddingException: Given final block not properly padded
    When I go to decrypt ont he other side. despite the length of the two byte[]'s being the same.
    Any ideas anyone ??

    Yes it does at that. I currently use that.
    Here is the code I have for creating the key:
    public void createKey(){
    if( dezKey == null ) {
    try {
         Security.addProvider(new                          com.sun.crypto.provider.SunJCE());
         KeyGenerator keygen =                          KeyGenerator.getInstance("DESede");          
         dezKey = keygen.generateKey();
         cyphr =                                    Cipher.getInstance("DESede/ECB/PKCS5Padding");
    catch( Exception e ) {
         System.out.println("There is and error intializing the                     provider and cypher");
         e.printStackTrace();
    }//End if
    }//End public void createKey()     
    I have standard encrypt and decrypt methods that are will take either a byte[] or string nad successfully enrypt or decrypt. The problem arrises when i send the message of over the net to decrypt. Both sides use a key generated and saved in a third location.
    Any ideas anyone??

  • 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.

  • Encrypt/decrypt same file with two different passwords

    Hi everyone:
    I'm quite new to Java and cryptography in general and have a theoretical question. Is the following scenario possible and how would it be implemented:
    Two users with two passwords (say, a regular user and a superuser) encrypt, decrypt, read from and write to the same file. The secret key for encryption and decryption should be based on their passwords (generated from their passwords), i.e. not stored anywhere on the system.
    I've been racking my brains but can't think of a way. Am I missing an obvious solution?
    Can it be done?
    Thanks,
    Michael

    I don't think you can avoid having more than just a password hash stored on the system. Using a combination of my approach and Jeff's approach I can implement this as long as you allow a password protected key store to be stored on each system. A given user's key store would contain his RSA private key and associated public key together with the admin user's RSA certificate (thought the admin user's public key could be stored in the program since it does not have to be kept private). The admin user's key store would contain only his RSA private and public keys.
    Assume that the data file is to be create by a standard non-admin user. His code performs the following actions -
    1) Generates a random symmetric algorithm key. Say a 128 bit AES key.
    2) He write a digest of this to the output file.
    3) He writes the random key encrypted with his public key to the file.
    4) He writes his public key (or certificate) to the file.
    5) He writes the random key encrypted with the admin users public key to the file.
    6) He encrypts the data using the random key writes the result to the file.
    This user can then update the file by
    1) reading from the file the digest of the random key.
    2) reading the random key encrypted with his public key.
    3) Decrypting this encrypted random key using his private key extracted from his keystore.
    4) Check the digest of this key to make sure he has the correct random key.
    5) skipping his certificate and the random key encrypted using the admin user's public key.
    5) Decrypting the data using the random key.
    6) Update the data.
    7) Re-encrypt the file as described in the first part using a new random key.
    The admin user can
    1) read from the file the digest of the random key.
    2) skip the random key encrypted using the user's public key.
    3) reading the user's public key from the file (for use later if the file needs to be updated).
    4) read the random key encrypted using the admin's public key.
    5) decrypting the random key using the admin's private key obtained from his key store.
    6) check the digest of the random key to make sure it is correct.
    7) decrypt the the data.
    The admin can edit the data since he can re-encrypt the data in a similar manner to the way it was created in the first place.

  • Encrypt/decrypt streams with same password

    Hi all!
    I'would like to know if I can encrypt/decrypt streams using key's which are hardwired in my application. By a hardwired key I understand a key which is generated using the same seed; practically I don't keep the key, but the minimum info to regenerate it.
    Is this possible and if yes, how? Where can I find some more info about regenerating a key?
    Stefan.
    PS: I'm a newbie in field of cryptography, so...

    You can use password-based encryption. See an example
    of such a thing in:
    http://javaalmanac.com/egs/javax.crypto/PassKey.html
    Erm, what sort of encryption isn't password-based ?

  • 3DES decryption with SHA1 hashed key

    Hello all,
    I've been given the task of rewriting an existing VB application in Java, and one routine makes use of the Microsoft Cryptography API.
    The VB code decrypts a string using TripleDES decryption, using a string key that's been hashed with a SHA1 has algorithm.
    Most of the java DESede encryption/decryption examples I've worked through generate keys with a KeyGenerator instance, but I have not yet found any examples that use a key that's been SHA1 hashed.
    My attempts at using a hashed byte[] array of my key phrase with a DESede Crypto instance always return a "wrong key size" error.
    Can anyone provide some help? Example code fragments or anything would help.

    Thanks for the reply, and you're right in that this might be a more appropriate question to ask on a VB forum or on a MS cryptography API forum.
    Nevertheless, I've been able to make some headway on the VB side by getting the bytes of the SHA-1 hash map through some API calls.
    The hex representation of the SHA-1 hashed keyword:
    "3EC10CE885353DCD23B912860C2B91885CD3D6D1"
    A keyword to use as a test:
    "logins"
    Hex representation of the 3DES encrypted result of "logins" using the hashed keyword:
    "FB158A921E3C4CDB"
    Currently, my problem is with the length of the key. As you pointed out, SHA is 20 bytes, while 3DES is looking for 24 bytes. I'll experiment with your suggested 2-key approach, but here's my test code at the moment:
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.Cipher;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.spec.SecretKeySpec;
    public class EncryptionTest {
    public static void main(String[] args) {
    String hashedKey = "3EC10CE885353DCD23B912860C2B91885CD3D6D1";
    String textToCode = "logins";
    byte[] keyBytes = hexStringToBytes( hashedKey );
    byte[] source = textToCode.getBytes();
    SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    try {
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] result = cipher.doFinal(source);
    String sresult = hex( result );
    System.out.println( result );
    } catch ( NoSuchPaddingException e ) {
    e.printStackTrace();
    } catch ( BadPaddingException e ) { 
    e.printStackTrace();
    } catch ( NoSuchAlgorithmException e ) {
    e.printStackTrace();
    } catch ( InvalidKeyException e ) {
    e.printStackTrace();
    } catch (IllegalBlockSizeException e ) {
    e.printStackTrace();
    static byte[] hexStringToBytes( String s ) {
    int iLength = s.length();
    int iBuff = iLength / 2;
    byte[] buff = new byte[ iBuff ];
    int j = 0;
    for(int i = 0; i < iLength; i+=2) {
    try {
    String s1 = s.substring(i, i+2);
    buff[j++] = (byte) Integer.parseInt(s1, 16);
    } catch ( Exception e ) {
    e.printStackTrace();
    return buff;
    static String hex(byte[] data) {
    StringBuilder sb = new StringBuilder();
    for (byte b : data) {
    sb.append(Character.forDigit((b & 240) >> 4, 16));
    sb.append(Character.forDigit((b & 15), 16));
    return sb.toString();
    }

  • 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_);

  • 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

  • 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...

  • Encrypt/decrypt

    Hello!
    I have been trying to use this syntax for encrypting/decrypting BUT I get different values all the time even if I use the same String. I would be really glad if anyone could help me to tell me why. What I want to use this encrypt/decrypt/ is to make some info unreadable in my database but I want to be able to decrypt the info.
    -----------------------------syntax----------------------------------------------------------------------
    SecretKey key=null;
    try{
    key = KeyGenerator.getInstance("DES").generateKey();
    }catch(Exception e){}
    DesEncrypter d= new DesEncrypter(key);
    -----------------------------My cryptClass--------------------------------------------------------
    public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    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) {
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    thanks in advance!

    I don't understand caffeiene's answer but maybe it will help you. It seems to me that you need to encrypt and decrypt the same way across application sessions, etc. Therefore you will need to store your key outside of the application in a file on the server. So you'll have to use a key generator that will let you save the key to a file. That's about all the detail I can give you since I've never worked directly with cryptography. Obviously you'll need to make sure the server is behind a good firewall, or whatever other security measures you deem appropriate to protect the key. It seems unsecure, but you have to persist the key, because otherwise if the app server crashes then the data in the db will be inaccessible.

  • Encrypt/Decrypt data, multiple public keys using Bouncy castle api?

    Hi all.
    I need to implement encrypt/decrypt functionality of some data with many public keys using bouncy castle api and EnvelopedData class in java 1.4 SE.
    Could someone give me examples how to do it. I searched whole the internet and i could not find simple example.

    Hi thanks very much.
    I had a quick look at the examples. I will see if they could help me.
    Here is more specific what i want:
    Encrypt data with multiple public keys that are kept in .pkcs12 file.
    And decrypt the data using coresponding private key after that.
    I must use bouncy castle api for java 1.4 se.
    Best regards
    Edited by: menchev on Nov 13, 2008 8:26 AM

  • XML encrypt/decrypt

    Hi All,
    I'm a newbie, and want to know if the output XML file (UUT test report) from TestStand can be encrypted without using any third party software?
    Actually I want to know if TestStand itself supports encryption/decryption of XML?
    And if TestStand doesn't supports, is there any work around for this requirement?
    I am not allergic to Kudos, in fact I love Kudos.
     Make your LabVIEW experience more CONVENIENT.

    Hello,
    Encryption in XML file is required to encrypt the various configuration parameter values so that a user cannot view / edited it external outside the to the test application. By making use of Private / Public keys data would be encrypted.This key will be exchanged between TestStand & XML to decrypt & display it to user.
    See additional details on XML encryption on : http://www.w3.org/TR/xmlenc-core/
    We can encrypt the step result using LabVIEW encryption example --> http://zone.ni.com/devzone/cda/epd/p/id/3473
    My question now is --> How to include the customize XML report header to include the encryption standard?
    I saw many articles to make use of "ModifyReportHeader". Can someone furnish me with a working example of modifying the header through TestStand? I tried ... but in Vain..

  • Encrypt-Decrypt in XI

    Hi ,
       Can any one explain me how do u perform encryption decryption in XI
       with an example.
       I Just knw that it is possible through Java  mapping.
      but i dont knw how to do it. can any one send a sample code on
      [email protected]
       Is it possible through ABAP mapping ?
    Regards

    Hi
    Go through this
    http://help.sap.com/saphelp_nw04s/helpdata/en/4f/65c3b32107964996a56e4165077e24/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/a4/d0201854fb6a4cb9545892b49d4851/frameset.htm
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/55ba9790-0201-0010-aa98-ce8f51ea93cd
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b2e7020d-0d01-0010-269c-a98d3fb5d16c
    http://help.sap.com/saphelp_nw04s/helpdata/en/a8/882a40ce93185de10000000a1550b0/content.htm
    /people/sap.user72/blog/2005/06/16/using-digital-signatures-in-xi
    How to achieve encryption in XI
    Encryption in XI
    XI Encryption
    Thanks

Maybe you are looking for