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

C# Java的加密的各种折腾

程序员文章站 2024-01-14 10:38:34
24位加密 Java 对应的C ......

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());
            }
        }