欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#与Java AES 加密解密

程序员文章站 2023-10-26 18:55:40
参考文档:https://www.cnblogs.com/xbzhu/p/7064642.html 这是参考文档的博主写的Demo:https://github.com/zhu-xb/AES-Cryptography 再次感谢博主 朱小波 https://www.cnblogs.com/xbzhu/ ......

参考文档:

前几天对接java接口,需要c#加密参数,java解密。奈何网上找了一堆大同小异的加解密方法都跟jaca加密的密文不一致,java接口也无法解密,直到看见上面链接的第二种方法。能够正常的解密java加密的密文,说明此方法有效,但这里只有解密,我需要的是加密方法(伸手党做习惯了),没办法读读代码看看是怎么解密的,巧了看到了 createdecryptor 改一下 试一下解密 跟java完全一致 成功!感谢博主!

这是参考文档的博主写的demo:https://github.com/zhu-xb/aes-cryptography

    /// <summary>
    /// aes解密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string aesdecrypt(string content, string key)
    {
        keygenerator kgen = keygenerator.getinstance("aes");
        securerandom securerandom = securerandom.getinstance("sha1prng");
        securerandom.setseed(encoding.ascii.getbytes(key));
        kgen.init(128, securerandom);
        secretkey secretkey = kgen.generatekey();
        byte[] encodeformat = secretkey.getencoded();

        using (aescryptoserviceprovider aesprovider = new aescryptoserviceprovider())
        {
            aesprovider.key = encodeformat;
            aesprovider.mode = ciphermode.ecb;
            aesprovider.padding = paddingmode.pkcs7;
            using (icryptotransform cryptotransform = aesprovider.createdecryptor())
            {
                byte[] inputbuffers = convert.frombase64string(content);
                byte[] results = cryptotransform.transformfinalblock(inputbuffers, 0, inputbuffers.length);
                aesprovider.clear();
                return encoding.utf8.getstring(results);
            }
        }
    }
 /// <summary>
    /// aes加密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string aesencrypt(string content, string key)
    {
        keygenerator kgen = keygenerator.getinstance("aes");
        securerandom securerandom = securerandom.getinstance("sha1prng");
        securerandom.setseed(encoding.ascii.getbytes(key));
        kgen.init(128, securerandom);
        secretkey secretkey = kgen.generatekey();
        byte[] encodeformat = secretkey.getencoded();

        using (aescryptoserviceprovider aesprovider = new aescryptoserviceprovider())
        {
            aesprovider.key = encodeformat;
            aesprovider.mode = ciphermode.ecb;
            aesprovider.padding = paddingmode.pkcs7;
            using (icryptotransform cryptotransform = aesprovider.createencryptor())
            {
                byte[] inputbuffers = encoding.utf8.getbytes(content);
                byte[] results = cryptotransform.transformfinalblock(inputbuffers, 0, inputbuffers.length);
                aesprovider.clear();
                return convert.tobase64string(results);
            }
        }
    }

再次感谢博主 朱小波