Calculating bit strength

I have an application which uses AES/CBC/PKCS5Padding to encrypt data. How would I calculate the bit strength of the encryption. I'm using a key entered by the user to encrypt, then this code to generate a SecretKeySpec.
        byte[] key = new byte[16];
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(keystring.getBytes("UTF-8"));
        byte[] hash = digest.digest();
        int len = hash.length;
        if (len > key.length) {
            len = key.length;
        System.arraycopy(hash, 0, key, 0, len);
        return new SecretKeySpec(hash, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);How would I calculate the bit strength of the encryption?

Use the KeyGenerator class to generate a key once and store it in a KeyStore, retrieve it when needed using a strong password.
Or, generate a PBE key whenever needed which is still based on a string but a LOT better than just .getBytes on a string. Sun doesn't support PBE with AES, but I think the bouncycastle provider does.

Similar Messages

  • How can I determine the cipher bit strength used by MY os X?

    How can I determine the cipher bit strength used by MY OS X?  Using Lion now?

    CT:
    Not Filvault, but the regular cryptographic use as built into OS X.  For example 1Password uses the algorithm in the OS X's Linux.  How many bits (i.e. 50, 128, 256...) does it use and what algorithm (DES, AES...)
    Linc
    As per reply to CT?
    Like so:
    http://osxdaily.com/2012/01/30/encrypt-and-decrypt-files-with-openssl/
    What is the strength used?

  • OS X Calculator: bits don't show in binary view

    I don't know when this started, but in the binary view of the OS X Calculator the bits aren't showing anymore (0 or 1).
    I haven't found a solution yet. Could I reinstall the calculator?

    Please read this whole message before doing anything.
    This procedure is a test, not a solution. Don’t be disappointed when you find that nothing has changed after you complete it.
    Step 1
    The purpose of this step is to determine whether the problem is localized to your user account.
    Enable guest logins and log in as Guest. For instructions, launch the System Preferences application, select Help from the menu bar, and enter “Set up a guest account” (without the quotes) in the search box.
    While logged in as Guest, you won’t have access to any of your personal files or settings. Applications will behave as if you were running them for the first time. Don’t be alarmed by this; it’s normal. If you need any passwords or other personal data in order to complete the test, memorize, print, or write them down before you begin.
    Test while logged in as Guest. Same problem(s)?
    After testing, log out of the guest account and, in your own account, disable it if you wish. Any files you created in the guest account will be deleted automatically when you log out of it.
    Note: If you’ve activated “Find My Mac” or FileVault in Mac OS X 10.7 or later, then you can’t enable the Guest account. Create a new account in which to test, and delete it, including its home folder, after testing.
    Step 2
    The purpose of this step is to determine whether the problem is caused by third-party system modifications that load automatically at startup or login.
    Disconnect all wired peripherals except those needed for the test, and remove all aftermarket expansion cards. Boot in safe mode and log in to the account with the problem. The instructions provided by Apple are as follows:
    Be sure your Mac is shut down.
    Press the power button.
    Immediately after you hear the startup tone, hold the Shift key. The Shift key should be held as soon as possible after the startup tone, but not before the tone.
    Release the Shift key when you see the gray Apple icon and the progress indicator (looks like a spinning gear).
    Safe mode is much slower to boot and run than normal, and some things won’t work at all, including wireless networking on certain Macs.
    The login screen appears even if you usually log in automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
    Test while in safe mode. Same problem(s)?
    After testing, reboot as usual (i.e., not in safe mode) and verify that you still have the problem. Post the results of steps 1 and 2.

  • Need help for a newbie problem

    I am VERY new to all this Java programming but have really started to enjoy it.
    I have two problems with my program that I can not find answers to.
    1. I am looking to find out why my code will not select the right answers when I select the first choice in the array. The answer that is delivered turns out to be the 3rd selection. The second and third selection work great, but the first selection always turns out with the thrid answer.
    2. I know I need to do better error checking on the user input. At this point I am only checking for correct integer input, but I dont know how to fix or avoid the error for when the user would mistakedly enter letters instead of numbers.
    Any hints?
    Code to follow... I hope...
    No gui allowed for this program.
    First time posting so I hope this works and I do it the right way...
    import java.text.DecimalFormat;      //To round to 2 decimal places for payment format.
    import java.io.*;                          //Allows User to input.
    public class Wk5JimP
         //classes for keyboard inputs from user
         public static InputStreamReader reader = new InputStreamReader (System.in);
         public static BufferedReader keyboard = new BufferedReader (reader);
         //main
         public static void main (String[] args) throws IOException
              //Variables
              DecimalFormat decimal = new DecimalFormat("#,##0.00");     //Makes the decimal format for the output
              int appAmount = 200000;                                             //approved loan amount
              short rPay = 0;                                                       //repayment option
              int ps;                                                                 //payment schedule switching variable.
              //Year array and variables
              int yTerm[] = {30, 15, 7,};                                        //Term of the loan in years array
              short rOller2 = 0;                                                  //looping variable for rolling the years
              short rOller3 = 0;                                                  //looping variable for rolling the years
              //Month array and variables
              int mTerm[] = {360, 180, 84,};                                   //Term of the loan in months array
              short rOller = 0;                                                  //looping variable for rolling the months
              short rOller1 = 0;                                                  //looping variable for rolling the months
              //Interest rate array and variables
              double iRate[] = {5.75, 5.50, 5.35,};                              //interest rate array
              int liRate = 0;                                                       //looping variable for interest rate
              int liRate1 = 0;                                                  //looping variable for interest rate
              // Payment array and variables
              double mPayment[] = {
                   ((appAmount*(iRate[0]/12/100))/(1-1/Math.pow((1+iRate[0]/12/100), mTerm[0]))),
                   ((appAmount*(iRate[1]/12/100))/(1-1/Math.pow((1+iRate[1]/12/100), mTerm[1]))),
                   ((appAmount*(iRate[2]/12/100))/(1-1/Math.pow((1+iRate[2]/12/100), mTerm[2])))
                                       };                                             //monthly payment array
              int lPay = 0;                                                       //looping variable for payment incrementation
              int lPay1 = 0;                                                       //looping variable for payment incrementation
              //Dollar amounts into decimal format of two places
              String fappAmount = decimal.format(appAmount);
              //Output to screen for header information
              System.out.println();
              System.out.println("Congratulations!");
              System.out.println("You are approved for a $" + fappAmount + " loan");
              System.out.println("The three repayment options are listed below.\n");
              System.out.println("-------------------------------------------------------------------------");
              System.out.println(" Repayment\t Loan\t\t   Term\t\t  Interest\t  Monthly");
              System.out.println("  Option\tAmount\t       Years   Months\t  Rate \t          Payment");
              System.out.println("-------------------------------------------------------------------------");
              //Begin repayment option loop for calculation
              while (rOller != 3)
                        // if else loop to second and third repayment options
                      if (rOller1 <= 2)
                           // for statement loops last repayment option
                           for (rPay = 1; rPay <=3; rPay++)
                                    {mPayment[lPay] = mPayment[lPay1++];
                                     yTerm[rOller2] = yTerm[rOller3++];
                                     mTerm[rOller] = mTerm[rOller1++];
                                     iRate[liRate] = iRate[liRate1++];
                                //Output to screen for numerical repayment option info
                              System.out.println("    " + rPay + "\t    $" + fappAmount + "\t\t " + yTerm[rOller2] + "\t" + mTerm[rOller] + "\t    " + decimal.format(iRate[liRate]) + "% \t$" + decimal.format(mPayment[lPay])+ "\n\n");
                        else
                             //begin payment option selection
                             System.out.println();
                             System.out.println("Which one of the payment schedules would you like to see?\n");
                             System.out.println("Please enter 1 or 2 or 3 to see the payment schedule\nor enter any other number to exit.");
                             ps = Integer.parseInt(keyboard.readLine());
                                  switch (ps)
                                            case 1:
                                                 System.out.println("\nOption #1\n");
                                                 paysched(yTerm[0], appAmount, iRate[0], mPayment[0]);
                                                 break;
                                            case 2:
                                                 System.out.println("\nOption #2\n\n");
                                                 paysched(yTerm[1], appAmount, iRate[1], mPayment[1]);
                                                 break;
                                            case 3:
                                                 System.out.println("\nOption #3\n\n");
                                                 paysched(yTerm[2], appAmount, iRate[2], mPayment[2]);
                                                 break;
                                            default:
                                                 System.out.println("Thank you!\n\n");
                                                 System.exit(0);
                                      }//end switch
                   }//end while
              }//end main
                             //payment schedule method
                             public static void paysched(int yTerm, int appAmount, double iRate, double mPayment) throws IOException
                             //Declare variables for looped calculations
                             DecimalFormat decimal = new DecimalFormat("#,##0.00");     //Makes the decimal format for the output
                             double balance = appAmount;
                             double monIRate = iRate / 12;
                             double iPay = 0;
                             double pPay = 0;
                             short pNum = 1;
                             short year = 1;
                             //Header Output to screen for payment schedule
                             System.out.println("-------------------------------------------------------------------------");
                             System.out.println("   Payment \t   Principle\tInterest\tTotal \t\tBalance");
                             System.out.println(" Year  Month\t   Payment\tPayment \tPayment \tRemaining");
                             System.out.println("-------------------------------------------------------------------------");
                             //Loop for shceduled payment calculation for all but the final year
                             do
                                       //Apply the payment
                                       iPay = balance * (monIRate /100);
                                       pPay = mPayment - iPay;
                                       balance = balance - pPay;
                                       //Output to screen for payment information
                                       System.out.println("   " +year+ " \t " +pNum+ " \t  $" +(decimal.format(pPay))+ "\t$" +(decimal.format(iPay))+ "\t      $" +(decimal.format(mPayment))+ "\t     $" +(decimal.format(balance)));
                                       pNum++;
                                       if (pNum % 13 == 0)
                                            System.out.println("Press enter to see the next year payments.");
                                            System.in.read();
                                            System.in.read();
                                            year++;
                                            pNum = 1;
                                            //Output to screen for payment schedule
                                            System.out.println("-------------------------------------------------------------------------");
                                            System.out.println("   Payment \t   Principle\tInterest\tTotal \t\tBalance");
                                            System.out.println(" Year  Month\t   Payment\tPayment \tPayment \tRemaining");
                                            System.out.println("-------------------------------------------------------------------------");
                                            } //end if
                                    } //end do
                             while(year < yTerm);
                             //Final Year calculations
                             do
                                       //Apply the payment
                                       iPay = balance * (monIRate /100);
                                       pPay = mPayment - iPay;
                                       balance = balance - pPay;
                                       //Output to screen for payment information
                                       System.out.println("   " +year+ " \t " +pNum+ " \t  $" +(decimal.format(pPay))+ "\t$" +(decimal.format(iPay))+ "\t      $" +(decimal.format(mPayment))+ "\t     $" +(decimal.format(balance)));
                                       pNum++;
                                       if (pNum % 13 == 0)
                                            System.out.println("Please press enter to select and view another payment schedule.");
                                            System.in.read();
                                            System.in.read();
                                            year++;
                                            } //end if
                                  }//end do
                             while(year < (yTerm+1));
                        }//end class
    }//end classThis is my first post so please be gentle...
    Thanks for any help!

    When you choose Java to solve the problems, you need to adapt to the power/strategies/methodology that java offers you, and thats the way for solving problems in Java.
    Why would you put the entire implementation for calculation inside main method? You could break down the program into smaller methods which could do the calculation bit and then call them in main method.
    Anyways the reason that it is calculating for term of 7 years is that
                           // for statement loops last repayment option
                           for (rPay = 1; rPay <=3; rPay++)
                                    {mPayment[lPay] = mPayment[lPay1++];
                                     yTerm[rOller2] = yTerm[rOller3++];You are changing the value of the array yTerm[ ]. Hence once the control is out of the for loop the value of y[0]=7,y[1]=7 and y[2]=7.
    Solution 1: mark yTerm as final.
    Solution 2: set yTerm[0], yTerm[1] back as 30,15 after the for loop.
                      if (rOller1 <= 2)
                           // for statement loops last repayment option
                           for (rPay = 1; rPay <=3; rPay++)
                                    {mPayment[lPay] = mPayment[lPay1++];
                                     yTerm[rOller2] = yTerm[rOller3++];
                                     mTerm[rOller] = mTerm[rOller1++];
                                     iRate[liRate] = iRate[liRate1++];
                                //Output to screen for numerical repayment option info
                              System.out.println("    " + rPay + "\t    $" + fappAmount + "\t\t " + yTerm[rOller2] + "\t" + mTerm[rOller] + "\t    " + decimal.format(iRate[liRate]) + "% \t$" + decimal.format(mPayment[lPay])+ "\n\n");
                           yTerm [0]=30;
                           yTerm [1]=15;
                              }Futher the issue is with monthly calculation of pay back amount in switch - case statement.
    As you have not provided what the problem is and what is the criteria for calculation of monthly interest or reducing the amount etc. Its not possible (at least for me) to tell you why it would run to negative. Mathematically that is the only thing possible,
    Step 1: make those changes in your code. Make changes required to claculate the balance.
    Step 2: Execute the new code and
    Step 3: Gimme the dukes.
    Cheers
    $

  • Saving Maps as JPG's for Book Module Use

    Does anyone know of a way to save a map with my data (locational) on it for import into the book module?

    Sure, but that's really a work around and may not give you the bit strength to make a clean map feature in either the book module or slide show.

  • Questions about Azure

    Good Afternoon,
    I am just looking at Azure as an alternative to using in house hosting for a couple of customers but I keep coming up with questions I cannot find the answer to, hence my question.
    The first one that springs to mind is this:
    If I set up a new Virtual Server in Azure is the operating system included in the price of the Server? So far I have played around with the calculator bit for pricing and its explanations leave lots of gaps.
    If I pick a basic Server it tells me the processor and RAM but does not mention a hard drive, so do I go to the Locally Redundant storage and select it there? Does this storage include the OS partition as well or is that included.
    How do I work out the Bandwidth? Surely we won't know that until it has run for a while?
    How is the virtual server backed up? How do I restore files if I need to.
    There may be more questions but this will do for a start.
    Thanks for your help.
    alamb200

    You need to pay for OS disk and other Data disks. You do not have to pay for temporary storage drive (D:\)
    You cost for VM includes OS license.
    https://msdn.microsoft.com/en-us/library/azure/dn683781.aspx
    https://msdn.microsoft.com/en-us/library/azure/dn197896.aspx

  • How do I configure Compressor for a 122 min clip?

    I'm trying to make a 122 min viewer DVD ...its not fancy .. no menus, no titles ... its first play. I've read the user manual trying to figure out how to configure Compressor but I can't make heads or tails of it -- calculating bit rates and all.
    its a 22 GB file. I don't need high quality video output. I just need to get this whole clip on one DVD that will play in a consumer deck.
    I used Compresssor 1.2 to create files for DVD Pro 3 ... using the "MPEG2 120 min Fast Encode" preset and got 5 GB.
    is there a better preset? ... something else I need to do to the quicktime file to fit it on a 4.7 GB disk?
    thanks for your help!
    ana

    Try 120 minute best quality.
    Don't forget to compress the audio to AC3.
    If that ends up too large, duplicate the preset you just used and dial down the bitrate and save it. Then apply the new version and try again.
    Rinse and repeat as nec till it fits.
    x

  • ACE client authentication performance degredation

    Hi,
    If possible is anybody able to provide any advice & guidance WRT the below:
    According to; http://www.cisco.com/en/US/docs/interfaces_modules/services_modules/ace/vA4_1_0/command/reference/sslproxy.html “When you enable client authentication, a significant performance decrease may occur in the ACE module.”
    The statement raises a lot of questions;
    1. Presumably the degradation can only happen as a result of an SSL client performing a handshake with the ACE (SSL server), the ACE requesting a client certificate and the client responding with a certificate at which stage the ACE has to verify the Client certificate?
    2. Some metrics are needed from Cisco around the degradation – for example how many certificate verifications per second can the ACE support (1,10,100,1000)? If this is dependent on RSA key size then metrics are needed  for 1024 and 2048 keys.
    3. The Cisco ACE supports partitioning of resources (http://docwiki.cisco.com/wiki/Cisco_Application_Control_Engine_%28ACE%29_Module_Troubleshooting_Guide,_Release_A2%28x%29_--_Managing_Resources_ and therefore I assume that the ACE can be protected from degradation by setting a limit on SSL handshakes per second which is well below the limit from 2?
    4. Any references to some relevant documentation ?

    Hello Preck-
    As a first point, we don't generally document ever possible aspect of performance numbers on products because there are many factors that play into the numbers.  This is one of the grey areas where we cannot pin down any hard numbers due to too many outside factors.
    Here is the full story on SSL client authentication:
    Under a normal SSL handshake, the SSL server exchanges the public key and certificate file to the client, and a cipher is chosen to encrypt the communication between the two entities.  Past that communication, there are a few things that could result in extra packets, or a new SSL handshake i.e. SSL version negotiation and/or cipher related issues.  Some things can shorten the handshake time like SSL session ID's and using specific SSL protocols (i.e. if the client and server only ever used TLS v1.1 and never had to negotiate from SSL v3.0 to TLS).
    Once the handshake is done, the performance only depends on network latency and the amount of time it takes to encrypt/decypt the traffic which is dependent on the SSL version, cipher, and SSL strength (key bits).  This is important to your questions because the only thing that effects performance is the initial handshake process.
    When you enable client authentication, before the handshake is complete, the server requests the client to send a certificate.  The client may send multiple certificates, or just 1. When the server recieves the certificate, it checks that it matches the certificate that it has installed for client authentication. As well, the server may do an extra check against the CRL to see if the certificate has been revoked (this is an external call to the CA via TCP or LDAP generally)  The amount of certs, size of the certs, and size of the CRL are not known to the server, hence, it has to work with what it recieves.  The larger the files, the longer the handshake takes to complete.
    Specific to ACE:
    The degredation you are going to see is exactly what I stated in the last paragraph - it will be related to how many certs the ACE has to parse, how long it takes to get the CRL and check it all the way through.  Because every client could give the ACE a different amount of certificates and the CRL could be any size/take any amount of time to retrieve and scan, there is no such thing as a common metric we can state about the difference in performance.
    We can tell you that the performance degredation is limited to the VIP that you have this enabled on and should not effect any other vips/context/the whole ACE in general.  It also only relates to the amount of possible transactions per second, and not to total SSL concurrent connections or throughput.  Throughput is not effected because the SSL Nitrox and Cadvium engines are not used to scan the client certificate - the XScale Microengine is, so the throughput of the SSL daughter cards are not effected here.
    The bit count within the keypair is non-effecting to the performance when enabling client authentication if you are comparing the same as without client authentication.  Certainly, you will see a drop in performance when moving from 1024 to 2048 bit keys due to the extra complexity involved in encrypting/decrypting - but no additional loss with client authentication.  On a side note, keep in mind that doubling you key bit strength means your performance will take an exponential drop - not a linear drop.  If you are planning on deploying 2048bit keys, make sure you test your environment prior to production release so that you know exactly what kind of performance to expect.
    About your question on partitioning resources, because this only effects the vip you have the authentication on, you don't need to worry about sandboxing off a context to handle this.
    Regards,
    Chris Higgins

  • PSD doubt against MATLAB

    Task:
    On components exposed to high vibration, it is often inertial forces that provide the greatest the load. One way to test the strength of these components is by using a shaker table. By first measuring the accelerations which the component is exposed to the test track or at a customer to the acceleration as a function of frequency are developed, a so-called power density spectrum (PSD). This then used as the driving signal to skakbordet where the tested component is fixed. Using Finite Element program, the same can be done with a virtual shaker table. The advantage is that component's strength can be calculated before an expensive prototype. Many variations can be also tested in a short time. Instead of a calculation in the time domain, a calculation by a frequency response analysis using the PSD produced for use in skakprovningen. The is performed by the FE program first calculates the system's natural frequencies and with a estimated modal damping estimates the transfer function of the system. Thereafter, the response, distributed over the frequencies, obtained by excitations from the PSD spectrum. That is, the acceleration as a function of frequency times the system transfer function gives the response (eg, voltage) function of frequency. The result is a power spectrum in each calculation point in the model for all voltage components. We uses this method today for calculating the strength of the components are assumed to have a fatigue limit. The evaluation is made when the "infinite life". But no clear fatigue limit Not available for welders but these must be evaluated in a finite lifespan. Mission Statement Study the methods described in the literature and develop a method for fatigue assessment of welds. Verify the method by perform a load measurement at an appropriate component containing welding and fatigue try this and calculate the lifetime of the proposed method. Objectives Develop a routine for calculating the fatigue assessment of weld to do with the PSD.
    This task can be done by  Abaqus and MATLAB.
    Dobut
    Can we do it with Labview?. I am good at labVIEW tham MATLAB. So, I don't know wheather i can do it in labVIEW or not. I have been working with Signal processing. SO i hope it is possible to do it in labview but not sure.

    Thanks for your help.
    When i run matlab psd code it return real values and for matlab csd it return complex values (due to the difference in the 2 signals phase). 
    So the in LV i tried run the signals using FFT spectrum.vi(real and im) and FFT cross spectrum.vi(real and im). it return different values from Matlab. So i reckon some of the parameters like window or averaging was not defined properly.
    Attached is my vi.  
    Attachments:
    Pic2.JPG ‏111 KB

  • Flash player not working on internet explorer 8 cipher strength 128-bit

    PLEASE HELP!
    I'Mm using Windows XP and Internet Explorer 8 with cipher strength 128-bit and Flash player does not work properly, like when I want to watch a music video or listen to music on You Tube it plays then stops and plays and stops continuously I have installed the latest Flash Player but still have the same problem.
    Please please help anyone!

    That sounds like you either have a very slow Internet connection, or the server at the other end (providing the video) is slow.
    Try clearing your Internet cache; this helps sometimes.

  • How to add 15 bit can crc calculation to labview polynom is x15 + x14 + x10 + x8 + x7 + x4 + x3 + 1 .

    how to add can crc calculation to labview polynom is x15 + x14 + x10 + x8 + x7 + x4 + x3 + 1
    for 15 bit calulation
    thanks for any assistance

    Hi there,
    Here you can find the explanation of how the CRC calculation is done (see page 15). Now, if you are planing to do this with NI hardware/software it does not make sense since the calculation it is already taken care by the driver. In case you want to do this on your own using digital lines be careful with impedances and any other electrical consideration.
    I hope this helps
    Alejandro | Academic Program Engineer | National Instruments

  • CS5: 16 Bit, File - Save As JPEG - No Size Pre-Calculation

    I just want to say thanks again to the engineers at Adobe for finally adding the ability to save a 16 bit per channel file as a JPEG without first converting to 8 bit mode.  It will save me a bunch of future "aw dang" moments when I realize I've forgotten to go back in the history after saving to restore my file to 16 bits per channel.
    I've noticed the pre-calculation of the JPEG file size estimate, however, is not correct when saving from a 16 bit file...  Usually it just shows "--" though I believe I've seen it say 0 kb at one time or another (could be wrong)...  I assume this is because the size estimate algorithm doesn't know about 16 bit data.  It seems to work as usual for 8 bit data.
    Is this a well-known glitch and can we expect a fix (Chris)?  It's a minor annoyance but as I often save JPEGs for forums that have size limitations it would be nice to have back.
    -Noel

    Yep, known bug

  • Looking for an online bit calculator

    What's the best way of determining bit rate for long form jobs. I do between 1 1/2 hours to 2 hours 20 minutes?
    I am interested in 2 pass mainly. I will be using FCP6 & converting to m2v-ac3 in compressor then bringing into DVD studio pro4 for authoring. 3 pages of 12-15 chapters motion menus.
    NTSC, DV, 8 core mac, 8 gigs ram, 3 drives raid0
    What on line calculator could you suggest??
    Steve from NY.

    Steve:
    ... and if you want an online option: * Bitrate Calculator *.
    Hope that helps !
      Alberto

  • 128-bit floating point calculations

    I'm looking to buy a used SPARC. Which model is the oldest that provides
    C or fortran 128-bit floating point calculations? Does every 64-bit CPU
    have 128-bit quad real numbers?
    Ron

    The AMD 64-bit processor does not support 128-bit
    floating numbers. I need a Sparc processor that
    does.And yet your question has just what to do with Java -- why did you create a userid and post this question in the Java forums?
    A response "Does every person have ten fingers?"
    shows me that you don't know much about writting
    computer programs that have more than 16 significant
    decimal digits.I wouldn't infer that - but now that you've proven to be a whiny little snot, I'm sure everyone is just going to want to help you here.

  • Bit Calculator - Criticize please

    After teaching myself basic java, I've created my first useful java app. A bit calculator.
    first off what data type should i be using?? I used a Float type.
    Second any critisizm on my code is welcomed. change it and make it your own. I will only learn from it.
    Third I compared it to a Perl bitcalculator which i find superior to the one I've created. http://www.matisse.net/bitcalc/ Is it fair to compare the two? Perl I assume you don't have to choose the data type.
    I challenge you to improve my code.
    Part 2 of my question is that i sometimes see multiple class files for the same program. Can anybody point me to a good tutorial that would explain when i should use more than 1 class file and why I should.
    thanks in advance amigos.
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class BitCalculator extends JApplet implements ActionListener {
    private JButton but1;
    private JComboBox combo1;
    private JTextField textfield1;
    private JLabel label1;
    private float size;
    private String s;
    private double intBitsSize;
      public void init() {
          Container content = getContentPane();
         content.setLayout(new BorderLayout());
        JPanel jp1 = new JPanel();
        JPanel jp2 = new JPanel();
        but1= new JButton("Calculate");
        but1.addActionListener(this);
        textfield1= new JTextField(10);
        label1 = new JLabel();
        combo1 = new JComboBox();
        combo1.addItem("Bits");
        combo1.addItem("Bytes");
        combo1.addItem("Kilobits");
        combo1.addItem("Kilobytes");
        combo1.addItem("Megabits");
        combo1.addItem("Megabytes");
        combo1.addItem("Gigabits");
        combo1.addItem("Gigabytes");
        content.add (jp1,BorderLayout.NORTH);
        content.add (jp2,BorderLayout.CENTER);
        //jp1.setBackground(Color.white);
        jp1.setLayout(new FlowLayout());
        jp1.add(textfield1);
        jp1.add(combo1);
        jp1.add(but1);
        jp2.add(label1);
    //content.setVisible(false);
    public void actionPerformed(ActionEvent e){
          s = (String)combo1.getSelectedItem();
            size = Integer.parseInt(textfield1.getText());
         // label1.setText(size + " " + s);
            if (s=="Gigabytes"){
                size = size * 1024* 1024 * 1024 * 8;
               doCalculate (size);
         else if (s=="Gigabits"){
             size = size * 1024* 1024 * 1024;
               doCalculate (size);
         else if (s=="Megabytes"){
                size = size * 1024* 1024 * 8;
               doCalculate (size);
         else if (s=="Megabits"){
             size = size * 1024* 1024;
               doCalculate (size);
         else if (s=="Kilobytes"){
                size = size * 1024* 8;
               doCalculate (size);
         else if (s=="Kilobits"){
             size = size * 1024* 1024;
               doCalculate (size);
         else if (s=="Bytes"){
                size = size * 8;
               doCalculate (size);
            else if (s=="Bits"){
             doCalculate(size);
    public void doCalculate( float number){
       String strFinal;
       strFinal = "<html>" + ("Bits - " + number) + "<br>";
       strFinal = strFinal + ("Bytes - " + (number/8) + "<br>" );
       strFinal = strFinal + ("Kilobits - " + (number/1024)) + "<br>";
       strFinal = strFinal + ("Kilobytes - " + (number/8/1024)) + "<br>";
       strFinal = strFinal + ("Megabits - " + (number/1024/1024)) + "<br>";
       strFinal = strFinal + ("Megabytes - " + (number/8/1024/1024)) + "<br>";
       strFinal = strFinal + ("Gigabits - " + (number/1024/1024/1024)) + "<br>";
       strFinal = strFinal + ("Gigabytes - " + (number/8/1024/1024/1024)) + "</html>";
       label1.setText(strFinal);
    }

    Just for fun, I reworked your code. This is my solution:
    package server;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class BitCalculator extends JApplet implements ActionListener {
    private JButton but1;
    private JComboBox combo1;
    private JTextField textfield1;
    private JLabel label1;
      enum BitSizes{
           Bits{
                public long getSize(){ return 1;}
           Bytes{
                public long getSize(){ return 8;}
           Kilobits{
                public long getSize(){ return 1024;}
           Kilobytes{
                public long getSize(){ return 8 * 1024;}
           Megabits{
                public long getSize(){ return 1024 * 1024;}
           Megabytes{
                public long getSize(){ return 8 * 1024 * 1024;}
           Gigabits{
                public long getSize(){ return 1024 * 1024 * 1024;}
           Gigabytes{
                public long getSize(){ return 8 * 1024 * 1024 * 1024;}
           public abstract long getSize();
      public void init() {
          Container content = getContentPane();
         content.setLayout(new BorderLayout());
        JPanel jp1 = new JPanel();
        JPanel jp2 = new JPanel();
        but1= new JButton("Calculate");
        but1.addActionListener(this);
        textfield1= new JTextField(10);
        label1 = new JLabel();
        combo1 = new JComboBox();
        for(BitSizes bitSize : BitSizes.values()){
             combo1.addItem(bitSize.name());
        content.add (jp1,BorderLayout.NORTH);
        content.add (jp2,BorderLayout.CENTER);
        //jp1.setBackground(Color.white);
        jp1.setLayout(new FlowLayout());
        jp1.add(textfield1);
        jp1.add(combo1);
        jp1.add(but1);
        jp2.add(label1);
    //content.setVisible(false);
    public void actionPerformed(ActionEvent e){
          String selection = (String)combo1.getSelectedItem();    
         final BitSizes selectedSize;
         for(BitSizes bitSize : BitSizes.values()){
              if(bitSize.name().equals(selection)){
                   selectedSize = bitSize;
                   long number = Long.parseLong(textfield1.getText());
                  number *= selectedSize.getSize();
                  doCalculate(number);
                   return;
    public void doCalculate(long number){
          StringBuilder stringBuilder = new StringBuilder();
          stringBuilder.append("<html>");
          for(BitSizes bitSize : BitSizes.values()){
               stringBuilder.append(bitSize.name());
               stringBuilder.append(" - ");
               stringBuilder.append(number / bitSize.getSize());
               stringBuilder.append("<br>");
          stringBuilder.append("</html>");
          label1.setText(stringBuilder.toString());
    }As you can see, it is not really shorter than your solution (and it still contains some flaws. long is just not big enough for the full scale), but the complexity is moved to a completely different location. All specific information now lies within the enum, everything else is just processing it.
    The advantage of this is, that you can easily expand your program without repeating similar code.

Maybe you are looking for

  • I want to watch my blu ray on my ps3 through the imac 27 new generation. how.   thank you

    I want to watch my blue ray on my ps3 through the iMac 27 new generation. how can I do that?   thank you

  • .java files in J2EE

    Where do I find files like HttpServlet.java in the j2ee 1.3.1 download? I installed into c:\j2sdkee1.3.1 on Windows 2000. Thanks.

  • Security in oracle

    Hello, I'm planning to write my bachelor thesis and i'm writing about Security in Oracle database. I heard that security is an audit subject and it's interesting to talk about security. I wanna know what can i do at the practice part of my thesis? I

  • Method to create Player directly from the mp3 bytes array

    I was checking JMF and didn't find any method to play a mp3 informing its byte array Wouldn't it be an interesting method ? Ok, URL is much easier, but I am talking about ID3 files that has sequences of mp3 chuncks in the same file... Anyone knows a

  • Assigning CoCd to Controlling areas

    Hi, I have 4 company codes in 4 different countries with different currencies. Should i have 4 controlling areas or can i have just one controlling area what is more benificail. Appreciate any response Shine