I am trying to port the following Java code to the C # equivalent:
public static String encrypt(String value, String key) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] bytes = value.getBytes(Charset.forName("UTF-8")); X509EncodedKeySpec x509 = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(key)); KeyFactory factory = KeyFactory.getInstance("RSA"); PublicKey publicKey = factory.generatePublic(x509); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); bytes = cipher.doFinal(bytes); return DatatypeConverter.printBase64Binary(bytes); }
So far, I have managed to write the following in C # using the BouncyCastle library for .NET:
public static string Encrypt(string value, string key) { var bytes = Encoding.UTF8.GetBytes(value); var publicKeyBytes = Convert.FromBase64String(key); var asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes); var rsaKeyParameters = (RsaKeyParameters) asymmetricKeyParameter; var cipher = CipherUtilities.GetCipher("RSA"); cipher.Init(true, rsaKeyParameters); var processBlock = cipher.DoFinal(bytes); return Convert.ToBase64String(processBlock); }
However, the two methods give different results, even if called with the same parameters. For testing purposes, I use the following RSA public key:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLCZahTj/oz8mL6xsIfnX399Gt6bh8rDHx2ItTMjUhQrE/9kGznP5PVP19vFkQjHhcBBJ0Xi1C1wPWMKMfBsnCPwKTF/g4yga6yw26awEy4rvfjTCuFUsrShSPOz9OxwJ4t0ZIjuKxTRCDVUO7d/GZh2r7lx4zJCxACuHci0DvTQIDAQAB
Could you help me successfully port Java code or suggest an alternative to get the same result in C #?
EDIT1 : The output in Java is different every time the program starts. I don’t think any addition was indicated, so I don’t understand what makes the conclusion random.
EDIT2 . Java uses PKCS1 by default, so it was enough to specify it in the C # encryption initialization to get the same type of encryption (although not the same result that is currently irrelevant).