AES encrypt/decrypt

Hi,
I need to encrypt a file in Java using AES, given an 'EncryptionKey'. The "EncryptionKey" will be given to me as a String. Later, the client needs to be able to decrypt it using the same "EncryptionKey", with ANY decryption tool.
I'm not sure how this can be done. The sample codes I saw online usually use a KeyGenerator to generate the Key. It seems like maybe I can use the "EncryptionKey" as a password, and use this password to generate a Key like this:
http://javaalmanac.com/egs/javax.crypto/PassKey.html
However, the link above uses DES. If I want to use AES, is it possible? Also, the client is not supposed to know anything about the salt and iteration count, all he knows is the "EncryptionKey".
Thanks a lot!

The use of 'any' decryption tool needs to be constrained to those tools that support not just the prime encryption algorithm but also the secondary algorithms.
The code fragment I posted explicitly used
a) 'AES' as the prime encryption algorithm,
b) 'CBC' as the block mode,
c) 'PKCS5Padding' to pad the data to an integral number of blocks
and it implicitly used a separate Key and IV. It is possible to use a random IV and to send the IV as a prefix to the encrypted data. It is normal then to use a random IV so that no two messages use the the same IV. You could of course take a pragmatic approach and just use a fixed IV!
The JCE gives you other encryption algorithms, other block modes and other padding modes and, since it is really a framework, it can be extended to add in further algorithms and processing.
Further processing not included in the JCE could be applied. For example, the resultant encrypted data could be 'armored' by using Base64 or HEX encoding and it may be compressed before encryption.
As you can see, the 'devil is in the detail' and YOU have to decide how the data will be processed and therefore what algorithms any decryption tool must support.
The JCE gives you a set of building block but there are more operations (such as Base64 encoding) that may be needed. Using the JCE together with some 3rd party tools will allow you to create an encryption procedure that another tool will be able to decrypt BUT the other tool will need to specify what operations it performs to decrypt the data. You will need to study the decryption tool's manual to decide what operations you need to perform when encrypting your data.
If you need more general information then, as a starting point, there is an electronic book at http://www.cacr.math.uwaterloo.ca/hac/ and of course there is the JCE specification.

Similar Messages

  • Persistent AES encryption decryption

    Hi
    I m using AES actually indirectly throuch the bouncycastle.org's jar files and I have a problem.
    The encryptiona and decryption works fine as long as the virtual machine is not shut down, but when the machine is started fresh then the decryption of strings doesnt return the same results.
    Now is there a way where i can make it persistent across machine shutdowns, because i have a customer DB and I want to kep the names (for ex.) consistent throughtout.
    Any sample code or alternative methods wud be highly appreciated

    Serialize the secret key to the filesystem after it is generated (this would best be done with a separate, small, standalone application). Somehow protect this key. One idea would be to have a password suplied at server startup. Use the password to create a PBE key that would decrypt the secret key. (The one disadvantage to this is that you will not be able to launch the server in a shell script without also storing the password, kind of defeating the point). Once the key is decrypted, read it in from your application for normal use.
    - Saish

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

  • AES Encryption for Windows Phone

    Hi,
    We are developing a windows phone app and the same app is also being developed in Android and IOS. All three platforms are using a JSON web service for data access. Parameters to be passed are encrypted using AES algorithm.
    The web service uses the Encryption and Decryption as shown in the following link : 
    https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged(v=vs.110).aspx
    The same is Encryption is available in IOS and Android and working fine.
    I am unable to achieve the same encryption in Windows Phone as System.Security.Cryptography is not available in Windows Phone. I did browse around and found a few alternatives as shown below but i am not getting the desired result i.e. Encrypted data is
    not the same and hence Decryption is not giving the same result in server side.
    public static byte[] Encrypt(string plainText, string pw, string salt)
    IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
    IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
    IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE);
    // Derive key material for password size 32 bytes for AES256 algorithm
    KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
    // using salt and 1000 iterations
    KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
    // create a key based on original key and derivation parmaters
    CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
    IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
    CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
    // derive buffer to be used for encryption salt from derived password key
    IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
    // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
    string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
    string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);
    SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
    // create symmetric key from derived password key
    CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
    // encrypt data buffer using symmetric key and derived salt material
    IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);
    byte[] result;
    CryptographicBuffer.CopyToByteArray(resultBuffer, out result);
    return result;
    public static string Decrypt(byte[] encryptedData, string pw, string salt)
    IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
    IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
    IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData);
    // Derive key material for password size 32 bytes for AES256 algorithm
    KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
    // using salt and 1000 iterations
    KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
    // create a key based on original key and derivation parmaters
    CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
    IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
    CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
    // derive buffer to be used for encryption salt from derived password key
    IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
    // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
    string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
    string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);
    SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
    // create symmetric key from derived password material
    CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
    // encrypt data buffer using symmetric key and derived salt material
    IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
    string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);
    return result;
    public static string AES_Encrypt(string input, string pass)
    SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
    CryptographicKey AES;
    HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
    CryptographicHash Hash_AES = HAP.CreateHash();
    string encrypted = "";
    try
    byte[] hash = new byte[32];
    Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
    byte[] temp;
    CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
    Array.Copy(temp, 0, hash, 0, 16);
    Array.Copy(temp, 0, hash, 15, 16);
    AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
    IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
    encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
    return encrypted;
    catch (Exception ex)
    return null;
    public static string AES_Decrypt(string input, string pass)
    SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
    CryptographicKey AES;
    HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
    CryptographicHash Hash_AES = HAP.CreateHash();
    string decrypted = "";
    try
    byte[] hash = new byte[32];
    Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
    byte[] temp;
    CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
    Array.Copy(temp, 0, hash, 0, 16);
    Array.Copy(temp, 0, hash, 15, 16);
    AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
    IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
    byte[] Decrypted;
    CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
    decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
    return decrypted;
    catch (Exception ex)
    return null;
    Both methods shown above are not giving the same result.
    I would require the following scenario :
    Plain Text : "login@123"
    Key : "0123456789abcdef"
    IV : "fedcba9876543210"
    Hex : 356F65678C82C137BDBB2A2C8F824A68
    Encrypted Text : 5oegåÇ¡7Ωª*,èÇJh
    Request you to please suggest alternative to obtain the same AES Encryption using a Key and IV in Windows Phone.
    Thanks in advance.
    Regards,
    Vinay D

    Hi,
    The encryption and decryption in : http://dotnetspeak.com/2011/11/encrypting-and-decrypting-data-in-winrt-2 is
    not giving me the desired result.
    I would require the following scenario :
    Plain Text : "login@123"
    Key : "0123456789abcdef"
    IV : "fedcba9876543210"
    Encrypted Text : 5oegåÇ¡7Ωª*,èÇJh
    But what i am getting from the above link is : 
    I would require the following scenario :
    Plain Text : "login@123"
    Key : "0123456789abcdef"
    IV : "fedcba9876543210"
    Encrypted Text : NW9lZ4yCwTe9uyosj4JKaA==
    As u can see the encrypted string is not the same and hence i would get a different decrypt string on the server.
    I cannot change the server as it is in production and working with Android and IOS.
    Regards,
    Vinay D

  • Crypt::cbc encrypt / decrypt using javax.crypto

    I am having a bit of a time encrypting with crypt::cbc and decrypting with java. To get to the point, here is my code, perl first, java 2nd - I have tried to keep things very simple.
    #!/usr/local/bin/perl -w
    use strict;
    use Crypt::CBC 2.30;
    die "Need to specify a file" if(!(my $infile = shift));
    my $key = q(nvA9s$233eOrlQG4);
    my $iv = q(0123456701234567);
    my $bufsize = 16384;
    my $cipher = Crypt::CBC->new({
              'key'          => $key,
              'iv'          => $iv,
              'header'     => 'none',
              'cipher'     => 'Rijndael',
              'keysize'     => '16',     #forced - default is 32 bytes
              'padding'     => 'standard',     #PKCS5
              'blocksize'     => '16',
              'literal_key'     => '1',          #do not MD5 hash key
    open (FORIG,"$infile")|| die "can't open file: $!";
    open (FCRYPT,">$infile.crypt")|| die "can't open file: $!";
    $cipher->start('encrypting');
    while(my $readsize = sysread(FORIG, my $buf, $bufsize)) {
         print FCRYPT $cipher->crypt($buf);
    print FCRYPT $cipher->finish();
    close FCRYPT;
    close FORIG;
    now the java:
    // i have elided the import stmts for brevity
    public class AESEncrypter {
         Cipher ecipher;
         Cipher dcipher;
         byte [] buf = new byte[1024];
         public AESEncrypter() {
              String strKey = "nvA9s$233eOrlQG4";
              byte[] keyBytes = null;
              try {
                   keyBytes = strKey.getBytes("UTF-8");
              } catch(java.io.UnsupportedEncodingException ex) {
                   ex.printStackTrace();
              byte[] iv = new byte[] { 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7 };
              IvParameterSpec ivSpec = new IvParameterSpec(iv);
              try {
                   ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                   dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
              } catch (NoSuchPaddingException e) {
                   e.printStackTrace();
              try {
                   SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
                   ecipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
                   dcipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
              } catch (InvalidKeyException e1) {
                   e1.printStackTrace();
              } catch (InvalidAlgorithmParameterException e1) {
                   e1.printStackTrace();
         public void encrypt(InputStream in, OutputStream out) {
              try {
                   out = new CipherOutputStream(out, ecipher);
                   int numRead = 0;
                   while((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                   out.close();
              } catch(java.io.IOException e) {
                   e.printStackTrace();
         public void decrypt(InputStream in, OutputStream out) {
              try {
                   out = new CipherOutputStream(out, dcipher);
                   int numRead = 0;
                   while((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                   out.close();
              } catch(java.io.IOException e) {
                   e.printStackTrace();
         public static void main(String args[]) {
              if(args.length != 1) {
                   System.out.println("Usage: java AESEncrypter filename");
                   System.exit(0);
              AESEncrypter encrypter = new AESEncrypter();
              try {
         //          encrypter.encrypt(new FileInputStream(args[0]), new FileOutputStream("Java_encrypted.txt"));
                   encrypter.decrypt(new FileInputStream(args[0]), new FileOutputStream("Java_decrypted.txt"));
              } catch (java.io.FileNotFoundException ex) {
                   ex.printStackTrace();
    so with file named whoop.txt containing the following contents:
    whoop
    whoop
    whoop
    whoop
    I do:
    $>./encrypt.pl whoop.txt
    and get the resulting file whoop.txt.crypt. then I do
    $>java AESEncrypter whoop.txt.crypt
    and get the resulting file Java_decrypted.txt. when I do a hex dump of this file:
    $>dump.pl Java_decrypted.txt
    i get the following
    /0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /A /B /C /D /E /F 0123456789ABCDEF
    0000 : 47 58 5F 5F 40 3A 47 58 5F 5F 40 3A 47 58 5F 5F GX__@:GX__@:GX__
    0010 : 70 0A 77 68 6F 6F 70 0A p.whoop.
    I have tried to ensure that everything matches between the perl and java code, however I am obviously missing something. Thanks in advance for any ideas!
    Gregg

    i have hardcoded the IV in perl as:
    my $iv = q(0123456701234567);
    and in the .java file as:
    byte[] iv = new byte[] { 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7 };
    IvParameterSpec ivSpec = new IvParameterSpec(iv)
    Are these not compatible?
    thanks - gh

  • AES Encryption example?

    I'm new to the cryptography area, so bear with me if I get things mixed up a bit.
    Here is what I need to do - using AES encryption.
    I have a stand-alone swing application that I need to encode certain sets of passwords and serial numbers.
    These will be stored in a database and compared against user input strings.
    Basically, I want to be able to store the key for the encryption in the program and use it for the encoding
    and decoding.
    I realize this is probably not the best way to handle this, but the security is not all that critical for this application.
    Basically we just don't want someone fetching the data from the database without having to use the application to decrypt it.
    I have seen several examples where a SecretKeySpec gets generated for each time the example is run,
    an example is http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
    but I have not been able to find anything where a "static" key is used for the encryption/decryption.
    Can someone help me out here?
    Thanks.

    From your usage description, there is no need to encrypt anything. Just store a hash (MD5, SHA-1, SHA256 etc) of the passwords and serial numbers. You then compare the hash of whatever the user enters with the hash stored in the DB.

  • AES Encryption - Encrypted value lengths

    HI all -
    I am attempting to use CF 8's AES encryption feature, and
    have not found a critical piece of info in the docs to enable me to
    progress.
    I am using the function to encrypt a password that can be
    from 6 to 16 characters long, which will be stored in a database. I
    am using generateSecretKey("AES"), and that gives me a 24 character
    key that I'm storing for future decryption use. I find that when I
    use the key to encrypt a 6 character password the resulting
    encrypted string is 32 characters long, but when I encrypt a 16
    character password I get a 64 character encrypted string. This is
    the case whether I specify "HEX" or "UU" as the encoding.
    Without knowing how the length of the resulting encoded
    string is determined, I cannot know how large to make my database
    column. (MySQL's AES encryption gives the formula 16 ×
    (trunc(string_length / 16) + 1) to arrive at the resulting string's
    length, but that formula doesn't yield the results I'm seeing in
    CFMX). Can anyone point me to a doc, or explain to me how to
    determine the column length for storing the resulting encrypted
    value?

    No. Only things like key, encoding and string size should
    matter. If the encoding is "hex", 1-15 characters should produce
    size 32, 16-31 characters should produce 64, etcetera. Unless space
    is at a premium, you could always increase the field size if that
    makes you feel more comfortable.
    Well, the results are dictated by the AES standard and basic
    string encoding rules, not CF. I highly doubt either one is going
    to change any time soon ;-) I agree documentation is good. However,
    unlike aes_encrypt, the encrypt function supports many different
    algorithms. Most of which have a distinct set of rules. So it would
    probably be difficult to provide accurate information about all of
    them. Especially as the specifications for each one alone probably
    spans volumes ;-)

  • I want to use my key that is a BigIntegar in aes encryption

    Random rand = new Random();
    BigInteger secretKey= new BigInteger(1024,3,rand) ;
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);

    The two methods that i used to create the secretkey are
    //that is member variables in the class server
    public SecretKey secretKey;
    public PublicKey publicKey;
    public KeyAgreement ka ;
    public static String genDhParams() {
    try {
    // Create the parameter generator for a 1024-bit DH key pair
    AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
    paramGen.init(1024);
    // Generate the parameters
    AlgorithmParameters params = paramGen.generateParameters();
    DHParameterSpec dhSpec
    = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
    // Return the three values in a string
    return ""+dhSpec.getP()+","+dhSpec.getG()+","+dhSpec.getL();
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidParameterSpecException e) {
    return null;
    The second method is:
    private void keyExchange()throws IOException
    setTextFieldEditable( true );
    // Retrieve the prime, base, and private value forgenerating the key pair.
    // If the values are encoded as in
    // Generating a Parameter Set for the Diffie-Hellman Key Agreement Algorithm,
    // the following code will extract the values
    String[] values = genDhParams().split(",");
    BigInteger p = new BigInteger(values[0]);
    BigInteger g = new BigInteger(values[1]);
    int l = Integer.parseInt(values[2]);
    try {
    // Use the values to generate a key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    DHParameterSpec dhSpec = new DHParameterSpec(p, g, l);
    keyGen.initialize(dhSpec);
    KeyPair keypair = keyGen.generateKeyPair();
    // Get the generated public and private keys
    PrivateKey privateKey = keypair.getPrivate();
    publicKey = keypair.getPublic();
    // Send the public key bytes to the other party..
    byte[] publicKeyBytes = publicKey.getEncoded();
    try // send publicKeyBytes to client
    output.writeObject( publicKeyBytes );
    output.flush(); // flush output to client
    } // end try
    catch ( IOException ioException )
    displayArea.append( "\nError writing object" );
    } // end catch
    // Retrieve the public key bytes of the other party
    try // read publicKeyBytes
    publicKeyBytes = (byte[]) input.readObject(); } // end try
    catch ( ClassNotFoundException classNotFoundException )
    displayMessage( "\nUnknown object type received" );
    } // end catch
    // Convert the public key bytes into a PublicKey object
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
    KeyFactory keyFact = KeyFactory.getInstance("DH");
    publicKey = keyFact.generatePublic(x509KeySpec);
    // Prepare to generate the secret key with the private key and public key of the other party
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(publicKey, true);
    // Generate the secret key
    secretKey = ka.generateSecret("AES");
    System.out.println("the secret key is"+ secretKey);
    // Use the secret key to encrypt/decrypt data;
    } catch (java.security.InvalidKeyException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } Thanks

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

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

  • Branch Office  - Not syncing with Mobile server

    Hi All, I have a strange problem with brach office installation , After downloading brachoffice set up on to my system from mobile server and completing set up .. I can see any tables . . is there any other steps I have to follow?

  • ODI topology connection error - oracle database

    Hi, I'm trying to connect to oracle database installed on a remote server through odi client installed on my windows machine. Oracle db is on RHEL 64 bit, I believe. I know the connection details such as hostname, sid etc but i'm not able to establis

  • Publishing via FTP server

    I have now shifted my webpages from Mobile Me to a local web hosting service, and need to know how I go about uploading them to this new server in the way that was advised on a recent post: "When you FTP up the files, instead of FTP'ing the index fil

  • 2 problems with QT

    Hi, I have recently 2 problems with QT, I downloaded the latest version. (7.2) 1. When I'm on a website by Firefox or safari, I can't see any video. I see a big QuickTime "Q" logo and a question mark in the middle of it... What do I do? 1. I received

  • How do I move a Premier Elements Project to a new computer?

    I want to move a Premier Elements Project to a different machine with more efficient RAM and SSDs. How do I move a Premier Elements Project to a new computer?