2

I need to port to C# a portion of an existing and working Java system which handles encrypting/decrypting a string. My C# solution will encrypt a string, and the existing Java system will need to be able to decrypt that string.

Both systems will need to use the existing private and public keys. The keys were generated from the Java system (".key" extension). Assume both systems will have safe and reliable access to the same key files.

The closest I've found is this thread (RSA .NET encryption Java decryption) but it uses RSACryptoServiceProvider.FromXmlString(). Most other examples deal with generating your own keys using RSACryptoServiceProvider, and encrypting/decrypting all in the same solution. In short, I can't find any way to accomplish this.

For reference, here is the relevant Java code currently handling the encrypting (obvious cut/paste job so please ignore minor syntax errors; again, this is working fine currently)

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class Encryptor{

    private static final String XFROM = "RSA";
    private static PublicKey iPubKey;

    public String encryptString() {
        // init
        byte[] pkeyByte = Util.grabKey("keys/private.key");
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pkeyByte);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        iPubKey = keyFactory.generatePublic(pubKeySpec);

        // encrypt          
        String uid = "string_to_encrypt";
        byte[] dataBytes = uid.getBytes();
        byte[] encBytes = encrypt(dataBytes, iPubKey, XFROM);

        String result = Base64.encodeBase64String(encBytes);

        Return result;
    }

    private static byte[] encrypt(byte[] inpBytes, PublicKey key, String xform) throws Exception {
        Cipher cipher = Cipher.getInstance(xform);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(inpBytes);
    } 

}

Questions:

Is this possible?

Any samples or documentation that can set me in the right direction?

4

0 回答 0