SM4加密、解密

npm install sm-crypto --save

const sm4 = require('sm-crypto').sm4;
let sm4Api = {
  encrypt: function (data) {
    if(!data) return data;
    return this.convertToBase64(sm4.encrypt(data, "43484c43484c40323032332121212121"));
  },
  decrypt: function (data) {
    if(!data) return data;
    return sm4.decrypt(this.convertToHex(data), "43484c43484c40323032332121212121");
  },
  convertToBase64: function(hexString) {
    const buffer = Buffer.from(hexString, 'hex');
    const base64String = buffer.toString('base64');
    return base64String;
  },
  convertToHex: function(base64String) {
    const buffer = Buffer.from(base64String, 'base64');
    const hexString = buffer.toString('hex');
    return hexString;
  }
};
export default sm4Api;

Java中可以使用Bouncy Castle库来实现SM4加密解密。以下是一个简单的示例代码: ```java import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.encoders.Hex; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; public class SM4Util { private static final int KEY_LENGTH = 16; private static final int IV_LENGTH = 16; public static byte[] encrypt(byte[] key, byte[] iv, byte[] data) { byte[] encrypted = new byte[data.length]; CBCBlockCipher cipher = new CBCBlockCipher(new SM4Engine()); cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); int length = cipher.processBytes(data, 0, data.length, encrypted, 0); try { cipher.doFinal(encrypted, length); } catch (Exception e) { e.printStackTrace(); } return encrypted; } public static byte[] decrypt(byte[] key, byte[] iv, byte[] data) { byte[] decrypted = new byte[data.length]; CBCBlockCipher cipher = new CBCBlockCipher(new SM4Engine()); cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); int length = cipher.processBytes(data, 0, data.length, decrypted, 0); try { cipher.doFinal(decrypted, length); } catch (Exception e) { e.printStackTrace(); } return decrypted; } public static void main(String[] args) { String keyStr = "0123456789abcdef"; String ivStr = "0123456789abcdef"; byte[] key = Hex.decode(keyStr); byte[] iv = Hex.decode(ivStr); byte[] data = "Hello, world!".getBytes(StandardCharsets.UTF_8); byte[] encrypted = encrypt(key, iv, data); byte[] decrypted = decrypt(key, iv, encrypted); System.out.println(new String(decrypted, StandardCharsets.UTF_8)); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值