Store cryptography key in a file in Java

Description

In cryptography operations, Symmetric key required for encryption and decryption need to be stored for later usage. Symmetric key is represented in bytes. Hence key bytes can be stored in file using write method of FileOutputStream object that accepts byte as an argument.

  • Filename: KeyStorage.java

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
import java.io.*;
class KeyStorage {
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;

public KeyStorage() {
generateSymmetricKey();
writeKey();
}
void generateSymmetricKey() {
try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey=getRawKey(knumb);
skeyString = new String(skey);
System.out.println("AES Symmetric key = "+skeyString);
}
catch(Exception e) {
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
void writeKey() {
try {
FileOutputStream f0;
f0 = new FileOutputStream("D://symmetricKey.txt");
f0.write(skey);
f0.close();
}
catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
KeyStorage ks = new KeyStorage();
}
}