когда я кодирую и декодирую свою строку, я получаю это исключение плохого заполнения, я не могу найти проблему ...
класс защиты с некоторыми методами для генерации ключей и сохранения их в файлы.
private KeyPairGenerator keyGen;
private KeyPair pair;
private PrivateKey privateKey;
private PublicKey publicKey;
final static String PRIVATEKEYPATH = "KeyPair/privateKey";
final static String PUBLICKEYPATH = "KeyPair/publicKey";
public Guard(int keylength) {
try {
this.keyGen = KeyPairGenerator.getInstance("RSA");
this.keyGen.initialize(keylength);
this.createKeys();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public void createKeys() {
this.pair = this.keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
try {
this.writeToFile(PUBLICKEYPATH, this.getPublicKey().getEncoded());
this.writeToFile(PRIVATEKEYPATH, this.getPrivateKey().getEncoded());
} catch (IOException e) {
e.printStackTrace();
}
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void writeToFile(String path, byte[] key) throws IOException {
File f = new File(path);
f.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(f);
fos.write(key);
fos.flush();
fos.close();
}
класс шифрования с некоторыми дополнительными методами.
private Cipher cipher;
public Encryption() {
new Guard(2048);
try {
this.cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
}
}
public PrivateKey getPrivate() throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(Guard.PRIVATEKEYPATH).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
public PublicKey getPublic() {
try {
byte[] keyBytes = Files.readAllBytes(new File(Guard.PUBLICKEYPATH).toPath());
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String encryptText(String msg) {
try {
System.out.println("private: " + this.getPrivate());
this.cipher.init(Cipher.ENCRYPT_MODE, this.getPrivate());
return new String(Base64.getEncoder().encode(cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8))));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decryptText(String msg) {
try {
System.out.println("public: " + this.getPublic());
this.cipher.init(Cipher.DECRYPT_MODE, this.getPublic());
return new String(cipher.doFinal(Base64.getDecoder().decode(msg.getBytes())), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Код, который я использую для проверки этого
String encryptedtext = encryption.encryptText(message);
System.out.println("\n");
System.out.println("Encrypted: " + encryptedtext);
System.out.println("\n");
String decryptedtext = encryption.decryptText(message);
System.out.println("\n");
System.out.println("Decrypted: " + decryptedtext);
System.out.println("\n");
Я получаю эту ошибку в консоли .. .
private: sun.security.rsa.RSAPrivateCrtKeyImpl@ffbcd71b
Encrypted: UmTs0orBBUCDw8goMKt8D62UpPSBNcyCiBFRy06ZUIDwkVSVi5ycSJwbPguh9j1Dl8mUWHgENqcjkdVS29Tmm2BVUB3UVLZ9ipZA2Wy6hP6bGII6Mc7lXRct7vtt8vP7V9XaSdDFnGnOYxuHNxZp20uzjSO/01Q7BLvZeyFZ7mtiOCpjVsJsfgbjv2fhvjmI5AwSPKy9zBAF3TELNYjFFG4vR40Kvo5ivBUr7K6semoxu2LopRvdkHJuy0Fct9IrjtQEBm6Rtc76h4571/Ax+WGRAChvQlSfF79eTpnzi7RFyY4gQob3hoe/OKjLoq3ND7bZH16TfCvyQWJ3Uy6NmQ==
public: Sun RSA public key, 2048 bits
modulus: 22360571078888891193532117761064208601291380042312881237141286755755048492670469689781772100169628763155056404733727791370921766847501848789367350048728066527572419400469351759588879920426324091317192540815347347662468102850915691007295311501919365450102253833487458361205471990638199135985417559640118903065242821950008443420650262118390561181631624932671294373897078530352657238981603419775318915330987897031276189082238722221970046601708025263128821760949975495097805142117377923923311362585617048765071867603719217326844608463821757474965536664782012717061027456244049018643966975847167459872042365451121275472741
public exponent: 65537
Decrypted: null
javax.crypto.BadPaddingException: Decryption error
Кто-нибудь из вас видит, что я делаю неправильно?