Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.Net和Java RSA加密解密的问题 #1

Open
alanwei43 opened this issue Jul 31, 2015 · 0 comments
Open

.Net和Java RSA加密解密的问题 #1

alanwei43 opened this issue Jul 31, 2015 · 0 comments

Comments

@alanwei43
Copy link

你好,我是.Net开发者,我想问一下这两个语言之间互相RSA加密解密的问题。
在.Net提供中RSA加密对象RSACryptoServiceProvider支持PKCS#1 v1.5 padding,在Java中同样适用PKCS1填充,为什么加密后的密文不一致呢?

下面是Java的实现:

    public static String encrypt(String source, String publicKey)
        throws Exception {
    Key key = getPublicKey(publicKey);
    /** 得到Cipher对象来实现对源数据的RSA加密 */
    Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] b = source.getBytes();
    /** 执行加密操作 */
    byte[] b1 = cipher.doFinal(b);
    return new String(Base64.encodeBase64(b1),
            ConfigureEncryptAndDecrypt.CHAR_ENCODING);
}

    public static PublicKey getPublicKey(String key) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
            Base64.decodeBase64(key.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

下面是.Net的实现

    public static byte[] RsaEncrypt(string data, string key)
    {
        var rsaProvider = new RSACryptoServiceProvider();
        rsaProvider.FromXmlString(key);
        return rsaProvider.Encrypt(Encoding.UTF8.GetBytes(data), false);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant