Skip to content

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

Description

@alanwei43

你好,我是.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);
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions