使用 RSA 私钥加密消息是否安全

Is it safe to use RSA private key to encrypt a message

我想分发加密信息,只有我可以加密,但所有人都可以解密。我正在使用以下代码来执行任务。它有效,但我想知道它是否存在任何安全问题?

我知道正常的用法是使用RSA public 密钥加密和私钥解密(但我的用例是相反的)。我也不想在这里使用 java.security.Signature。

用例: 我想通过电子邮件将配置文件从服务器发送到客户端,而收件人无法以明文形式读取配置。在安装期间拥有服务器 public 密钥的应用程序将能够在将配置文件导入配置目录后对其进行解密。

public static final String ALGORITHM = "RSA/ECB/PKCS1Padding";

public Cipher createCipher(final int encryptionMode, final Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    final Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(encryptionMode, key);
    return cipher;
}

public byte[] encryptString(final String text, final PrivateKey privateKey) throws GeneralSecurityException, IOException {
    return createCipher(Cipher.ENCRYPT_MODE, privateKey).doFinal(text.getBytes("UTF-8"));
}

public String decryptString(final byte[] msg, final PublicKey publicKey) throws GeneralSecurityException, IOException {
    final byte[] decrypted = createCipher(Cipher.DECRYPT_MODE, publicKey).doFinal(msg);
    return new String(decrypted, "UTF-8");
}

// me 
final PrivateKey privateKey = ... read from file ...
final byte[] msg = encryptString("my-secret-text-that-everybody-can-read-but-only-I-can-generate", privateKey);

// other person
final PublicKey publicKey = ... read from file ...
final String text = decryptString(msg, publicKey));

感谢@Maarten Bodewes 的评论回答了我的问题。

I'm voting to close this question as off-topic because although the question contains code this really is a conceptual question about cryptography, where it has been asked before – Maarten Bodewes

根据他提供的link,我的问题的答案是:"No, you generally cannot swap the public and private keys."

它在 public 指数中使用小素数只会危害 RSA 的安全性。详细答案如下:

Your public key consists of a public exponent and a modulus. The modulus should be known to the person doing the encryption. The public exponent - in general - is a relatively small prime such as 3 or 65537 (Fourth number of Fermat). So given the modulus all an attacker has to do is guess the public key. It's very easy to factor pretty small exponents (I've written software to generate public keys given a private key). The exponent of the private key on the other hand consists of a number that is about as large as the modulus. It cannot be easily factored; the security of RSA relies on this fact.