加密和解密成功時,加密與公鑰與私鑰解密: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