Steps to create a symmetric key in Java

Example description

This example shows the steps to create a symmetric key in Java , and save it in a file through object serialization.

Programming ideas:

(1)       Get the key generator

KeyGenerator kg=KeyGenerator.getInstance("DESede");

Analysis: The KeyGenerator class in Java provides a method to create a symmetric key. Classes in Java generally use the new operator to create objects through the constructor, but the KeyGenerator class does not. It predefines a static method getInstance (), through which an object of type KeyGenerator is obtained. Such a class becomes a factory class or factory.

The parameter of the method getInstance ( ) is of type string, specifying the name of the encryption algorithm. Can be " Blowfish " , " DES ", " DESede ", " HmacMD5 " or " HmacSHA1 " etc. All of these algorithms can implement encryption. We don't care about the details of these algorithms here, as long as we know the characteristics of their use. Among them, " DES " is the most commonly used symmetric encryption algorithm, but it is less secure. Improvements to DES security have resulted in the TripleDES algorithm, " DESede ", that meets current security needs. " Blowfish " has a key length of up to 448 bits and is very secure. " AES " is a new algorithm that replaces the DES algorithm and provides very good security.

(2)       Initialize the key generator

kg.init(168);

Analysis: This step generally specifies the length of the key. If this step is omitted, the default key length is automatically used according to the algorithm. When specifying the length, if the first step key generator uses the " DES " algorithm, the key length must be 56 bits; if it is " DESede ", it can be 112 or 168 bits, of which 112 bits are valid; if " AES " ", can be 128, 192 or 256 bits; if " Blowfish ", it can be a number between 32 and 448 that is divisible by 8 ; " HmacMD5 " and " HmacSHA1 " The default key length is 64 bytes.

(3)       Generate a key

         SecretKey k=kg.generateKey( );

Analysis: Use the generateKey( ) method in the KeyGenerator type object obtained in the first step to obtain the key. Its type is SecretKey type, which can be used for subsequent encryption and decryption.

(4)       Save the key in the file by object serialization

            FileOutputStream  f=new FileOutputStream("key1.dat");

               ObjectOutputStream b=new  ObjectOutputStream(f);

               b.writeObject(k);

Analysis: The writeObject method provided in the ObjectOutputStream class can serialize objects and process them in a stream. Here, the file output stream is passed as a parameter to the constructor of the ObjectOutputStream class, so that the created key will be saved in the file key1.data .

Code and Analysis :

import java.io. *;

import javax.crypto.*;

public class Skey_DES{

 public static void main(String args[])

 throws Exception{

KeyGenerator kg=KeyGenerator.getInstance("DESede");

            kg.init(168);

            SecretKey k=kg.generateKey( );

            FileOutputStream  f=new FileOutputStream("key1.dat");

            ObjectOutputStream b=new  ObjectOutputStream(f);

            b.writeObject(k);

         }

}

Run java   Skey_DES , the file key1.dat will be generated in the current directory, the key contained in it can be used for encryption and decryption using the Triple DES algorithm.

 

 

Store symmetric key in bytes

Example description

2.2.1小节的实例将密钥通过对象序列化方式保存在文件中,在文件中保存的是对象,本实例以另一种方式保存在文件中,即以字节保存在文件中。

编程思路:

Java中所有的密钥类都有一个getEncoded( )方法,通过它可以从密钥对象中获取主要编码格式,其返回值是字节数组。其主要步骤为:

(1)       获取密钥

FileInputStream f=new FileInputStream("key1.dat");

ObjectInputStream b=new ObjectInputStream(f);

Key k=(Key)b.readObject( );

 

分析:该步骤与2.2.1小节的第4步是相对应的,2.2.1小节的第4步将密钥对象以对象流的方式存入文件,而这一步则将文件中保存的对象读取出来以便使用。首先创建文件输入流,然后将其作为参数传递给对象输入流,最后执行对象输入流的readObject( )方法读取密钥对象。由于readObject( )返回的是Object类型,因此需要强制转换成Key类型。

这里使用的是已有的密钥,也可以不使用这里的三行代码,而使用2.1.1小节中的前三步的代码生成新的密钥再继续下面的步骤。

(2)       获取主要编码格式

byte[ ] kb=k.getEncoded( );

 

分析:执行SecretKey类型的对象kgetEncoded( )方法,返回的编码放在byte类型的数组中。

(3)       保存密钥编码格式

FileOutputStream  f2=new FileOutputStream("keykb1.dat");

    f2.write(kb);

分析:先创建文件输出流对象,在其参数中指定文件名,如keykb1.dat。然后执行文件输出流的write( )方法将第2步中得到的字节数组中的内容写入文件。

 

代码与分析

import java.io.*;

import java.security.*;

public class Skey_kb{

   public static void main(String args[]) throws Exception{

FileInputStream f=new FileInputStream("key1.dat");

ObjectInputStream b=new ObjectInputStream(f);

Key k=(Key)b.readObject( );

        byte[ ] kb=k.getEncoded( );

        FileOutputStream  f2=new FileOutputStream("keykb1.dat");

       f2.write(kb);

        // 打印密钥编码中的内容

        for(int i=0;i<kb.length;i++){

             System.out.print(kb[i]+",");

        }

   }

}

 

程序中在保存了密钥编码后,又使用循环语句将字节数组中的内容打印出来。这样可以较为直观地看到密钥编码的内容。

 

运行程序

输入java  Skey_kb 运行程序,在程序的当前目录中将产生文件名为keykb1.dat的文件,屏幕输出如下:

 

11,-105,-119,50,4,-105,16,38,-14,-111,21,-95,70,-15,76,-74,67,-88,59,-71,55,-125,104,42,

 

此即程序中创建的密钥的编码内容,如果用文本编辑器打开keykb1.dat,看到的不是上面的数字而是类似下面的字符:


2?&

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326933780&siteId=291194637