Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, April 18, 2014

RSA Encryption/Decryption - Part 2

My previous post on RSA details about basics of RSA and how to generate public and private key in java.


Encryption in Java



         public static byte[] encrypt(String text, PublicKey key) {
  byte[] cipherText = null;
  try {
   // get an RSA cipher object and print the provider
   final Cipher cipher = Cipher.getInstance(ALGORITHM);
   // encrypt the plain text using the public key
   cipher.init(Cipher.ENCRYPT_MODE, key);
   cipherText = cipher.doFinal(text.getBytes());

  } catch (Exception e) {
   e.printStackTrace();
  }
  return cipherText;
 }




Decryption in Java



         public static String decrypt(byte[] text, PrivateKey key) {
  byte[] decryptedText = null;
  try {
   // get an RSA cipher object and print the provider
   final Cipher cipher = Cipher.getInstance(ALGORITHM);

   // decrypt the text using the private key
   cipher.init(Cipher.DECRYPT_MODE, key);
   decryptedText = cipher.doFinal(text);

  } catch (Exception ex) {
   ex.printStackTrace();
  }

  return new String(decryptedText);
 }


RSA Encryption/Decryption - Part 1


What is Cryptography?

Cryptography is the practice or techniques for securing a communication in the presence of others. It is about constructing and analyzing protocols that overcome the influence of adversaries and are related to various aspects in information security such as data confidentiality, data integrity, authentication.

What is Encryption?

Encryption is one of the ways to achieve data security by translation of data into secret code or unreadable format called cipher text.

What is Decryption?

Decryption is the reverse of encryption that is converting cipher text to its original message, i.e. plain or readable text.

What is RSA?

RSA is one of the widely used public key cryptography for secure data communication. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman, who first publicly described it in 1978. Public key cryptohraphy is also called Asymmetric cryptography which requires two separate keys, one which is private key (secret key) and another which is public key. the public key is used to encrypt text while private key is used to decrypt text.

How to generate public/private key in java?




public static void generateKey(String private_key, String public_key) {
  try {
   final KeyPairGenerator keyGen = KeyPairGenerator
     .getInstance(ALGORITHM);
   keyGen.initialize(512);
   final KeyPair key = keyGen.generateKeyPair();

   File privateKeyFile = new File(private_key);
   File publicKeyFile = new File(public_key);

   // Create files to store public and private key
   if (privateKeyFile.getParentFile() != null) {
    privateKeyFile.getParentFile().mkdirs();
   }
   privateKeyFile.createNewFile();

   if (publicKeyFile.getParentFile() != null) {
    publicKeyFile.getParentFile().mkdirs();
   }
   publicKeyFile.createNewFile();

   // Saving the Public key in a file
   ObjectOutputStream publicKeyOS = new ObjectOutputStream(
     new FileOutputStream(publicKeyFile));
   publicKeyOS.writeObject(key.getPublic());
   publicKeyOS.close();

   // Saving the Private key in a file
   ObjectOutputStream privateKeyOS = new ObjectOutputStream(
     new FileOutputStream(privateKeyFile));
   privateKeyOS.writeObject(key.getPrivate());
   privateKeyOS.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

To call

generateKey("c:/rsa/key/public.key", "c:/rsa/key/private.key");
My next post on RSA details about how to encrypt and decrypt in java using  public and private key generated above.

Saturday, August 20, 2011

Better Faster Lighter Java

The section is designed to help you make the most effective use of the Java™ programming language and its fundamental libraries, java.lang, java.util, and, to a lesser extent, java.util.concurrent and java.io. It discusses other libraries from time to time, but it does not cover graphical user interface programming, enterprise APIs, or mobile devices. Section consists of 9 items, each of which conveys one rule. The rules capture practices generally held to be beneficial by the best and most experienced programmers. Many new features were added to the platform in Java 5. Most of the items here try to cover these features in some way.
  1. Minimize the scope of local variablesBy minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. Declaring a local variable prematurely can cause its scope not only to extend too early, but also to end too late. The scope of a local variable extends from the point where it is declared to the end of the enclosing block. If a variable is declared outside of the block in which it is used, it remains visible after the program exits that block. If a variable is used accidentally before or after its region of intended use, the consequences can be disastrous. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
    // Preferred idiom for iterating over a collection
    for (Element e : c) {
    doSomething(e);
    }
    Here is another loop idiom that minimizes the scope of local variables:
    for (int i = 0, n = expensiveComputation(); i < n; i++)
    {
    doSomething(i);
    }
    A final technique to minimize the scope of local variables is to keep methods small and focused. If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one for each activity.
  2. Know and use the librariesDon’t reinvent the wheel. If you need to do something that seems like it should be reasonably common, there may already be a class in the libraries that does what you want. If there is, use it; if you don’t know, check. Generally speaking, library code is likely to be better than code that you’d write and is likely to improve over time. Advantages of using library are:- Firstly by using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you. A second advantage of using the libraries is that you don’t have to waste your time writing ad hoc solutions to problems that are only marginally related to your work. Third advantage of using standard libraries is that their performance tends to improve over time, with no effort on your part. Because many people use them and because they’re used in industry-standard benchmarks also. Many of the Java platform libraries have been rewritten over the years, sometimes repeatedly, resulting in dramatic performance improvements. A final advantage of using the standard libraries is that you place your code in the mainstream. Such code is more easily readable, maintainable, and reusable by the multitude of developers.

  3. Prefer primitive types to boxed primitivesJava has a two-part type system, consisting of primitives, such as int, double, and boolean, and reference types, such as String and List. Every primitive type has a boxed primitives corresponding to it, like int, double, and boolean are Integer, Double, and Boolean. To summarize, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
  4. Avoid strings where other types are more appropriateStrings are designed to represent text, and they do a fine job of it. Because strings are so common and so well supported by the language, there is a natural tendency to use strings for purposes other than those for which they were designed. This item discusses a few things that you shouldn’t do with strings.
    • Strings are poor substitutes for other value types.
    • Strings are poor substitutes for enum types.
    • Strings are poor substitutes for aggregate types.
    • Strings are poor substitutes for capabilities.
    To summarize, avoid the natural tendency to represent objects as strings when better data types exist or can be written. Used inappropriately, strings are more cumbersome, less flexible, slower, and more error-prone than other types. Types for which strings are commonly misused include primitive types, enums, and aggregate types.
  5. Beware the performance of string concatenationThe string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.
    // Inappropriate use of string concatenation - Performs horribly!
    public String statement() {
    String result = "";
    for (int i = 0; i < numItems(); i++)
    result += lineForItem(i);
    // String concatenation return result;
    }
    This method performs abysmally if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete. The difference in performance is dramatic.
  6. Use loggingWhile building an application or doing debugging to trace out the control flow to rectify a bug always use standard logging libraries. Below are wrong and right way do keep control over logging.
    WRONG
    public void bar() {
    try {
    //doSomething()
    }
    catch (JMSException e) {
    System.out.println("exception occurred"); e.printStackTrace();
    }
    finally {
    System.out.println("cleaning up");
    }
    }
    RIGHT
    public void bar() {
    try {
    // ...
    }
    catch (JMSException e) {
    logger.log(Level.WARNING, "JMS Problem", e);
    } finally {
    logger.info("cleaning-up");
    }
    }

    Wrap complex logging expressions into conditions
    if (logger.isDebugEnabled()) {
    logger.debug("Message: " + object.calculateSomething() + ", count=" + cnt);
    }
  7. Code Formatting and stylingThere are 2 standard plugins available for Eclipse PMD and CheckStyle which comes to rescue
    • CheckStyle
      • http://checkstyle.sourceforge.net/index.html
      • Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard.
      • Checkstyle will help you during your programming by checking your coding style i.e braces, naming etc. Simple things but very numerous!
      • Checkstyle is highly configurable and can be made to support almost any coding standard.
      • Historically it's main functionality has been to check code layout issues
      • Checkstyle is most useful if you integrate it in your build process or your development environment.
    • PMD
      • http://pmd.sourceforge.net/
      • PMD scans Java source code and looks for potential problems like:
        • Possible bugs - empty try/catch/finally/switch statements
        • Dead code - unused local variables, parameters and private methods
        • Suboptimal code - wasteful String/StringBuffer usage
        • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops Duplicate code - copied/pasted code means copied/pasted bugs
      • PMD is also able to point out questionable coding practices and its output is generally more relevant and useful.
      • PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the clone function. Simply, PMD will check your programming style
      • PMD to find problematic code areas and next refactoring targets
    Checkstyle and PMD both are good at checking coding standards and are easy to extend. But PMD has additional rules to check for cyclomatic complexity,Npath complexity,etc which allows you write healthy code.
  8. Adhere to generally accepted naming conventions
    The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification. Loosely speaking, naming conventions fall into two categories: typographical and grammatical. There are only a handful of typographical naming conventions, covering packages, classes, interfaces, methods, fields, and type variables. You should rarely violate them and never without a very good reason. If an API violates these conventions, it may be difficult to use. If an implementation violates them, it may be difficult to maintain. In both cases, violations have the potential to confuse and irritate other programmers who work with the code and can cause faulty assumptions that lead to errors.

Monday, June 13, 2011

Better Faster Lighter Java

The section is designed to help you make the most effective use of the Java™ programming language and its fundamental libraries, java.lang, java.util, and, to a lesser extent, java.util.concurrent and java.io. It discusses other libraries from time to time, but it does not cover graphical user interface programming, enterprise APIs, or mobile devices. Section consists of 9 items, each of which conveys one rule. The rules capture practices generally held to be beneficial by the best and most experienced programmers. Many new features were added to the platform in Java 5. Most of the items here try to cover these features in some way.
  1. Minimize the scope of local variablesBy minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. Declaring a local variable prematurely can cause its scope not only to extend too early, but also to end too late. The scope of a local variable extends from the point where it is declared to the end of the enclosing block. If a variable is declared outside of the block in which it is used, it remains visible after the program exits that block. If a variable is used accidentally before or after its region of intended use, the consequences can be disastrous. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
    // Preferred idiom for iterating over a collection
    for (Element e : c) {
    doSomething(e);
    }
    Here is another loop idiom that minimizes the scope of local variables:
    for (int i = 0, n = expensiveComputation(); i < n; i++)
    {
    doSomething(i);
    }
    A final technique to minimize the scope of local variables is to keep methods small and focused. If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one for each activity.
  2. Know and use the librariesDon’t reinvent the wheel. If you need to do something that seems like it should be reasonably common, there may already be a class in the libraries that does what you want. If there is, use it; if you don’t know, check. Generally speaking, library code is likely to be better than code that you’d write and is likely to improve over time. Advantages of using library are:- Firstly by using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you. A second advantage of using the libraries is that you don’t have to waste your time writing ad hoc solutions to problems that are only marginally related to your work. Third advantage of using standard libraries is that their performance tends to improve over time, with no effort on your part. Because many people use them and because they’re used in industry-standard benchmarks also. Many of the Java platform libraries have been rewritten over the years, sometimes repeatedly, resulting in dramatic performance improvements. A final advantage of using the standard libraries is that you place your code in the mainstream. Such code is more easily readable, maintainable, and reusable by the multitude of developers.

  3. Prefer primitive types to boxed primitivesJava has a two-part type system, consisting of primitives, such as int, double, and boolean, and reference types, such as String and List. Every primitive type has a boxed primitives corresponding to it, like int, double, and boolean are Integer, Double, and Boolean. To summarize, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
  4. Avoid strings where other types are more appropriateStrings are designed to represent text, and they do a fine job of it. Because strings are so common and so well supported by the language, there is a natural tendency to use strings for purposes other than those for which they were designed. This item discusses a few things that you shouldn’t do with strings.
    • Strings are poor substitutes for other value types.
    • Strings are poor substitutes for enum types.
    • Strings are poor substitutes for aggregate types.
    • Strings are poor substitutes for capabilities.
    To summarize, avoid the natural tendency to represent objects as strings when better data types exist or can be written. Used inappropriately, strings are more cumbersome, less flexible, slower, and more error-prone than other types. Types for which strings are commonly misused include primitive types, enums, and aggregate types.
  5. Beware the performance of string concatenationThe string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.
    // Inappropriate use of string concatenation - Performs horribly!
    public String statement() {
    String result = "";
    for (int i = 0; i < numItems(); i++)
    result += lineForItem(i);
    // String concatenation return result;
    }
    This method performs abysmally if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete. The difference in performance is dramatic.
  6. Use loggingWhile building an application or doing debugging to trace out the control flow to rectify a bug always use standard logging libraries. Below are wrong and right way do keep control over logging.
    WRONG
    public void bar() {
    try {
    //doSomething()
    }
    catch (JMSException e) {
    System.out.println("exception occurred"); e.printStackTrace();
    }
    finally {
    System.out.println("cleaning up");
    }
    }
    RIGHT
    public void bar() {
    try {
    // ...
    }
    catch (JMSException e) {
    logger.log(Level.WARNING, "JMS Problem", e);
    } finally {
    logger.info("cleaning-up");
    }
    }

    Wrap complex logging expressions into conditions
    if (logger.isDebugEnabled()) {
    logger.debug("Message: " + object.calculateSomething() + ", count=" + cnt);
    }
  7. Code Formatting and stylingThere are 2 standard plugins available for Eclipse PMD and CheckStyle which comes to rescue
    • CheckStyle
      • http://checkstyle.sourceforge.net/index.html
      • Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard.
      • Checkstyle will help you during your programming by checking your coding style i.e braces, naming etc. Simple things but very numerous!
      • Checkstyle is highly configurable and can be made to support almost any coding standard.
      • Historically it's main functionality has been to check code layout issues
      • Checkstyle is most useful if you integrate it in your build process or your development environment.
    • PMD
      • http://pmd.sourceforge.net/
      • PMD scans Java source code and looks for potential problems like:
        • Possible bugs - empty try/catch/finally/switch statements
        • Dead code - unused local variables, parameters and private methods
        • Suboptimal code - wasteful String/StringBuffer usage
        • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops Duplicate code - copied/pasted code means copied/pasted bugs
      • PMD is also able to point out questionable coding practices and its output is generally more relevant and useful.
      • PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the clone function. Simply, PMD will check your programming style
      • PMD to find problematic code areas and next refactoring targets
    Checkstyle and PMD both are good at checking coding standards and are easy to extend. But PMD has additional rules to check for cyclomatic complexity,Npath complexity,etc which allows you write healthy code.
  8. Adhere to generally accepted naming conventions
    The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification. Loosely speaking, naming conventions fall into two categories: typographical and grammatical. There are only a handful of typographical naming conventions, covering packages, classes, interfaces, methods, fields, and type variables. You should rarely violate them and never without a very good reason. If an API violates these conventions, it may be difficult to use. If an implementation violates them, it may be difficult to maintain. In both cases, violations have the potential to confuse and irritate other programmers who work with the code and can cause faulty assumptions that lead to errors.