加密和解密成功时,加密与公钥与私钥解密:C#RSA加密与私钥
C#加密基于公钥(成功)
public string EncryptData(string data) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xml); //public key
var cipher = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
return Convert.ToBase64String(cipher);
}
Java的解密与私人钥匙(成功)
public static void decrypt() throws Exception{
byte[] modulusBytes = Base64.getDecoder().decode(mod);
byte[] dByte = Base64.getDecoder().decode(d);
BigInteger modulus = new BigInteger(1, (modulusBytes));
BigInteger exponent = new BigInteger(1, (dByte));
RSAPrivateKeySpec rsaPrivKey = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(rsaPrivKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherData = Base64.getDecoder().decode(cipherByte);
byte[] plainBytes = cipher.doFinal(cipherData);
System.out.println(new String(plainBytes));
}
问题是在这里
当与私钥和java C#加密与公开密钥坏填充错误解密发生:
C#加密的私人密钥(失败)
public stringEncryptData(string data) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xml); //private key
var cypher = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
return Convert.ToBase64String(cypher);
}
java的解密带公钥(失败)
public static void decryptPublic() throws Exception{
byte[] modulusBytes = Base64.getDecoder().decode(mod);
byte[] expBytes = Base64.getDecoder().decode(exp);
BigInteger modulus = new BigInteger(1, (modulusBytes));
BigInteger exponent = new BigInteger(1, (expBytes));
RSAPublicKeySpec pubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey publicKey = fact.generatePublic(pubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] cipherData = Base64.getDecoder().decode(cipherByte);
byte[] plainBytes = cipher.doFinal(cipherData);
System.out.println(new String(plainBytes));
}
我知道公钥应该用来做解密加密和私钥。但在我的情况下,我需要将公钥发送给多个客户端,以解密由其私钥加密的文本。除客户端外,其他人不应阅读文本。 任何人都可以看到我的代码有什么问题,或者建议更好的解决方案来解决我的问题。
用公钥加密并用私钥解密。将私钥的副本提供给需要副本解密的每个人,但不要尝试颠倒算法。 – WDS
@WDS正如我的回答所述,分配私钥也是一个非常糟糕的主意,因为您完全无法控制其他方可能与谁共享密钥,并且极大地增加了处理被盗用密钥的难度。 – Iridium
@CY LIM:你的加密和解密方法应该是镜像的,这意味着如果你在你的JAVA解密函数中使用PKCS1填充('Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”)'),你应该也使用PKCS1填充你的C#加密函数'var cypher = rsa.Encrypt(Encoding.UTF8.GetBytes(data),false);'用'var cypher = rsa.Encrypt(Encoding.UTF8.GetBytes(data),RSAEncryptionPadding.Pkcs1) ;'。 https://msdn.microsoft.com/en-us/library/mt132684%28v=vs.110%29.aspx – godvsdeity