Sunday, 5 July 2015

R: unserialize : unserialize serialized data

By using “unserialize” function, you can unserialize, serialized data.

Syntax
unserialize(connection, refhook = NULL)

> data <- 1:50
> data
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
> 
> x <- serialize(data, NULL)
> x
  [1] 58 0a 00 00 00 02 00 03 02 00 00 02 03 00 00 00 00 0d 00 00 00 32 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00
 [70] 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00 19 00 00 00 1a 00 00 00 1b 00 00 00 1c 00 00 00 1d
[139] 00 00 00 1e 00 00 00 1f 00 00 00 20 00 00 00 21 00 00 00 22 00 00 00 23 00 00 00 24 00 00 00 25 00 00 00 26 00 00 00 27 00 00 00 28 00 00 00 29 00 00 00 2a 00 00 00 2b 00 00 00 2c 00 00 00 2d 00 00 00 2e 00
[208] 00 00 2f 00 00 00 30 00 00 00 31 00 00 00 32
> 
> 
> x <- unserialize(x)
> x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50



Prevoius                                                 Next                                                 Home

Export public key certificate from keystore

Use following command to export public key certificate from keystore.

Syntax
keytool -export -keystore key_store_file_name -alias certificate_name -file certificate_name.cer

To extract certificate1 from keystore.jks, use following command.

keytool -export -keystore /Users/harikrishna_gurram/keystore.jks -alias certificate1 -file Example.cer

$ keytool -export -keystore /Users/harikrishna_gurram/keystore.jks -alias certificate1 -file Example.cer
Enter keystore password: 
Certificate stored in file <Example.cer>

Use following command to view contents of Example.cer.

openssl x509 -inform der -in Example.cer -noout –text

$ openssl x509 -inform der -in Example.cer -noout -text
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 312551854 (0x12a129ae)
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=IN, ST=Karnataka, L=Bangalore, O=Self learn Java, OU=Self learn Java, CN=Hari Krishna Gurram
        Validity
            Not Before: Jul  3 07:09:19 2015 GMT
            Not After : Jul 10 07:09:19 2015 GMT
        Subject: C=IN, ST=Karnataka, L=Bangalore, O=Self learn Java, OU=Self learn Java, CN=Hari Krishna Gurram
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (2048 bit)
                Modulus (2048 bit):
                    00:bb:23:ca:60:a1:64:05:cc:94:ea:be:3e:a1:84:
                    bb:ed:82:42:2e:58:4f:06:ec:6d:db:78:70:4d:7b:
                    0d:d9:17:fd:90:9e:56:3e:fc:02:f2:17:e1:89:03:
                    ff:0a:4e:c3:4c:b9:5d:b9:fb:1a:2b:ea:a5:c5:fb:
                    58:61:c7:7c:f8:44:29:dc:0a:93:fa:61:5c:e5:b5:
                    b2:f9:9c:0b:1b:52:32:53:28:7e:79:72:d5:62:2b:
                    f7:15:e9:8c:dd:8a:4a:42:27:51:1b:36:f3:8b:3b:
                    28:de:c5:30:6e:4e:50:d0:11:11:27:41:01:33:84:
                    a5:7b:2d:33:9b:64:bf:2e:c2:c4:0f:e0:3b:c4:a3:
                    2d:2f:de:46:4b:7b:ac:71:63:e4:13:a9:27:e8:6a:
                    2e:d8:55:ee:18:d3:f1:5d:1e:cf:3a:59:d9:9c:4d:
                    17:49:f5:47:da:a4:bb:6f:33:1f:7c:6b:51:9b:ff:
                    af:a6:d9:9d:c7:5a:94:09:7a:61:72:08:ea:18:83:
                    ab:57:f0:1d:e2:89:57:41:c5:cd:6e:4f:0f:f6:99:
                    d1:2b:c1:b9:e5:87:fb:4c:c8:5c:b3:4e:a9:d0:a2:
                    3a:8e:0b:67:b1:d7:6e:8f:c5:3e:bc:3e:2e:28:3b:
                    a2:31:4d:ab:9a:10:b8:97:43:78:9c:0a:46:03:cf:
                    66:3b
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                AF:12:09:BA:52:E9:E2:DB:F7:92:BD:93:C2:31:FC:81:44:EA:7C:32
    Signature Algorithm: sha256WithRSAEncryption
        7e:4b:00:da:81:08:99:98:1e:d4:25:35:8f:90:3c:63:f2:80:
        69:f7:ea:bf:03:a9:af:1e:aa:7f:37:7b:49:b8:a8:a0:55:3e:
        ed:2d:74:46:dc:2c:1a:ee:fb:9c:af:0d:c7:7d:b2:0f:e6:e4:
        75:bb:11:4f:97:2d:51:78:de:93:50:d2:cc:cb:20:7f:39:a3:
        7f:8f:a4:da:9e:bc:65:cd:69:9a:40:e0:d8:ce:2b:46:95:e8:
        05:fc:a4:40:f5:71:53:9b:bd:37:6f:4a:ef:26:04:d5:8c:1f:
        79:b7:ef:97:f2:45:d4:bb:99:60:e5:3c:12:46:f2:00:35:09:
        e8:37:20:b7:19:af:d7:4f:d9:f9:f8:62:03:6d:f2:10:83:e1:
        49:49:2d:94:bf:44:8c:4b:b9:df:3e:6b:a6:16:1e:9d:56:4e:
        9c:db:52:a9:5c:2f:27:28:85:33:a7:87:a5:b3:57:e7:87:bf:
        dd:7d:4a:89:c9:b9:e8:ea:01:f0:37:a6:77:b0:1b:05:c5:37:
        fc:05:63:bc:de:ac:0b:74:56:b6:e2:20:5c:38:9f:b4:54:8c:
        8f:58:68:72:30:d6:5e:51:be:c6:7e:ce:3f:b5:13:a5:4b:9f:
        0e:55:1a:be:10:a4:90:a3:fd:dd:a3:db:25:23:fe:f6:99:4f:
        8f:cf:3f:72


Public, private key generation in Java

In secure data communications, data is encrypted using a key, to provide confidentiality. There are two types of encryptions.

a.   Symmetric key encryption
b.   Public key encryption

a. Symmetric key Encryption
In Symmetric key encryption, data is encrypted and decrypted using same key, called secret key.

b. Public key encryption
It is also known as asymmetric key encryption. It uses two keys.
1.   Public key
2.   Private key
Every one knows public key, but only recipient knows private key. Suppose A wants to send a message M to B, then A encrypts M with B’s public key and send. At recipient end B decrypts message with his private key.

Each approach has it’s own advantages and disadvantages.

1.   Symmetric key encryption is easy to implement and faster. But main problem is both parties (sender and receiver) must exchange the key in secure way.
2.   Public key encryption works slow, but solves key exchange problem. In real world both the approaches combined to achieve more security and performance (See HTTPS).

In this post, I am going to explain how to generate public and private keys.

“java.security.KeyPairGenerator” class is used to generate public and private key pair. KeyPairGenerator class provides “getInstance” method, which takes algorithm name as argument and generate public and private key pairs specific to the algorithm supplied.

Following are the algorithms that java provides.
Algorithm
Description
Generates keypairs for the Diffie-Hellman KeyAgreement algorithm.
Generates keypairs for the Digital Signature Algorithm.
Generates keypairs for the RSA algorithm (Signature/Cipher).
Generates keypairs for the Elliptic Curve algorithm.

KeyPairGenerator class provides 3 forms of getInstance method.
getInstance(String algorithm)
getInstance(String algorithm, Provider provider)
getInstance(String algorithm, String provider)

First method returns KeyPairGenerator instance for specific algorithm mentioned in above table. Second and 3rd methods returns a new KeyPairGenerator object encapsulating the KeyPairGeneratorSpi implementation from the specified Provider object.

Once you got the instance of KeyPairGenerator, you can initialize KeyPairGenerator with specified parameter set. There are two ways to initialize KeyPairGenerator.

a. Algorithm-Independent initialization
Following methods are used to initialize KeyPairGenerator to initialize in Algorithm independent manner.

initialize(int keysize)
Initializes the key pair generator for a certain keysize using a default parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

initialize(int keysize, SecureRandom random)
Initializes the key pair generator for a certain keysize with the given source of randomness (and a default parameter set).
        
b. Algorithm-specific implementation
Following methods are used to initialize KeyPairGenerator to initialize in Algorithm dependent manner.

initialize(AlgorithmParameterSpec params)
Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

initialize(AlgorithmParameterSpec params, SecureRandom random)
Initializes the key pair generator with the given parameter set and source of randomness.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class PublicKeyUtil {

 public static KeyPair getKeyPair(String algorithm)
   throws NoSuchAlgorithmException {
  KeyPairGenerator keyPairGenerator = KeyPairGenerator
    .getInstance(algorithm);
  return keyPairGenerator.generateKeyPair();
 }

 public static PublicKey getPublicKey(KeyPair keyPair) {
  return keyPair.getPublic();
 }

 public static PrivateKey getPrivateKey(KeyPair keyPair) {
  return keyPair.getPrivate();
 }

 /**
  * Convert key to string.
  * 
  * @param key
  * 
  * @return String representation of key
  */
 public static String keyToString(Key key) {
  /* Get key in encoding format */
  byte encoded[] = key.getEncoded();

  /*
   * Encodes the specified byte array into a String using Base64 encoding
   * scheme
   */
  String encodedKey = Base64.getEncoder().encodeToString(encoded);

  return encodedKey;
 }

 /**
  * Save key to a file
  * 
  * @param key
  *            : key to save into file
  * @param fileName
  *            : File name to store
  */
 public static void saveKey(Key key, String fileName) {
  byte[] keyBytes = key.getEncoded();
  File keyFile = new File(fileName);
  FileOutputStream fOutStream = null;
  try {
   fOutStream = new FileOutputStream(keyFile);
   fOutStream.write(keyBytes);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (fOutStream != null) {
    try {
     fOutStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

}


import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;

import com.sample.PublicKeyUtil;

public class TestPublicKeyUtil {
 public static void main(String args[]) throws NoSuchAlgorithmException {
  KeyPair keyPair = PublicKeyUtil.getKeyPair("RSA");

  String publicKey = PublicKeyUtil.keyToString(PublicKeyUtil
    .getPublicKey(keyPair));
  String privateKey = PublicKeyUtil.keyToString(PublicKeyUtil
    .getPrivateKey(keyPair));

  System.out.println(publicKey);
  System.out.println(privateKey);
 }
}

Referred Articles

Related Articles


Saturday, 4 July 2015

R : Serialize object

Serialization is the process of converting object state into sequence of bytes. de-Serialization is a process to bring back the object’s state from bytes. You can serialize object using serialize function.

Syntax
serialize(object, connection, ascii, xdr = TRUE,
          version = NULL, refhook = NULL)


Parameter
Description
object
R object to serialize
connection
Represents open connection
ascii
If ascii is TRUE or NA, then ascii representation writeen, else binary one
xdr
A logical value: if a binary representation is used, should a big-endian one (XDR) be used?
version
The workspace format version to use. NULL specifies the current default version (2). Versions prior to 2 are not supported, so this will only be relevant when there are later versions.
refhook
A hook function to handle reference objects.


> data <- 1:50
> data
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
> 
> x <- serialize(data, NULL)
> x
  [1] 58 0a 00 00 00 02 00 03 02 00 00 02 03 00 00 00 00 0d 00 00 00 32 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00
 [70] 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00 19 00 00 00 1a 00 00 00 1b 00 00 00 1c 00 00 00 1d
[139] 00 00 00 1e 00 00 00 1f 00 00 00 20 00 00 00 21 00 00 00 22 00 00 00 23 00 00 00 24 00 00 00 25 00 00 00 26 00 00 00 27 00 00 00 28 00 00 00 29 00 00 00 2a 00 00 00 2b 00 00 00 2c 00 00 00 2d 00 00 00 2e 00
[208] 00 00 2f 00 00 00 30 00 00 00 31 00 00 00 32
> 
> 
> x <- unserialize(x)
> x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50




Prevoius                                                 Next                                                 Home