Showing posts with label Key. Show all posts
Showing posts with label Key. Show all posts

Monday, 20 August 2012

JPA Primary Keys, Composite and Unique

This post illustrates JPA entity key, be them unique or composite. The code examples are available from Github in the JPA directory.

Unique Key

An entity can used a simple key made of a unique field. The only requirement is to annotate this field with @Key. The set of allowed types for unique keys is:

  boolean Boolean
  byte Byte
  char Character
  int Integer
  long Long
  short Short

  String
  BigInteger
  BigDecimal

  @Temporal(TemporalType.DATE)
  java.util.Date
  java.sql.Date
  java.math.BigDecimal
  java.math.BigInteger

  // Don't - Not recommended
  double Double
  float Float

Generated Value Strategy

The @GeneratedValue annotation can be used to specify an id generation strategy via a GenerationType. A sequence name can be specified using the proper annotation property.

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private long id; 

Composite Key

Here is an example of a composite key:
/**
 * Composite key must implement Serializable
 * and must be public.
 */
@AutoProperty
public class CompositeKey implements Serializable {

    // Must be public or protected
    public String s;
    public long l;

    // Default public parameter-less
    // constructor is required
    public CompositeKey() { }

    // equals() must be implemented
    @Override
    public boolean equals(Object o) {
        return Pojomatic.equals(this, o);
    }

    // hashCode() must be implemented
    @Override
    public int hashCode() {
        return Pojomatic.hashCode(this);
    }

    @Override
    public String toString() {
        return Pojomatic.toString(this);
    }

}
Using @EmbeddedId:
@Entity
public class WithEmbeddedId {

    @EmbeddedId
    private CompositeKey id;

    private String data;

    // Setter & Getter

}
The entity needs to declare the composite key with @EmbeddedId.

Using @IdClass:
@Entity
@IdClass(CompositeKey.class)
public class WithIdClass {

    @Id
    String s;

    @Id
    long l;

    private String someData;

    public WithIdClass() { }

    // Setter & Getter

}
With @IdClass, the class must declare the @Id fields matching the composite key fields.

Sunday, 19 August 2012

AES 256 Symmetric Encryption with BouncyCastle

Java provides the Cipher class to perform symmetric encryption. Several algorithms are available, but unfortunately, not all key sizes are allowed. The recommended solution is to install the unlimited JCE version. However, this is not a portable solution.

Trying to perform AES encryption with a 256 bit key triggers an error. A portable solution is to use BouncyCastle's library instead:
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.46</version>
</dependency>
The following class illustrates how BounceCastle can be used for AES:
public class AESBouncyCastle {

    private final BlockCipher AESCipher = new AESEngine();

    private PaddedBufferedBlockCipher pbbc;
    private KeyParameter key;

    public void setPadding(BlockCipherPadding bcp) {
        this.pbbc = new PaddedBufferedBlockCipher(AESCipher, bcp);
    }

    public void setKey(byte[] key) {
        this.key = new KeyParameter(key);
    }

    public byte[] encrypt(byte[] input)
            throws DataLengthException, InvalidCipherTextException {
        return processing(input, true);
    }

    public byte[] decrypt(byte[] input)
            throws DataLengthException, InvalidCipherTextException {
        return processing(input, false);
    }

    private byte[] processing(byte[] input, boolean encrypt)
            throws DataLengthException, InvalidCipherTextException {

        pbbc.init(encrypt, key);

        byte[] output = new byte[pbbc.getOutputSize(input.length)];
        int bytesWrittenOut = pbbc.processBytes(
            input, 0, input.length, output, 0);

        pbbc.doFinal(output, bytesWrittenOut);

        return output;

    }

}
It can be used as following:
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey sk = kg.generateKey();

AESBouncyCastle abc = new AESBouncyCastle();
abc.setPadding(new PKCS7Padding());
abc.setKey(sk.getEncoded());

String secret = "This is a secret message!";
System.out.println(secret);
byte[] ba = secret.getBytes("UTF-8");

byte[] encr = abc.encrypt(ba);
System.out.println("Encrypted : "
    + Hex.encodeHexString(encr));
byte[] retr = abc.decrypt(encr);

if ( retr.length == ba.length ) {
    ba = retr;
} else {
    System.arraycopy(retr, 0, ba, 0, ba.length);
}

String decrypted = new String(ba, "UTF-8");
System.out.println(decrypted);
The above starts by creating an AES 256 private key (more about private key generation here). Next, a padding is set. From the Javadoc, available paddings are: ISO10126d2, ISO7816d4, PKCS7, TBC, X923 and ZeroByte.

After retrieving the decrypted byte array, we check for its length, because AES operates with blocks of bytes. The original message length may not be a multiple of these block length.

The generated output is:
This is a secret message!
Encrypted : 6d204e3e52daee09800ba6fd9080653dad04a3d4725f3502b78a89b2150e1f63
This is a secret message!
The Hex class is an Apache Commons tool.

Saturday, 18 August 2012

AES 128-192-256 Private Key Generation in Java

Java delivers a standard tool called KeyGenerator to generate private keys. The following describes how to generate private (or symmetric) keys for AES (other algorithms are available too):
KeyGenerator kg = KeyGenerator.getInstance("AES");
SecretKey sk;

kg.init(128);
sk = kg.generateKey();
System.out.print("AES 128 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));

kg.init(192);
sk = kg.generateKey();
System.out.print("AES 192 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));

kg.init(256);
sk = kg.generateKey();
System.out.print("AES 256 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));
The generated output is:
AES 128 - 737677d940a988b04d99667406ea0d18
AES 192 - 727f44e3052aa4a6a72e385b9e9b421592f9ca1f5779925c
AES 256 - 383062669b33959fd8b57d93401c18c9d85d588ee90bb4ee82e486ac90620264
The Hex class is an Apache Commons tool.

Monday, 13 August 2012

How to Generate a Public Private Key Pair in Java?

Java offers features to generate public/private key pairs. The list of available algorithms is: DiffieHellman (Diffie-Hellman), DSA (Digital Signature Algorithm), RSA (Rivest, Shamir and Adleman, and EC (Elliptic Curve).
public static KeyPair generateKeyPair(String algorithm, int keysize)
       throws NoSuchAlgorithmException {

   KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
   keyGen.initialize(keysize);

   return keyGen.genKeyPair();

}
Considering the above method and the following:
KeyPair kp = generateKeyPair("RSA", 1200);

System.out.println(kp.getPublic());
System.out.println(kp.getPrivate());
The generated output is:
Sun RSA public key, 1200 bits
  modulus:          9869434664406071422397837320764405182639187275838230993850845712119792960719253107137826291378531088798687188823076370201242339197879199249064933049166569948405393151733986369838996220598856887300012669754735304190978435430220593101694644244314877878605534096811338814490286832890418449631509846730240623970004851838612509884903198786095740146540225924110683179
public exponent: 65537
Sun RSA private CRT key, 1200 bits
  modulus:          9869434664406071422397837320764405182639187275838230993850845712119792960719253107137826291378531088798687188823076370201242339197879199249064933049166569948405393151733986369838996220598856887300012669754735304190978435430220593101694644244314877878605534096811338814490286832890418449631509846730240623970004851838612509884903198786095740146540225924110683179
  public exponent:  65537
  private exponent: 1582133460247649211341863052809113033077609617772501866447914690198369544613218077476692601388877239100340381857198839515605719145107631831037065880564322197811115254773902693158497157951570638902393594757932655753965475860517442661157051743687056572748027450726509909507973409417657097270834672334740647227515714009141606345006585607294455971993731635917157153
  prime p:          3256149439130022408436310311885111793464195858196258233187003768668905068326967709908800218408588778082838728236339782637613895789098072922267211467323843674447148299706221862611571
  prime q:          3031014039405693160199592278696049712727614456472639744562120993703109441692657536297714688397058789187582744250860764288923138208010664879900484905834875292341824001685681393062249
  prime exponent p: 651011277612961893552359339253103129983999242106681288881842476476931551799567540518104418295127008548139766179116532216925627912851550261691369331161699859106779135008478036312303
  prime exponent q: 2314803602335998723791900653692051576540424968504998578742980573658152351590081974292947767962543135291937438889479715480185116658515674930251600928055012332834896823296306504785977
  crt coefficient:  1264506160423420660013941104026558245174285118352499963549245021823942032361239666081851546710377637751263799087922801195636712628068424427135886836129544889379051273632748195244747

Monday, 30 July 2012

Java: How to Iterate Through a Map?

There are multiple ways to iterate through a Java Map. Assuming the following map declaration:
Map<String,Object> m = new HashMap<String,Object>();
Here are the mutliple ways to iterate it.

Iterate on Keys and Values

// With an Iterator (with Generics)
Iterator<Entry<String, Object>> iterator
    = m.entrySet().iterator();

while ( iterator.hasNext() ) {
    Entry<String, Object> item = iterator.next();
    System.out.println(item.getKey()
      + " - " + item.getValue());
}

// Without an Iterator (without Generics)
Iterator iterator2 = m.entrySet().iterator();
while ( iterator2.hasNext() ) {
    Entry item = (Entry) iterator.next();
    System.out.println(item.getKey()
      + " - " + item.getValue());
}

// Using For Each (with Generics)
for ( Entry<String, Object> item : m.entrySet() ) {
    System.out.println(item.getKey()
      + " - " + item.getValue());
}

// Using For Each (without Generics)
for ( Entry item : m.entrySet() ) {
    System.out.println(item.getKey()
      + " - " + item.getValue());
}

// Inefficient (fetching value from key)
for ( String key : m.keySet() ) {
    System.out.println(key + " - " + m.get(key));
}

Iterate on Keys Only

for ( String key : m.keySet() ) {
    System.out.println(key);
}

Iterate on Values Only

for ( Object value : m.values() ) {
    System.out.println(value);
}