C# Java的加密的各种折腾
程序员文章站
2022-04-21 19:57:56
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()); } }
上一篇: MySql数据库创建表