Description
For RSA encryption, NoPadding produces repeatable ciphertext and permits manipulation. With PKCS1Padding, decryption errors or response times can disclose whether padding was valid.
Potential impact
Encrypted tokens, session keys or personal data may be exposed, or messages altered. A disclosed login token or API key can grant account access.
Remediation
- For new RSA encryption, replace algorithm-only
RSA,PKCS1PaddingorNoPaddingwith explicit OAEP. Check that both JCA/JCE providers support the same hash, MGF1 hash and label. Use RSA keys of at least 2048 bits. - Encrypt application data with AES-GCM and wrap its random session key with RSA-OAEP. Maintain the provider and make decryption failures indistinguishable to callers.
Examples
The examples encrypt a short string directly to illustrate RSA padding settings. Use a dedicated password hash when storing login passwords.
Before
java
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
public class InsecureRSAExample {
// 취약: PKCS#1 v1.5 패딩 사용
public static byte[] encryptPassword(String password, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // BAD
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
}
}
After
java
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import javax.crypto.spec.PSource;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
public class SecureRSAExample {
// 안전: OAEP(SHA-256, MGF1) 사용
public static byte[] encryptPassword(String password, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaep = new OAEPParameterSpec(
"SHA-256",
"MGF1",
MGF1ParameterSpec.SHA256,
PSource.PSpecified.DEFAULT
);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaep);
return cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
}
}
OAEPParameterSpec selects SHA-256 for both OAEP and MGF1, and PSource.PSpecified.DEFAULT selects the empty label. Configure the decrypting side to match.