当前位置: 移动技术网 > IT编程>开发语言>.net > C# Java的加密的各种折腾

C# Java的加密的各种折腾

2019年05月30日  | 移动技术网IT编程  | 我要评论

龙泽里拉,961,驻港部队打击香港黑帮

24位加密

java

public class desutil {

    private static final string key_algorithm = "desede";

    private static final string cipher_algorithm = "desede/ecb/pkcs5padding";

    private static final string encoding = "utf-8";

    /**
     *
     * @param data body的json字符串
     * @param key 腾住提供的dessecret密钥
     * @return
     */
    public static string encrypt(string data, string key) {
        byte[] encrypt = encrypt(data.getbytes(charset.forname(encoding)), key);
        return encrypt == null ? null : base64.encodebase64string(encrypt);
    }

    private static byte[] encrypt(byte[] data, string key) {
        try {
            //实例化des密钥
            desedekeyspec dks = new desedekeyspec(key.getbytes());
            //实例化密钥工厂
            secretkeyfactory keyfactory = secretkeyfactory.getinstance(key_algorithm);
            //生成密钥
            secretkey secretkey = keyfactory.generatesecret(dks);
            //实例化
            cipher cipher = cipher.getinstance(cipher_algorithm);
            //初始化,设置为加密模式
            cipher.init(cipher.encrypt_mode, secretkey);
            return cipher.dofinal(data);
        } catch (invalidkeyexception e) {
            e.printstacktrace();
        } catch (nosuchalgorithmexception e) {
            e.printstacktrace();
        } catch (invalidkeyspecexception e) {
            e.printstacktrace();
        } catch (nosuchpaddingexception e) {
            e.printstacktrace();
        } catch (illegalblocksizeexception e) {
            e.printstacktrace();
        } catch (badpaddingexception e) {
            e.printstacktrace();
        }
        return null;
    }
}

对应的c#

 public static string encrypt(string data, string key)
        {


            if (key.length > 24)
                key = key.substring(0, 24);

            tripledescryptoserviceprovider tdsp = new tripledescryptoserviceprovider()
            {
                mode = ciphermode.ecb,
                padding = paddingmode.pkcs7,
                key = encoding.utf8.getbytes(key)
            };
            using (memorystream ms = new memorystream())
            {
                cryptostream cstream = new cryptostream(ms, tdsp.createencryptor(), cryptostreammode.write);
                var buffer = encoding.utf8.getbytes(data);
                cstream.write(buffer, 0, buffer.length);
                cstream.flushfinalblock();
                cstream.close();
                return convert.tobase64string(ms.toarray());
            }
        }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网