I am creating a program to generate a key pair but i have this error:
Exception in thread "main" java.lang.NullPointerException
at generateAESKey.main(generateAESKey.java:43)
This is currently what I have been working. The
key.getEncoded());
is not being read.
public class generateAESKey {
public static void main(String[] args) throws Exception {
generateAESKey generatekey = new generateAESKey();
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey skey = keyGen.generateKey();
byte[] raw = skey.getEncoded();
FileOutputStream fos2 = new FileOutputStream("C:\\Users\\win8.1\\Desktop\\AES\\test.txt");
fos2.write(raw);
fos2.close();
KeyPairGenerator keyGen1 = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen1.initialize(1024, random);
KeyPair generatedKeyPair = keyGen1.genKeyPair();
savePublicKey(generatedKeyPair.getPublic(), "C:\\Users\\win8.1\\Desktop\\AES\\public");
savePrivateKey(generatedKeyPair.getPrivate(), "C:\\Users\\win8.1\\Desktop\\AES\\private");
PublicKey key = null;
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
key.getEncoded());
FileOutputStream fos3 = new FileOutputStream("C:\\Users\\win8.1\\Desktop\\AES\\public.txt");
fos3.write(x509EncodedKeySpec.getEncoded());
fos3.close();
PrivateKey key1 = null;
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
key1.getEncoded());
FileOutputStream fos4 = new FileOutputStream("C:\\Users\\win8.1\\Desktop\\AES\\private.txt");
fos4.write(pkcs8EncodedKeySpec.getEncoded());
fos4.close();
System.out.println("SAVE");
}
private static void savePrivateKey(PrivateKey private1, String string) {
// TODO Auto-generated method stub
}
private static void savePublicKey(PublicKey public1, String string) {
// TODO Auto-generated method stub
}
public SecretKeySpec getKeySpec() throws IOException, NoSuchAlgorithmException {
byte[] bytes = new byte[16];
File f = new File("aes.key");
SecretKey key = null;
SecretKeySpec spec = null;
if (f.exists()) {
new FileInputStream(f).read(bytes);
} else {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256); //128 kalagay
key = kgen.generateKey();
bytes = key.getEncoded();
new FileOutputStream(f).write(bytes);
}
spec = new SecretKeySpec(bytes,"AES");
return spec;
}
}
Any help will be greatly appreciated. Thanks.
I have already edited it.
First error: KeyPairGenerator.getInstance(String algorithm)
can only handle the following input String
s:
For mor infos look in the docs
Possible call
KeyPairGenerator.getInstance("RSA");
Second error (nullptr):
You have to create a PublicKey
! You are doing PublicKey key = null;
and then you Fall:
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
key.getEncoded());//key is null so nullpointer will occur
You have to assign a value to your key
variable. I assume you want to take your created PublicKey
so do:
PublicKey key = generatedKeyPair.getPublic();