Hallo!
Hab hier ne Klasse die n Text mittels RSA verschlüsselt. Die Verschlüsselung klappt (jedenfalls schmiert das Programm nicht ab). Bei der Entschlüsselung läuft allerdings anscheinend was schief, sodass ich immer eine NullPointerException bekomme.
[Code=Java]
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RsaCipher {
private static KeyPair key = null;
public static void main(String[] args) {
generateKey();
String text = "Pferde fressen keinen Gurkensalat";
String encrypted = encrypt(text, key.getPublic());
String decrypted = decrypt(text.getBytes(), key.getPrivate());
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
private static void generateKey() {
KeyPairGenerator keyGen = null;
try {
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = keyGen.generateKeyPair();
}
public static String encrypt(String text, PublicKey pubKey) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return new String(cipherText);
}
public static String decrypt(byte[] text, PrivateKey priKey) {
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, priKey);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
}
[/Code]
[Code=Text]
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at RsaCipher.decrypt(RsaCipher.java:66)
at RsaCipher.main(RsaCipher.java:18)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at RsaCipher.decrypt(RsaCipher.java:72)
at RsaCipher.main(RsaCipher.java:18)
[/Code]
Ich hoffe ihr könnt mir helfen!
Danke schonmal!