Will this encrypt data securely?

Hey I'm using bouncy castle AES password based encryption. I was just wondering if anyone would take a quick look at my code below to see if it will encrypt a string securely, or if I've missed anything out?
Thanks in advance
import java.io.File;
import java.security.Security;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;
public class encryptor {
     private final byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
               (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99,
               (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
               (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 };
     public static void main(String[] args)
          new encryptor();
     public encryptor()
          char[] password = "aRandomPassword".toCharArray();
          SecretKeySpec key = generateKey(password, salt);
          encrypt(salt, key, "A secret message");
     public SecretKeySpec generateKey(char[] charPassword, byte[] salt)
          byte[] bytePassword;
          PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          int count = 16;
          try
               bytePassword = new String(charPassword).getBytes("ASCII");
               generator.init(bytePassword, salt, count);
               ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(128, 128);
               KeyParameter keyParam = (KeyParameter) params.getParameters();
               return new SecretKeySpec(keyParam.getKey(), "AES");
          catch(Exception e)
               System.out.println(e);
               System.exit(1);
          //This will never occur
          return null;
     public void encrypt(byte[] salt, SecretKeySpec key, String text)
          IvParameterSpec iv = new IvParameterSpec(salt);
          Cipher cipher;
          byte[] temp;
          try
               cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
               cipher.init(Cipher.ENCRYPT_MODE, key, iv);
               temp = cipher.doFinal(text.getBytes("ASCII"));
               System.out.println(new String(Base64.encode(temp), "ASCII"));
          catch(Exception e)
               System.out.println(e);
}

I'm no expert in cryptology but you are using the salt byte array in two places, as salt and as the initialization vector. This strikes me as a big "no-no"; I suspect it could weaken your cipher. Even if I had no evidence of such weakening, I'd avoid that if at all possible.
You should generate separate salt and initialization vectors; in fact, you should generate them randomly each time you encrypt something. Naturally, you'll have to carry them along with the encrypted data so that you can pass them back in to the decryption process, but that's a small part to pay for not opening yourself up to dictionary attacks.
Also, you might want to apply the salt more than just 16 times; try something much larger, such as 1024.

Similar Messages

  • I am travelling overseas and want to transfer photos from my iPhone to the iPad using iCloud. will this incur data roaming costs?

    i am travelling overseas and want to transfer photos from my iPhone to the iPad using iCloud. will this incur data roaming costs?

    Yes, unless you are connected to free Wi-Fi.

  • Can you please help me with an office 365 issue in regards to receiving encrypted data/secure messages and being able to open and see the information

    I am unable to received encrypted emails from my work as when I log into my gmail account once I have clicked onto the email message I keep getting
    an error that says I must log out of my hotmail and into my gmail to receive this message.  I do this and still the same message.  I have actually gone onto Hotmail and signed out, gone then back to the link to sign into my gmail link for the encrypted
    message to log in with my gmail and password which I have also changed and still same, I am logged into Hotmail and I must log out and sign in with gmail address to access the encrypted message.  I have tried to use IE, Google Chrome and Firefox all with
    the same issues.  It appears our IT person is having the same issue.  We really need to get this going and is there a contact person who can help us?

    This is not an Office 365 support forum.  This is a Windows 7 support forum.
    The Microsoft Office support forums are found @
    https://social.technet.microsoft.com/Forums/office/en-us/home?category=officeitpro%2Cvisio2010%2Cgrooveserveritpro and that is where you need to post for assistance with Office 365.
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”

  • User Data Security through forms.

    Hi All,
    I am working on a forms(10g) which once deployed in application env. will have different level of accesses to different users , like view,edit,etc.
    could you please let me how to set up this user data security ,and access levels ...
    Is this to be done through forms development , or any environmental setups required?
    Any quick pointers in this regard are highlu appreciated.
    Thnaks.

    Hi,
    you can define your user level on oracle form,but these user only work on form level not on database level direct,you can make a proper setup form or role form to provide access to different user but you must mentioned these security on each transactional form.You also make a global procedure as security which maintain security only on form.Hope it'll helpful for you.
    Thanks
    Baloch.

  • Database Data Security: both from within (using MIMEbase64 encoding) and from without (using encryption).

    In my MDB file databases (Jet 4.x format) I turn on both compression and encryption.  This gives me data security from without, meaning, I can't open a MDB file in a Word Processing software (or otherwise) and read the data in a humanly recognized
    format.   But I am also using MIMEbase64 encoding of my stored data so that the data is humanly unreadable from within - meaning that anyone performing an SQL query will not be able to humanly read the data in my database.  I do the decoding
    (from MIMEbase64) within my end-user software interfaces to the databases. 
    I found out just recently (last few months) that I can do this from Win32 Perl, so I encorporated this feature into my Perl database applications.   Only thing is that MIMEbase64 increases the size of the data stored.
    Is there a better encoding strategy available today which might actually compress the data a little?    

     INSTRUCTIONS FOR SECURE/CUSTOM (non-formula based) TEXTFILE ENCODING (should be undecipherable w/o mappings file):
    by Eric C. Hansen. You may freely use these encoding instructions, and the code I have provided, but please
    acknowledge me as the author where credit is due - such as in a publication. And do not try to sell it.
    However, any code I have provided you may freely use in any programs you write to be sold for your own profit,
    except you may not attempt to sell this encoding scheme (or my code provided), as a generic encoding tool, for
    general use, to be marketed as a turn-key custom encoding solution. 
    (1) Create a unique code list 
          Using the characters:  A-Z a-z 0-9 only. That's 62 characters only.  
           62 (1 char codes) + 3844 (2 char codes) + 238,328 (3 char codes) = 242,234 total codes
                     62x1         +      62x62         +       62x62x62    
           REMINDS ME of my college Genetics course i.e. dominant/recessive trait inheritance tables  
           EXAMPLE CODES:  a, k, 3c, A4, xy1, H8j
    (2) Create a unique word(+punc) list from your textfile which is to be encoded. You know how to do this.
           Example of 9 words(+punc) found between whitespace within a textfile input line:
                "Hello", this is Mr. Bell-va-deer. My number is 999-342-8998.   
                    1       2    3   4       5              6      7       8       9
     PERL code for STEPS 3-7 is provided below. Code for STEP 1 above was previously provided. 
             You should have little trouble writing the textfile encode/decode logic yourself.  
    (3) Read your list of unique codes into an array.
    (4) Read your list of unique words(+punc) into another array.
         LOOP   #-- 0 to number of elements in words array
                (5)     select a random code and a random word(+punc) from the 2 arrays.
                (6)     now remove that code and that word(+punc) from each array using "splice".
                (7)     then save them as key/val pairs to persistent Perl SDBM database files ("mappings").  
         END LOOP
     (8) Once you have your persistent, random code/word mappings, you can convert your textfile
          to an encoded textfile. Read in one line at a time from your textfile (chomp), parse the words(+punc.)
         between whitespace within that line, then for each word(+punc) parsed, perform
         the word-to-code mapping conversions by doing a lookup within the Perl SDBM database
         file of key/val pairs, where KEY=word and VAL=code. You will then need to 
         concatenate these codes (space delimited) to your outputline, in the same order as found in your
         inputline, finally writing the outputline (newline "\n" terminated) to your new encoded textfile.    
    (9) Keep your persistent Perl SDBM database file ("mappings") in SAFE KEEPING, with a naming
         convention of your choice that perhaps hides any relationship to the name of
         your encoded text document - which it specifically pertains to. But keep a record of that joint
        relationship somewhere.  Keep a copy of both the original textfile and the encoded textfile,
        or perhaps you'd like to keep just the encoded textfile?, and not the original?  You can always decode it. 
    (10) Send your encoded text document via email as an attachment, to the recipient of your choice.
    (11) Upload your persistent Perl SDBM database "mappings" file to your secure login FTP download site. 
         NOTE:  If your encoded text document is very large, you may want to reverse 10 & 11, putting the encoded file
             on the FTP site, and sending the Perl SDBM database file ("mappings") as the email attachment.
    (12) Call your recipient to see if they have received the encoded textfile, email attachment.
         Let them know that the "mappings" file is uploaded for them to download from the FTP site.
        You can have a LINGO you both use/know on the phone, to secretly convey this message, if you like,
          to avoid possible interception of this sensitive information.
         Recipient will then take the encoded textfile email attachment, the FTP downloaded "mappings" file,
        and place them both in a directory on their PC where the Perl decoding program is located which you
         had previously sent them to handle all the decoding anytime you send them an encoded textfile + "mappings".
         Recipient will run the Perl decoding utility program to create the original textfile.
    use Win32;         #-- as you can see, I use a Windows O/S Perl distribution. 
    use IO::Handle;
    use SDBM_File;     #-- my understanding is this module comes standard with every Perl distribution
    use Fcntl;
        $PWD=Win32::GetCwd();  #-- get current working directory on Windows O/S platform.            
        srand;        #-- random seeding initiated, do this just once at top.
        @codesARR=();    @wordsARR=();          #-- initialize the arrays
        print "working.  please wait...\n\n";
        unlink( "$PWD\\Project_0836_Mappings_CtoW.pag" )
                    if (-e "$PWD\\Project_0836_Mappings_CtoW.pag" );
       unlink( "$PWD\\Project_0836_Mappings_CtoW.dir" )
                  if (-e "$PWD\\Project_0836_Mappings_CtoW.dir" );
        unlink( "$PWD\\Project_0836_Mappings_WtoC.pag" )
                  if (-e "$PWD\\Project_0836_Mappings_WtoC.pag" );
       unlink( "$PWD\\Project_0836_Mappings_WtoC.dir" )
                 if (-e "$PWD\\Project_0836_Mappings_WtoC.dir" );
         unlink( "$PWD\\Project_0836_Mappings.txt" )
                 if (-e "$PWD\\Project_0836_Mappings.txt" );
       $cnt1=0;    $ret="Y";
        open(CODES,"$PWD\\codes.txt") || do {$ret="N";};
        if ($ret eq "N") {  
               print "Codes input file not opened \n";  
               sleep 5;   die;  
        while (<CODES>) {
               chomp $_;
              $codesARR[$cnt1]=$_;
              $cnt1++;
        print $cnt1 . " codes loaded\n\n";
       close(CODES);
       $cnt2=0;    $ret="Y";
       open(WORDS,"$PWD\\words.txt") || do {$ret="N";};
        if ($ret eq "N") {  
                print "Words input file not opened \n";  
               sleep 5;   die;  
       while (<WORDS>) {
               chomp $_;
              $wordsARR[$cnt2]=$_;
                $cnt2++;
        print $cnt2 . " words loaded\n\n";
        close(WORDS);
        sleep 3;       #-- a little time to check on record counts loaded to both arrays
      tie( %Project_0836_Mappings_WtoC, "SDBM_File", '.\Project_0836_Mappings_WtoC', O_RDWR|O_CREAT, 0666 );
       if (tied %Project_0836_Mappings_WtoC) {
               print "WtoC Hash/SDBM File are now tied\n\n";    
       } else {
              print "Could not tie WtoC Hash/SDBM File\n\n";  sleep 5;  die;
       tie( %Project_0836_Mappings_CtoW, "SDBM_File", '.\Project_0836_Mappings_CtoW', O_RDWR|O_CREAT, 0666 );
        if (tied %Project_0836_Mappings_CtoW) {
                 print "CtoW Hash/SDBM File are now tied\n\n";    
        } else {
               untie(%Project_0836_Mappings_WtoC);  #-- close the successful tie made directly above 
              print "Could not tie CtoW Hash/SDBM File\n\n";  sleep 5;  die;
      open (OUT,"> $PWD\\Project_0836_Mappings.txt");
       OUT->autoflush(1);
       $cnt2=$#wordsARR;   #-- we do this because we will be removing elements from wordsARR
       for ($i=0; $i<=$cnt2; $i++) {
             $index   = rand @codesARR;    # get a random index from the codes array
            $code    = $codesARR[$index]; # get the value of that array element
            splice(@codesARR,$index,1);   # removes only this element from the codes array.
            $index   = rand @wordsARR;    # get a random index from the words array
            $word    = $wordsARR[$index]; # get the value of that array element
            splice(@wordsARR,$index,1);   # removes only this element from the words array.
            $Project_0836_Mappings_WtoC{$word}=$code;   # key/value pair where: word is key, code is value
            $Project_0836_Mappings_CtoW{$code}=$word;   # key/value pair where: code is key, word is value
        print "Your Mappings have been created and saved to (.dir and .pag extension files)\n\n";
        print OUT "Here are your Mappings you just created:\n\n";
        foreach $key (keys %Project_0836_Mappings_WtoC) {
              print OUT "word=" . $key . "     code=" . $Project_0836_Mappings_WtoC{$key} . "\n";
      print OUT "##################################################\n";
       foreach $key (keys %Project_0836_Mappings_CtoW) {
               print OUT "code=" . $key . "     word=" . $Project_0836_Mappings_CtoW{$key} . "\n";
        untie(%Project_0836_Mappings_WtoC);  #-- now you have saved a persistent word/code mappings file
        untie(%Project_0836_Mappings_CtoW);  #-- now you have saved a persistent code/word mappings file
        close(OUT);   
        print "Done.  Goodbye!\n";
        sleep 5;
        exit;

  • File Vault encryption locked up.  No progress for 24 hrs.  If I restore from a non-encypted back-up will this cause problems?

    Started file vault yesterday and no progress for 24 hrs.  If I do a Command-R restore from a non-encrypted back-up will this cause problems?

    You first must repartition and reformat the drive before restoring your backup.
    Install or Reinstall OS X from Scratch
    Boot to the Recovery HD:
    Restart the computer and after the chime press and hold down the COMMAND and R keys until the menu screen appears. Alternatively, restart the computer and after the chime press and hold down the OPTION key until the boot manager screen appears. Select the Recovery HD and click on the downward pointing arrow button.
    Erase the hard drive:
      1. Select Disk Utility from the main menu and click on the Continue button.
      2. After DU loads select your startup volume (usually Macintosh HD) from the
          left side list. Click on the Erase tab in the DU main window.
      3. Set the format type to Mac OS Extended (Journaled.) Optionally, click on
          the Security button and set the Zero Data option to one-pass. Click on
          the Erase button and wait until the process has completed.
      4. Quit DU and return to the main menu.
    Reinstall OS X: Select Reinstall OS X and click on the Install button.
    Note: You will need an active Internet connection. I suggest using Ethernet if possible
               because it is three times faster than wireless.
    This should install the version of OS X that you had installed.

  • How to make encrypted data more secure?

    Hi All,
    We are using Oracle 9i database. We have a task to encrypt some of data before storing into database. We have developed a function to encrypt the data using Dbms_Obfuscation toolkit. But, the user who has access to that function source code can easily decrypt the data. Now we need to have the solution so that we can securely save/store Encryption Key, which can be accessed by Application User only.
    One alternative we are thinking is creating a table in SYS user and storing the value there. We can grant SELECT privileges to Application User Only.
    We are looking for other alternatives if we have any. Do you have any idea?
    Thanks in Advance.
    Thanks and Best Regards,
    Dharmesh Patel
    Database Server:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    ******************************************************/

    I had a look at this conundrum a while back, when we wanted to store credit card details in a database. Basically, there are two choices:
    (1) Don't store the key in the database and make the users type it in whenever they want to see encrypted data; or
    (2) Store the key in the database and accept the risk that it might be abused by privileged users (i.e. DBAs).
    As many users have difficulty remembering their password when it's MOM123 I think it's unlikely they will be able to cope with a properly secure PKI string.
    You can mitigate the risks inherent in option 2 by having very strong auditing of the function's execution, but I'm sure knowledgeable, black-hatted DBAs will be able to find workarounds.
    But, if you can't trust your DBAs you're probably stuffed anyway.
    Cheers, APC

  • HT204053 I have one icloud id on my mac and want to share with an ipad with a different icloud id.  if I create a new id for both of us will this work?  My concern is losing data on either device.

    I have one icloud id on my mac and want to share photos, calendars, etc with an ipad with a different icloud id.  if I create a new id for both of us will this work?  My concern is losing data on either device. (the mac book pro is new, but has all of the retrieved data from my previous mac book pro)

    You will lose data from whichever was the 2nd to last to sync .
    Don't do it.

  • Some calendars in iCal appear corrupted but OK on iPhone. If I sync will the calendar data on the phone restore info on the desktop iCal? any other ideas for how to sort this please?

    Some calendars in iCal appear corrupted (ie have red exclamation mark by them) but are still OK on iPhone. If I sync, will the calendar data on the phone restore info on the desktop iCal or will I lose that as well? Or could I back up the calendars on my iPhone somewhere and then import them into iCal? any other ideas for how to sort this please? it's driving me mad. thanks.

    I don't think there will be a solution to this. Exchange 2003 just isn't supported.

  • I just got a new iPhone and i set up iCloud on my girlfriend's account. To change it on settings it says delete account. Will this delete her all her data and back up data for iCloud on her iPhone and iPad?

    I just got a new iPhone and i set up iCloud on my girlfriend's account. To change it on settings it says delete account. Will this delete her all her data and back up data for iCloud on her iPhone and iPad? Can i change it without deleting it? Please help.

    Delete the account on your phone. This will not delete any data on her phone or iPad, or data stored in iCloud.

  • Just bought a used MacBook pro after my previous died. I want to migrate my applications, data, etc from a time machine backup of the old computer to the new. Will this affect, or overwrite the Apps., data, etc existing on the new machine?

    Just bought a used MacBook pro after my previous died. I want to migrate my applications, data, etc from a time machine backup of the old computer to the new. Will this affect, or overwrite the Apps., data, etc existing on the new machine?

    No. Only those Apps that are not installed on the new will migrate over.

  • Just bought a 2tb external hard drive with the intention of moving my iPhoto data files on it. I have so much of my 500 gigs being used up by images and video. Questions: Will this foul up my iPhoto app? Do I need to point iPhoto to this new location?

    Just bought a 2tb external hard drive with the intention of moving my iPhoto data files to it. I have so much of my 500 gigs being used up by images and video. Questions: Will this foul up my iPhoto app?
    Do I need to point iPhoto to this new location?
    Thanks!

    Are you running a Managed or a Referenced Library?
    A Managed Library, is the default setting, and iPhoto copies files into the iPhoto Library when Importing. The files are then stored in the Library package
    A Referenced Library is when iPhoto is NOT copying the files into the iPhoto Library when importing because you made a change at iPhoto -> Preferences -> Advanced. (You unchecked the option to copy files into the Library on import) The files are then stored where ever you put them and not in the Library package. In this scenario you are responsible for the File Management.
    Assuming a Managed Library:
    Make sure the drive is formatted Mac OS Extended (Journaled)
    1. Quit iPhoto
    2. Copy the iPhoto Library from your Pictures Folder to the External Disk.
    3. Hold down the option (or alt) key while launching iPhoto. From the resulting menu select 'Choose Library' and navigate to the new location. From that point on this will be the default location of your library.
    4. Test the library and when you're sure all is well, trash the one on your internal HD to free up space.
    Regards
    TD

  • Using latest version of fireFox to access Think Central, pages will not load and they say that this is a security issue with FireFox?

    Teachers in our district are supposed to use www.thinkcentral.com with FireFox.
    Some have no problem accessing the lesson plans.
    Most when they login click on a lesson plan and an icon shows up that says loading but never does.
    If you reboot the computer and login you can open a page once but not a second time and no other lessons will open.
    Think Central support says this is a security issue with Firefox.
    I have updated FireFox, all the Adobe, Reader, Flash, Air and Shockwave. As well as Java.
    I have allowed the pop ups to the think Central web site.
    Any help would be appreciated

    Are there any notification icons on the left end of the address bar? If so, please click them to see whether they related to security issues (such as blocked content - shield icon: [[How does content that isn't secure affect my safety?]]) or a plugin requiring permission (Lego-like icon).
    Does Think Central have any help pages about this issue? Without an account, it is difficult to explore the issue first-hand.

  • Can I connect my iPad mini to a data projector using a lightning to 30-pin adapter connected to a 30-pin to VGA connector? Or will this only work with a lightning to VGA connector.

    Can I connect my iPad mini to a data projector using a lightning to 30-pin adapter connected to a 30-pin to VGA connector? Or will this only work with a lightning to VGA connector?

    The lightning to 30 pin adapter does not support video as per the item description in the Apple online store:
    http://store.apple.com/us/product/MD823ZM/A/lightning-to-30-pin-adapter
    This adapter lets you connect devices with a Lightning connector to many of your 30-pin accessories.* Supports analog audio output, USB audio, as well as syncing and charging. Video output not supported.
    You will need to the Lightning to VGA adapter directly
    http://store.apple.com/us/product/MD825ZM/A/lightning-to-vga-adapter?fnode=3a
    Or the Lightning Digital AV Adapter
    http://store.apple.com/us/product/MD826ZM/A/lightning-digital-av-adapter
    If the projector supports HDMI input.

  • Wifi is not available where I come from. I have broadband connection where data transmission is through cell sites then to USB modem connected to a computer. The modem draws power from the computer. Will this setup work with the ipad?

    Wifi is not available where I come from. I have broadband connection where data transmission is through cell sites then to USB modem connected to a computer. The modem draws power from the computer. Will this setup work with the ipad?

    iPad requires Wifi (or 3G /LTE) to connect to the Internet. You cannot connect a USB modem to the iPad.
    You can create your own WiFi hotspot through your computer for your iPad to connect to, if your computer supports this functionality. All Wifi Macs and many Wifi PCs do. Check your computer manual for how to do it.

Maybe you are looking for

  • Error  while posting customer and vendor documents

    Hi      Iam trying to post the entries in f-22 and f-43,its displaying that *No values for this selection* at account filed, I reconcile the customer and vendor accounts in fs00 I assigns the account no's to customer and vendor master records Thank y

  • Running Forms

    Hello all: I am running forms 9i and am now able to get it to run in the browser. Is there a way to make the form fill the entire browser for better viewing? Any help for a newbie is greatly appreciated. Thanks to all.

  • Lightroom not reading tiff files from photoshop

    It was working ok and then LR 3 stop bringing in the images that I sent to PS (CS5) to edit..it does not bring them into my collection..help!

  • I just bought a new iMac. But it has apps from another account.

    I'm a windows user who is recently interested in macs cuz they look pretty. After installing office, i went into the app store, only to find that i have new updates. so when i went to the updates tab. i found angry birds. but i didnt bought angry bir

  • Export graphics to Adobe Illustrator file format

    Does anyone have or know where to get a "hello world" type script to save Java2D objects to a Adobe Illustrator file format. I have looked at the file format specification and it is quite detailed. Just hoping for something to get me started, as the