JavaでRSAアルゴリズムを使用して暗号化/復号化する簡単なプログラムを実行しています。次のように暗号オブジェクトを作成します。
//Create a Cipher object
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
暗号化関数を呼び出して暗号化を行います。
String cipher=encrypt(textByte, pair, rsaCipher);
System.out.println("The Encryption using RSA Algorithm : "+cipher);
そして、次のように復号化します。
//Decryption
String plain=decrypt(Base64.decodeBase64(cipher),pair, rsaCipher);
System.out.println("The Decryption using RSA Algorithm : "+plain);
出力を表示すると、復号化出力は元のテキストの前に長いスペースを返します。
ただし、Cipher オブジェクトを作成するコードを次のように編集すると、 //Cipher オブジェクトを作成します Cipher rsaCipher = Cipher.getInstance("RSA");
つまり、操作モードとパディング引数を削除すると、問題が解決され、出力は次のようになります。
問題はどこだ。最初のケース (スペースが表示されたとき) では、NoPadding? を指定しました。復号化されたメッセージにスペースが表示されるのはなぜですか? パディングを使用したとしても、これは起こらないはずです。
編集: これは暗号化と復号化の方法です:
public static String encrypt(byte[] textBytes, KeyPair pair, Cipher rsaCipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
//get the public key
PublicKey pk=pair.getPublic();
//Initialize the cipher for encryption. Use the public key.
rsaCipher.init(Cipher.ENCRYPT_MODE, pk);
//Perform the encryption using doFinal
byte[] encByte = rsaCipher.doFinal(textBytes);
// converts to base64 for easier display.
byte[] base64Cipher = Base64.encodeBase64(encByte);
return new String(base64Cipher);
}//end encrypt
public static String decrypt(byte[] cipherBytes, KeyPair pair, Cipher rsaCipher) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
{
//get the public key
PrivateKey pvk=pair.getPrivate();
//Create a Cipher object
//Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
//Initialize the cipher for encryption. Use the public key.
rsaCipher.init(Cipher.DECRYPT_MODE, pvk);
//Perform the encryption using doFinal
byte[] decByte = rsaCipher.doFinal(cipherBytes);
return new String(decByte);
}//end decrypt