GithubHelp home page GithubHelp logo

dart_sm's Introduction

dart_sm

基于Dart语言实现的国密SM2、SM3、SM4算法。

实现内容

  • SM2
    • 非对称加密解密,支持C1C3C2和C1C2C3格式
    • 公钥压缩
    • 签名验签,包括纯签名、sm3杂凑(userId)、der编码
    • 密钥交换算法
  • SM3
    • 消息杂凑
    • hmac模式
  • SM4
    • ECB模式
    • CBC模式
    • CTR模式
    • GCM模式

安装

dependencies:
  dart_sm: ^0.1.5

使用方法

SM2

生成密钥对

KeyPair keypair = SM2.generateKeyPair();
String privateKey = keypair.privateKey; // 私钥
String publicKey = keypair.publicKey; // 公钥

公钥压缩(可选)

// 66位压缩公钥
String compressedPublicKey = SM2.compressPublicKey(publicKey);
bool isEqual = SM2.comparePublicKey(compressedPublicKey, publicKey);// 判断公钥是否相等
bool isValid = SM2.verifyPublicKey(compressedPublicKey); // 验证公钥

加密解密

// 默认C1C3C2格式
String cipherText = SM2.encrypt(data, publicKey);
String plainText = SM2.decrypt(cipherText, privateKey);
// C1C2C3格式
String cipherText = SM2.encrypt(data, publicKey, cipherMode: C1C2C3);
String plainText = SM2.decrypt(cipherText, privateKey, cipherMode: C1C2C3);

签名验签

// 纯签名
String sigValue = SM2.signature(data, privateKey);
bool verifyValue = SM2.verifySignature(data, sigValue, publicKey);
// 纯签名,不做公钥推导
String sigValue = SM2.signature(data, privateKey, publicKey: publicKey);
bool verifyValue = SM2.verifySignature(data, sigValue, publicKey);
// sm3杂凑
String sigValue = SM2.signature(data, privateKey, publicKey: publicKey, hash: true, userId: 'userId');
bool verifyValue = SM2.verifySignature(data, sigValue, publicKey, hash: true, userId: 'userId');
// der编码
String sigValue = SM2.signature(data, privateKey, publicKey: publicKey, der: true);
bool verifyValue = SM2.verifySignature(data, sigValue, publicKey, der: true);

SM3

// 参数为字符串
String hashValue = SM3.hash(data);
// 参数为字节数组
String hashValue = SM3.hashBytes(data);

//hmac,key要求为16进制字符串
String hashValue = SM3.hash(data, key:'95cb90ad5ba0c7c0e2a556f0072626b3');
String hashValue = SM3.hashBytes(data, key:'95cb90ad5ba0c7c0e2a556f0072626b3'); 

SM4

设置全局密钥,效率比每次加解密时设置密钥高

SM4.setKey('0123456789abcdeffedcba9876543210');

加密解密

// 默认ECB模式
String cipherText = SM4.encrypt(data);
String plainText = SM4.encrypt(cipherText);
// CBC模式
String cipherText = SM4.encrypt(data,mode: SM4CryptoMode.CBC,iv: 'fedcba98765432100123456789abcdef');
String plainText = SM4.decrypt(encryptData, mode: SM4CryptoMode.CBC,iv: 'fedcba98765432100123456789abcdef');
//单独指定密钥
String cipherText = SM4.encrypt(data, key: '0123456789abcdeffedcba9876543210');
String plainText = SM4.encrypt(cipherText, key: '0123456789abcdeffedcba9876543210');

致谢

协议

Copyright [luckykellan]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

dart_sm's People

Contributors

luckykellan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

dart_sm's Issues

SM3 含中文时与java端结果不一致

数据:{"appFlag":"true","currentPage":1,"pageSize":10,"productName":null,"riskClassCode":"全部"}

dart sm3结果:105513af9332bcf2cce70322ccbc24ab49c62b7e46f810487304e26a4102b9b5
java(hutool) sm3结果:752a357baa8645f07233103acf7e4333ae380225ec9287140a9b5697afc545d6

如果数据改为: {"appFlag":"true","currentPage":1,"pageSize":10,"productName":null,"riskClassCode":"06"} ,则完全匹配

关于SM2解密含中文的密文后,结果为乱码问题

KeyPair keypair = SM2.generateKeyPair();
String privateKey = keypair.privateKey; // 私钥
String publicKey = keypair.publicKey; // 公钥

String cipherText = SM2.encrypt('我是中文', publicKey);
String plainText = SM2.decrypt(cipherText, privateKey);

print(plainText); // 打印结果为:b�f/N-e

请大佬有空帮忙看看。

SM2 验签的时候这个位置会报错,只是传了个公钥进去

image

代码如下:
var sortString = "appId=19E179E5DC29C05E65B90CDE57A1C7E5&code=0&data={"accessToken":"!TgbtrMd3RFP_mk8P-qJG985Mjn_9suebPrBPfdyQZM08tqXOqaoq17e6mXqw2w9TKuj-sSvmGpGIih7jzH3FZPXmXDRkwN3SvwxpabD-Bi8TrYy6y_682iI0qtyKUh5PnK0Qw-ZEG3vQjgh0s9SA6zs5F0iWcocpg0NwNiRLKnNvg4geZHg9dMaymZUd8r8he7F51URXrHEORjkbUdwopusw==","certDateFlag":"1","certifyType":"0","isNeedFace":"0","isTrustDev":"1","pwdFlag":"0","refreshToken":"59b50736b38c4331ab8ef3414ea09d2e","secureToken":"aZIFOGqGe/SMPL3bhmvM/C6KbCaxi/pyE/juCpYsRJcgdkF6IMCiCjY7U+SBKMiQCo3Ti7xWwYRZloTE44djUGt+WvBTCcRmi4HoJ1Tb2xuiNFvTNo5nGx1BPBMFpN7JzUzRKBkXORWtUgxCqwjyuzq58SA4o09QvjHrWYp+qM1VWgMkKc53nzALYMI0bS42dvwflEuJbXm5UdANFs/rsc2LrmHqYHH+X46pCcyvC3nea9PPTMxOBT87CScZOmj6eC7Gkjwkeg2a2LSlV2IknWJEYCXeQnNsDsdD2jMbWl9npjDoGgwZlZmsR6OGijqVI3uA9uQBpuIRwbe0MfkJTA=="}&encType=SM4&message=成功&signType=SM2&timestamp=1716195185&type=success&key=D91CEB11EE62219CD91CEB11EE62219C";

var signData = "0d63e83510a7e1df0bb0d5708fc25091d1c8f5e4f3e60d08ad8222ab1121f0f9ffa31768f46b21fddad7d3b141971d26c04c39a4376aecfc79a64cabc97811ad";

var pubkey = "d74188eeb242f52e58da294017c4fb9dc7c8edab0224241d236e037196f77946ce2e4490c46957093c7a59209b58fa40f9076ccc6fef7d5c27ba499b3ab3ec2d";

if (SM2.verifySignature(sortString, signData, pubkey,
hash: true, userId: "1234567812345678")) {
print("YES");
} else {
print("NO");
}

同样的sm4使用ECB,和js版本的gm-crypto加密结果不一致

sm4和js版本的加密结果不一致, 导致后端解密不通用, 是哪里有问题吗?
js版本
let key = '7d5a493364f2f4250cb7963a17ee081f'
// 加密
let encData = SM4.encrypt('123456', key, {
mode: SM4.constants.ECB,
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
console.log(encData) // biOgHi0QdDILAvpxPf8r1w==

dart
sm4Key = '7d5a493364f2f4250cb7963a17ee081f';
String encodeString = SM4.encrypt('123456', key: sm4Key);
String encData = base64Encode(utf8.encode(encodeString));

Flutter web无法使用SM3

你好,flutter web项目,调用SM3.hash(data);报错“Unsupported operation: Uint64 accessor not supported by dart2js.”
When the exception was thrown, this was the stack:
dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 288:49 throw
dart-sdk/lib/_internal/js_dev_runtime/private/native_typed_data.dart 646:5 setUint64]
packages/dart_sm/src/sm3.dart 17:15 hashBytesToBytes
packages/dart_sm/src/sm3.dart 108:37 hash
请问怎么解决?

sm2 test 通不过啊

const data = '12345';
final keypair = SM2.generateKeyPair();
String privateKey = keypair.privateKey; // 私钥
String publicKey = keypair.publicKey; // 公钥

test('加密和解密', (){
  String encryptData = SM2.encrypt(data, publicKey, cipherMode: C1C2C3);
  String decryptData = SM2.decrypt(encryptData, privateKey);
  expect(decryptData, data);
});

Expected: '12345'
Actual: ''
Which: is different. Both strings start the same, but the actual value is missing the following trailing characters: 12345

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.