Hallo! Ich möchte einen String mit RSA verschlüsseln. allerdings bekomme ich immer folgenden Fehler:
Weiß gemand woran es liegt?
Hier der Code:
Code:
Exception in thread "main" java.lang.NullPointerException
at RsaVerschlüsselung.main(RsaVerschlüsselung.java:21)
Hier der Code:
Java:
import java.awt.RenderingHints.Key;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class RsaVerschlüsselung {
static int keysize = 1024;
private static KeyPair key = null;
public static void main(String[] arg) {
gen();
byte[] enc = encrypt("Hallo", key.getPublic());
System.out.println(new String(enc));
}
public static void gen() {
KeyPairGenerator keygen = null;
try {
keygen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keygen.initialize(1024);
KeyPair key = keygen.generateKeyPair();
}
public static byte[] encrypt (String message, PublicKey pk) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] chifrat = null;
try {
chifrat = cipher.doFinal(message.getBytes());
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return chifrat;
}
public static String decrypt(byte[] chifrat, PrivateKey sk) {
byte[] dec = null;
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, sk);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dec = cipher.doFinal(chifrat);
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return new String(dec);
}
}