1. Project Overview & Quickstart (Tencent/MMKV)
File: README.md
δΈζηζ¬θ―·εηθΏι
MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on Android, iOS/macOS, Windows, POSIX and HarmonyOS NEXT, with experimental Kotlin Multiplatform support.
MMKV for Kotlin Multiplatform
The v2.4.1 Kotlin Multiplatform package is experimental and currently targets
Android and iOS. Its API and artifact layout may change in a future release.
Add it to the shared module:
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.tencent:mmkv-kmp:2.4.1")
}
}
}Supported targets are Android, iosArm64, iosSimulatorArm64, and iosX64. See the Kotlin Multiplatform guide for initialization and packaging details.
MMKV for Android
Features
Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of Android to achieve the best performance.
- Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no
sync, noapplycalls needed.Small.
- A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
- About 50K in binary size: MMKV adds about 50K per architecture on App size, and much less when zipped (APK).
Getting Started
Installation Via Maven
Add the following lines to build.gradle on your app module:
dependencies {
implementation 'com.tencent:mmkv:2.4.1'
// replace "2.4.1" with any available version
}Starting from v2.0.0, MMKV no longer supports 32-bit arch and API level 22 or 21, if you want 32-bit or API level 21~22, use v1.3.x LTS series.
For other installation options, see Android Setup.
Quick Tutorial
You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.
Setup MMKV on App startup, say your Application class, add these lines:
public void onCreate() {
super.onCreate();
String rootDir = MMKV.initialize(this);
System.out.println("mmkv root: " + rootDir);
//β¦β¦
}MMKV has a global instance, that can be used directly:
import com.tencent.mmkv.MMKV;
MMKV kv = MMKV.defaultMMKV();
kv.encode("bool", true);
boolean bValue = kv.decodeBool("bool");
kv.encode("int", Integer.MIN_VALUE);
int iValue = kv.decodeInt("int");
kv.encode("string", "Hello from mmkv");
String str = kv.decodeString("string");MMKV also supports Multi-Process Access. Full tutorials can be found here Android Tutorial.
Performance
Writing random int for 1000 times, we get this chart:
For more benchmark data, please refer to our benchmark.
MMKV for iOS/macOS
Features
Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of iOS/macOS to achieve the best performance.
Easy-to-use. You can use MMKV as you go, no configurations are needed. All changes are saved immediately, no
synchronizecalls are needed.Small.
- A handful of files: MMKV contains encode/decode helpers and mmap logics and nothing more. It's really tidy.
- Less than 30K in binary size: MMKV adds less than 30K per architecture on App size, and much less when zipped (IPA).
Getting Started
Installation Via CocoaPods:
- Install CocoaPods;
- Open the terminal,
cdto your project directory, runpod repo updateto make CocoaPods aware of the latest available MMKV versions; - Edit your Podfile, add
pod 'MMKV'to your app target; - Run
pod install; - Open the
.xcworkspacefile generated by CocoaPods; - Add
#import <MMKV/MMKV.h>to your source file and we are done.
For other installation options, see iOS/macOS Setup.
Quick Tutorial
You can use MMKV as you go, no configurations are needed. All changes are saved immediately, no synchronize calls are needed.
Setup MMKV on App startup, in your -[MyApp application: didFinishLaunchingWithOptions:], add these lines:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// init MMKV in the main thread
[MMKV initializeMMKV:nil];
//...
return YES;
}MMKV has a global instance, that can be used directly:
MMKV *mmkv = [MMKV defaultMMKV];
[mmkv setBool:YES forKey:@"bool"];
BOOL bValue = [mmkv getBoolForKey:@"bool"];
[mmkv setInt32:-1024 forKey:@"int32"];
int32_t iValue = [mmkv getInt32ForKey:@"int32"];
[mmkv setString:@"hello, mmkv" forKey:@"string"];
NSString *str = [mmkv getStringForKey:@"string"];MMKV also supports Multi-Process Access. Full tutorials can be found here.
Performance
Writing random int for 10000 times, we get this chart:
For more benchmark data, please refer to our benchmark.
MMKV for Windows
Features
Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of Windows to achieve the best performance.
- Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no
save, nosynccalls are needed.Small.
- A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
- About 10K in binary size: MMKV adds about 10K on application size, and much less when zipped.
Getting Started
Installation Via Source
Getting source code from git repository:
textgit clone https://github.com/Tencent/MMKV.gitAdd
Core/core.vcxprojto your solution;Add
MMKVproject to your project's dependencies;Add
$(OutDir)includeto your project'sC/C++->General->Additional Include Directories;Add
$(OutDir)to your project'sLinker->General->Additional Library Directories;Add
mmkv.libto your project'sLinker->Input->Additional Dependencies;Add
#include <MMKV/MMKV.h>to your source file and we are done.
note:
- MMKV is compiled with
MT/MTdruntime by default. If your project usesMD/MDd, you should change MMKV's setting to match your project's (C/C++->Code Generation->Runtime Library), or vice versa. - MMKV is developed with Visual Studio 2017, change the
Platform Toolsetif you use a different version of Visual Studio.
For other installation options, see Windows Setup.
Quick Tutorial
You can use MMKV as you go. All changes are saved immediately, no sync, no save calls needed.
Setup MMKV on App startup, say in your main(), add these lines:
#include <MMKV/MMKV.h>
int main() {
std::wstring rootDir = getYourAppDocumentDir();
MMKV::initializeMMKV(rootDir);
//...
}MMKV has a global instance, that can be used directly:
auto mmkv = MMKV::defaultMMKV();
mmkv->set(true, "bool");
std::cout << "bool = " << mmkv->getBool("bool") << std::endl;
mmkv->set(1024, "int32");
std::cout << "int32 = " << mmkv->getInt32("int32") << std::endl;
mmkv->set("Hello, MMKV for Windows", "string");
std::string result;
mmkv->getString("string", result);
std::cout << "string = " << result << std::endl;MMKV also supports Multi-Process Access. Full tutorials can be found here Windows Tutorial.
MMKV for POSIX
Features
Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of POSIX to achieve the best performance.
- Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no
save, nosynccalls are needed.Small.
- A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
- About 7K in binary size: MMKV adds about 7K on application size, and much less when zipped.
Getting Started
Installation Via CMake
Getting source code from the git repository:
textgit clone https://github.com/Tencent/MMKV.gitEdit your
CMakeLists.txt, add those lines:cmakeadd_subdirectory(mmkv/POSIX/src mmkv) target_link_libraries(MyApp mmkv)Add
#include "MMKV.h"to your source file and we are done.
For other installation options, see POSIX Setup.
Quick Tutorial
You can use MMKV as you go. All changes are saved immediately, no sync, no save calls needed.
Setup MMKV on App startup, say in your main(), add these lines:
#include "MMKV.h"
int main() {
std::string rootDir = getYourAppDocumentDir();
MMKV::initializeMMKV(rootDir);
//...
}MMKV has a global instance, that can be used directly:
auto mmkv = MMKV::defaultMMKV();
mmkv->set(true, "bool");
std::cout << "bool = " << mmkv->getBool("bool") << std::endl;
mmkv->set(1024, "int32");
std::cout << "int32 = " << mmkv->getInt32("int32") << std::endl;
mmkv->set("Hello, MMKV for Windows", "string");
std::string result;
mmkv->getString("string", result);
std::cout << "string = " << result << std::endl;MMKV also supports Multi-Process Access. Full tutorials can be found here POSIX Tutorial.
MMKV for HarmonyOS NEXT
Features
Efficient. MMKV uses mmap to keep memory synced with file, and protobuf to encode/decode values, making the most of native platform to achieve best performance.
- Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no
sync, noflushcalls needed.Small.
- A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics and nothing more. It's really tidy.
- About 600K in binary size: MMKV adds about 600K per architecture on App size, and much less when zipped (HAR/HAP).
Getting Started
Installation via OHPM:
ohpm install @tencent/mmkvQuick Tutorial
You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.
Setup MMKV on App startup, say your EntryAbility.onCreate() function, add these lines:
import { MMKV } from '@tencent/mmkv';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
let appCtx = this.context.getApplicationContext();
let mmkvRootDir = MMKV.initialize(appCtx);
console.info('mmkv rootDir: ', mmkvRootDir);
β¦β¦
}MMKV has a global instance, that can be used directly:
import { MMKV } from '@tencent/mmkv';
let mmkv = MMKV.defaultMMKV();
mmkv.encodeBool('bool', true);
console.info('bool = ', mmkv.decodeBool('bool'));
mmkv.encodeInt32('int32', Math.pow(2, 31) - 1);
console.info('max int32 = ', mmkv.decodeInt32('int32'));
mmkv.encodeInt64('int', BigInt(2**63) - BigInt(1));
console.info('max int64 = ', mmkv.decodeInt64('int'));
let str: string = 'Hello OpenHarmony from MMKV';
mmkv.encodeString('string', str);
console.info('string = ', mmkv.decodeString('string'));
let arrayBuffer: ArrayBuffer = StringToArrayBuffer('Hello OpenHarmony from MMKV with bytes');
mmkv.encodeBytes('bytes', arrayBuffer);
let bytes = mmkv.decodeBytes('bytes');
console.info('bytes = ', ArrayBufferToString(bytes));As you can see, MMKV is quite easy to use.
For the full documentation, see HarmonyOS NEXT Tutorial.
License
MMKV is published under the BSD 3-Clause license. For details check out the LICENSE.TXT.
Change Log
Check out the CHANGELOG.md for details of change history.
Contributing
If you are interested in contributing, check out the CONTRIBUTING.md, also join our Tencent OpenSource Plan. MMKV has officially joined the Tencent Device-oriented Service Product Alliance, working together with other alliance members to build an open and mutually beneficial frontend technology product ecosystem.
To give clarity of what is expected of our members, MMKV has adopted the code of conduct defined by the Contributor Covenant, which is widely used. And we think it articulates our values well. For more, check out the Code of Conduct.
FAQ & Feedback
Check out the FAQ first. Should there be any questions, don't hesitate to create issues.
Personal Information Protection Rules
User privacy is taken very seriously: MMKV does not obtain, collect or upload any personal information. Please refer to the MMKV SDK Personal Information Protection Rules for details.
File: flutter/mmkv/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
Launch Screen Assets
You can customize the launch screen with your own desired assets by replacing the image files in this directory.
You can also do it by opening your Flutter project's Xcode project with open ios/Runner.xcworkspace, selecting Runner/Assets.xcassets in the Project Navigator and dropping in the desired images.
File: flutter/mmkv/example/README.md
mmkv_example
Demonstrates how to use the mmkv plugin.
Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
For help getting started with Flutter, view our
online documentation, which offers tutorials,
samples, guidance on mobile development, and a full API reference.
File: flutter/mmkv/README.md
MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on Android and iOS.
MMKV for Flutter
Features
Efficient. MMKV uses mmap to keep memory synced with file, and protobuf to encode/decode values, making the most of native platform to achieve best performance.
- Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no
sync, noapplycalls needed.Small.
- A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics and nothing more. It's really tidy.
- About 100K in binary size: MMKV adds about 100K per architecture on App size, and much less when zipped (apk/ipa).
Getting Started
Installation
Add the following lines to pubspec.yaml on your app module. Then run flutter pub get.
dependencies:
mmkv: "^2.4.1"If you already include MMKV native lib in your App, you need to upgrade to version newer than v2.0.0.
iOS
Starting from v1.3.5, there's no need to change the plugin name 'mmkv' to 'mmkvflutter'. You should remove the script (fix_mmkv_plugin_name()) previously added in your Podfile.
Android
If you previously use com.tencent.mmkv-static or com.tencent.mmkv-shared in your Android App, you should move to com.tencent.mmkv.
And if your App depends on any 3rd SDK that embeds com.tencent.mmkv-static or com.tencent.mmkv-shared, you can add this lines to your build.gradle to avoid conflict:
dependencies {
...
modules {
module("com.tencent:mmkv-static") {
replacedBy("com.tencent:mmkv", "Using mmkv for flutter")
}
module("com.tencent:mmkv-shared") {
replacedBy("com.tencent:mmkv", "Using mmkv for flutter")
}
}
}Setup
You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.
Setup MMKV on App startup, say your main() function, add these lines:
import 'package:mmkv/mmkv.dart';
void main() async {
// must wait for MMKV to finish initialization
final rootDir = await MMKV.initialize();
print('MMKV for flutter with rootDir = $rootDir');
runApp(MyApp());
}Note that you have to wait for MMKV to finish initialization before accessing any MMKV instance.
CRUD Operations
MMKV has a global instance, that can be used directly:
dartimport 'package:mmkv/mmkv.dart'; var mmkv = MMKV.defaultMMKV(); mmkv.encodeBool('bool', true); print('bool = ${mmkv.decodeBool('bool')}'); mmkv.encodeInt32('int32', (1<<31) - 1); print('max int32 = ${mmkv.decodeInt32('int32')}'); mmkv.encodeInt('int', (1<<63) - 1); print('max int = ${mmkv.decodeInt('int')}'); String str = 'Hello Flutter from MMKV'; mmkv.encodeString('string', str); print('string = ${mmkv.decodeString('string')}'); str = 'Hello Flutter from MMKV with bytes'; var bytes = MMBuffer.fromList(Utf8Encoder().convert(str))!; mmkv.encodeBytes('bytes', bytes); bytes.destroy(); bytes = mmkv.decodeBytes('bytes')!; print('bytes = ${Utf8Decoder().convert(bytes.asList()!)}'); bytes.destroy();As you can see, MMKV is quite easy to use.
Note: If you come across to failing to load
defaultMMKV()on Android after upgrading Flutter from 1.20+ to 2.0+, you can try passing this encryption key'\u{2}U'instead.dartvar mmkv = MMKV.defaultMMKV(cryptKey: '\u{2}U');Deleting & Querying:
dartvar mmkv = MMKV.defaultMMKV(); mmkv.removeValue('bool'); print('contains "bool": ${mmkv.containsKey('bool')}'); mmkv.removeValues(['int32', 'int']); print('all keys: ${mmkv.allKeys}');If different modules/logic need isolated storage, you can also create your own MMKV instance separately:
dartvar mmkv = MMKV("test"); mmkv.encodeBool('bool', true); print('bool = ${mmkv.decodeBool('bool')}');If multi-process accessing is neededοΌyou can set
MMKV.MULTI_PROCESS_MODEon MMKV initialization:dartvar mmkv = MMKV("test-multi-process", mode: MMKVMode.MULTI_PROCESS_MODE); mmkv.encodeBool('bool', true); print('bool = ${mmkv.decodeBool('bool')}');
Supported Types
Primitive Types:
bool, int, double
Classes & Collections:
String, List, MMBuffer
Log
By default, MMKV prints log to logcat/console, which is not convenient for diagnosing online issues.
You can setup MMKV log redirecting on App startup on the native interface of MMKV.
Checkout how to do it on Android / iOS.
Due to the current limitation of Flutter runtime, we can't redirect log on the Flutter side.You can turn off MMKV's logging once and for all on initialization (which we strongly disrecommend).
dartfinal rootDir = await MMKV.initialize(logLevel: MMKVLogLevel.None);
Encryption
By default MMKV stores all key-values in plain text on file, relying on Android's/iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.
dartfinal encryptKey = 'MyEncryptKey'; var mmkv = MMKV("test-encryption", cryptKey: encryptKey);You can change the encryption key later as you like. You can also change an existing MMKV instance from encrypted to unencrypted, or vice versa.
dart// an unencrypted MMKV instance var mmkv = MMKV("test-encryption"); // change from unencrypted to encrypted with AES-128 key length mmkv.reKey("Key_seq_1"); // change encryption key with AES-256 key length mmkv.reKey("Key_Seq_Very_Looooooooong", aes256: true); // change from encrypted to unencrypted kmmkv.reKey(null);
Customize location
By default, MMKV stores file inside
$(FilesDir)/mmkv/. You can customize MMKV's root directory on App startup:dartfinal dir = await getApplicationSupportDirectory(); final rootDir = await MMKV.initialize(dir, rootDir: dir.path + '/mmkv_2'); print('MMKV for flutter with rootDir = $rootDir');You can even customize any MMKV instance's location:
dartfinal dir = await getApplicationSupportDirectory(); var mmkv = MMKV('testCustomDir', rootDir: dir.path + '/mmkv_3');Note: It's recommended to store MMKV files inside your App's sandbox path. DO NOT store them on external storage(aka SD card). If you have to do it, you should follow Android's scoped storage enforcement.
Additional docs
For additional documents, checkout the wiki.
License
MMKV is published under the BSD 3-Clause license. For details check out the LICENSE.TXT.
Change Log
Check out the CHANGELOG.md for details of change history.
Contributing
If you are interested in contributing, check out the CONTRIBUTING.md, also join our Tencent OpenSource Plan.
To give clarity of what is expected of our members, MMKV has adopted the code of conduct defined by the Contributor Covenant, which is widely used. And we think it articulates our values well. For more, check out the Code of Conduct.
FAQ & Feedback
Check out the FAQ first. Should there be any questions, don't hesitate to create issues.
File: flutter/mmkv_android/README.md
mmkv\_android
The Android implementation detail of MMKV.
Usage
Never use it alone. It's NOT a complete set of MMKV functionality. It just provides the FFI implementation needed by MMKV.
This package is endorsed, which means you can simply use mmkv
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your pubspec.yaml.
However, if you import this package to use any of its APIs directly, you
should add it to your pubspec.yaml as usual.
File: flutter/mmkv_ios/README.md
mmkv\_ios
The iOS implementation detail of MMKV.
Usage
Never use it alone. It's NOT a complete set of MMKV functionality. It just provides the FFI implementation needed by MMKV.
This package is endorsed, which means you can simply use mmkv
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your pubspec.yaml.
However, if you import this package to use any of its APIs directly, you
should add it to your pubspec.yaml as usual.
Local MMKV checkout
To run a Flutter app against MMKV sources from a local checkout instead of the
tagged Swift package, set MMKV_LOCAL_PACKAGE_PATH to the checkout root:
MMKV_LOCAL_PACKAGE_PATH=/path/to/MMKV flutter runFile: flutter/mmkv_linux/README.md
mmkv\_linux
The Linux implementation detail of MMKV.
Usage
Never use it alone. It's NOT a complete set of MMKV functionality. It just provides the FFI implementation needed by MMKV.
This package is endorsed, which means you can simply use mmkv
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your pubspec.yaml.
However, if you import this package to use any of its APIs directly, you
should add it to your pubspec.yaml as usual.
File: flutter/mmkv_ohos/README.md
mmkv\_ohos
The OHOS implementation detail of MMKV.
Usage
Never use it alone. It's NOT a complete set of MMKV functionality. It just provides the FFI implementation needed by MMKV.
This package is endorsed, which means you can simply use mmkv
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your pubspec.yaml.
However, if you import this package to use any of its APIs directly, you
should add it to your pubspec.yaml as usual.
File: flutter/mmkv_platform_interface/README.md
mmkv\_platform\_interface
A common platform interface for the MMKV plugin.
This interface allows platform-specific implementations of the MMKV
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.
Usage
To implement a new platform-specific implementation of MMKV, extendMMKVPluginPlatform with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the defaultMMKVPluginPlatform by callingMMKVPluginPlatform.instance = MyMMKVPluginPlatform().
Checkout mmkv_ios or mmkv_android for example.
Note on breaking changes
Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.
See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less-clean interface is preferable to a breaking change.
File: flutter/mmkv_win32/README.md
mmkv\_win32
The Windows implementation detail of MMKV.
Usage
Never use it alone. It's NOT a complete set of MMKV functionality. It just provides the FFI implementation needed by MMKV.
This package is endorsed, which means you can simply use mmkv
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your pubspec.yaml.
However, if you import this package to use any of its APIs directly, you
should add it to your pubspec.yaml as usual.
2. Official Technical Reference & Guides (Tencent/Tencent.github.io)
File: konajdk/sm/README.md
Tencent Kona JDK ShangMi Reference Guide
Overview of ShangMi
ShangMi is a set of cryptographic techniques and tools in commercial or business applications, including the encryption of sensitive business data, secure communication channels, digital signatures for document verification, and even more.
Generally, the below ShangMi cryptographic algorithms and secure communication protocols are widely applied.
ShangMi cryptographic algorithms
- SM2, which is a public key algorithm based on Elliptic Curve Cryptography (ECC). It complies with China's specifications:
- GB/T 32918.1-2016 Part 1οΌGeneral
- GB/T 32918.2-2016 Part 2οΌDigital signature algorithm
- GB/T 32918.3-2016 Part 3οΌKey exchange protocol
- GB/T 32918.4-2016 Part 4οΌPublic key encryption algorithm
- GB/T 32918.5-2017 Part 5οΌParameter definition
- SM3, which is a cryptographic hash algorithm. It complies with China's specification:
- GB/T 32905-2016 SM3 cryptographic hash algorithm
- SM4, which is a block encryption algorithm. It complies with China's specification:
- GB/T 32907-2016 SM4 block cipher algorithm
ShangMi secure communication protocols
- Transport Layer Cryptography Protocol (TLCP), which is a TLS liked protocol. This protocol requires an endpoint must have two certificates, one for signature and the other for encryption. It complies China's specification:
- GB/T 38636-2020 Information security technology-Transport layer cryptography protocol (TLCP)
- ShangMi (SM) Cipher Suites for TLS 1.3, which defines elements for applying ShangMi algorithms over TLS 1.3. It complies IETF's Informational specification:
- RFC 8998 ShangMi (SM) Cipher Suites for TLS 1.3
Providers and implementations
Tencent Kona JDK extends Java Cryptography Architecture (JCA) and Java Cryptography Extension (JCE) providers, exactly SUN, SunEC and SunJCE, to support ShangMi cryptographic algorithms, and extends Java Secure Socket Extension (JSSE) provider, exactly SunJSSE, to support ShangMi secure communication protocols.
The algorithms are implemented by the different security providers in the JDK. The followings list the security providers and the corresponding supported ShangMi algorithms and protocols.
- SUN
- MessageDigest
- SM3
- MessageDigest
- SunEC
- KeyAgreement
- SM2
- KeyFactory
- SM2
- Signature
- SM3withSM2
- KeyAgreement
- SunJCE
- Cipher
- SM4
- KeyGenerator
- HmacSM3
- SM4
- Mac
- HmacSM3
- Cipher
- SunJSSE
- SSLContext
- TLCP 1.1
- ECC_SM4_GCM_SM3
- ECC_SM4_CBC_SM3
- ECDHE_SM4_GCM_SM3
- ECDHE_SM4_CBC_SM3
- TLS 1.3/RFC 8998
- TLS_SM4_GCM_SM3
- TLCP 1.1
- SSLContext
Since Tencent Kona JDK just uses the existing OpenJDK security providers to accommodate the ShangMi stuff, and these providers are already installed with the highest priorities, so the application developers can use these out-of-the-box features as those JDK built-in algorithms (e.g. EC and AES) and protocols (e.g. TLS 1.3).
The following sections will unveil the details on using the above algorithms and protocols.
SM2
Key pair
Generating SM2 key pair is the same as generating the key pairs on other EC curves. It just needs to invoke the standard JDK APIs. The JDK builtin ECKeyPairGenerator. In the key pair generated by this implementation, the format of private key is PKCS#8 and the format of public key is X.509.
Create KeyPairGenerator implementation for EC algorithm.
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC);
keyPairGenerator.initialize(spec);spec can be SM2ParameterSpec (use SM2ParameterSpec.instance() to create the instance) or ECGenParameterSpec (use new ECGenParameterSpec("curveSM2") to create the instance).
Generate key pair.
KeyPair keyPair = keyPairGenerator.generateKeyPair();
ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();SM2 key pair is also EC key pair, so the public key and private key are also ECPublicKey and ECPrivateKey respectively.
For more information on key pair generation, please refer to the official KeyPairGenerator docs.
Generally, in the signing and encrypting operations, the key pairs are already generated. They are not generated on the runtime. It just reads the existing public key and private key to create PublicKey and PrivateKey instances respectively.
byte[] encodedPublicKey = ;
byte[] encodedPrivateKey = ;
KeyFactory keyFactory = KeyFactory.getInstance("SM2");
SM2PublicKeySpec publicKeySpec = new SM2PublicKeySpec(encodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
SM2PrivateKeySpec privateKeySpec = new SM2PrivateKeySpec(encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);Signature
Using SM2 signature is the same as using other existing signatures, like ECDSA, though the parameters are different.
Create Signature instance.
Signature signature = Signature.getInstance("SM3withSM2);Initialize the Signature instance with the private key for signing.
signature.initSign(privateKey);Behind the above initialization, it uses the default SM2 ID, exactly 1234567812345678. It also derives the public key from the private key. According to the associated specification, public key must be used for generating SM2 signature data. This is a significant difference between the international algorithms, like ECDSA, and SM2 signature algorithm. Note that calculating the public key leads to some overhead. That is harmful for the performance.
If not using the default ID or expect to eliminate the cost on calculating public key, it would provide an AlgorithmParameterSpec, exactly SM2SignatureParameterSpec, instance.
byte[] altID = <custom ID>;
ECPublicKey publicKey = ;
SM2SignatureParameterSpec paramSpec = new SM2SignatureParameterSpec(altID, publicKey);
signature.setParameter(paramSpec);
signature.initSign(privateKey);After parameter setup and initialization, it is time to pass the message data in.
byte[] message = ;
signature.update(message);Generate signature data.
byte[] sign = signature.sign();Initialize the Signature instance with public key for verifying.
signature.initVerify(publicKey);Pass the message in.
byte[] message = ;
signature.update(message);Pass the signature data in.
boolean verified = signature.verify(sign);If the verification is successful, the result is true, otherwise false.
It has to know that the private key is used for signing, however the public key is used for verifying. For detailed information about Signature APIs, please refer to the official Signature docs.
Encryption
Because of the performance concern, public key encryption is only used for encrypting short but critical data. The same to SM2 encryption.
Create Cipher instance.
Cipher cipher = Cipher.getInstance("SM2");Initialize the Cipher instance with public key and set the mode to encryption.
cipher.init(Cipher.ENCRYPT_MODE, publicKey);Pass the message in and generate the ciphertext.
byte[] message = ;
byte[] ciphertext = cipher.doFinal(message);Initialize the Cipher instance with private key and set the mode to decryption.
cipher.init(Cipher.DECRYPT_MODE, privateKey);Pass the ciphertext in and generate the plaintext.
byte[] cleartext = cipher.doFinal(ciphertext);It has to know that public key is used for encryption, however the private key is used for decryption. For detailed information on Cipher APIs, please refer to the official Cipher docs.
SM3
Using SM3 hash algorithm is the same as using other existing hash algorithm, like SHA-256. It only invokes JDK APIs to generate the message digest (hash).
Create MessageDigest instance.
MessageDigest md = MessageDigest.getInstance("SM3");It can pass all the message in and generate the digest.
byte[] message = ;
byte[] digest = md.digest(message);It also can pass the message segments, and finally generate the digest.
byte[] messageSegment1 = ;
byte[] messageSegment2 = ;
// Pass the message segments in
md.update(messageSegment1);
md.update(messageSegment2);
// Finally generate the digest
byte[] digest = md.digest();For detailed information about MessageDigest APIs, please refer to the official MessageDigest docs.
HmacSM3
Using HmacSM3 algorithm is the same as using other existing MAC algorithm, like HmacSHA256. It only invokes JDK APIs to generate the message authentication code.
Prepare a 16-bytes key.
byte[] key = ;
SecretKey secretKey = new SecretKeySpec(key, "SM4");Create Mac instance.
Mac hmac = Mac.getInstance("HmacSM3");Initialize the Mac instance with the key.
hmac.init(secretKey);Pass all the message in and generate message authentication code. The code is 32-bytes length.
byte[] message = ;
byte[] mac = hmac.doFinal(message);It also can pass the message segments, and finally generate the message authentication code.
byte[] messageSegment1 = ;
byte[] messageSegment2 = ;
// Pass the message segments in
hmac.update(messageSegment1);
hmac.update(messageSegment2);
// Finally generate the message authentication code
byte[] mac = hmac.doFinal();For the detailed information about Mac APIs, please refer to the official Mac docs.
SM4
Using SM4 cipher algorithm is the same as using other existing block cipher algorithm, like AES. It only invokes JDK APIs to do encryption and decryption. Tencent Kona JDK supports four operation modes, including CBC, CTR, ECB and GCM. It also supports PKCS#7 padding specification.
Prepare a 16-bytes key.
byte[] key = ;
SecretKey secretKey = new SecretKeySpec(key, "SM4");Create Cipher instance.
Cipher cipher = Cipher.getInstance(transformation);The transformation consists of algorithm name, operation mode and padding type. A symbol / is used as separator between the parts.
The following transformations are supported:
- SM4/CBC/NoPadding: The operation mode is CBC. No padding is needed. It requires the input must be 16x bytes.
- SM4/CBC/PKCS7Padding: The operation mode is CBC. PKCS#7 padding is used. It doesn't require that the input must be 16x bytes.
- SM4/CTR/NoPadding: The operation mode is CBC. No padding is needed. It doesn't require that the input must be 16x bytes.
- SM4/ECB/NoPadding: The operation mode is ECB. No padding is needed. It requires the input must be 16x bytes.
- SM4/ECB/PKCS7Padding: The operation mode is ECB. PKCS#7 padding is used. It doesn't require that the input must be 16x bytes.
- SM4/GCM/NoPadding: The operation mode is GCM. No padding is needed. It doesn't require that the input must be 16x bytes.
Create the algorithm parameters.
AlgorithmParameterSpec paramSpec = ;Different operation modes may need different AlgorithmParameterSpec types,
- CBC and CTR modes use IvParameterSpec. This parameter type needs a 16-bytes as Initialization Vector (IV).
- GCM mode uses GCMParameterSpec. This parameter type needs a 12-bytes as Initialization Vector (IV) and specifies the tag length to 12-bytes.
Initialize the Cipher instance with the key and parameter type and set the mode to encryption.
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);Pass all the message in and generate the ciphertext.
byte[] ciphertext = cipher.doFinal(message);Initialize the Cipher instance with the key and parameter type and set the mode to decryption.
cipher.init(Cipher.DECRYPT_MODE, secretKey);Pass all the ciphertext in and generate the plaintext.
byte[] cleartext = cipher.doFinal(ciphertext);It also can receive the plaintext/ciphertext segments in, and then generate the ciphertext/plaintext segments.
byte[] input1 = <segment1>;
byte[] input2 = <segment2>;
// Pass the plaintext/ciphertext segments in
byte[] output1 = cipher.update(input1);
byte[] output2 = cipher.update(input2);
// Generate the ciphertext/plaintext segments
byte[] outputFinal = cipher.doFinal();For the detailed information about Cipher APIs, please refer to the official [Cipher] docs.
Certificate
The so-called ShangMi certificate also complies to X.509 specification, though the public key algorithm is EC with SM2 curve and the signature algorithm is SM3withSM2.
String certPEM = <certificate in PEM format>;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(
new ByteArrayInputStream(certPEM.getBytes(StandardCharsets.UTF_8));For more information on certificate parsing, please read the official reference on CertificateFactory.
It can parse public key from the ShangMi certificate.
PublicKey publicKey = certificate.getPublicKey();publicKey can be cast to ECPublicKey.
It can parse private key from PKCS#8 format.
String peyPEM = ;
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(keyPem));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);privateKey can be cast to ECPrivateKey.
It can sign data with PKCS#8 private key and verify the signature with X.509 certificate.
Create Signature instance and use SM3withSM2 signature algorithm.
Signature signature = Signature.getInstance("SM3withSM2");Sign the message with the private key and generate the signature data.
signature.initSign(privateKey);
signature.update(message);
byte[] sign = signature.sign();Verify the signature data with the certificate and determine whether the verification passes or fails.
signature.initVerify(certificate);
signature.update(message);
boolean verified = signature.verify(sign);The certificate has to contain digitalSignature key usage for verifying signature data. But it also can verify the signature with the public key directly.
signature.initVerify(publicKey);
signature.update(message);
boolean verified = signature.verify(sign);TLCP 1.1 and TLS 1.3/RFC 8998
In order to take advantage of the implementations on TLCP 1.1 and TLS 1.3/RFC 8998, the most important point is taking SSLSocket or SSLEngine to apply the SSLContext implementation that supports the protocols.
KeyStore trustStore = <a trust store carring the CAs>;
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trustStore);
KeyStore keyStore = <a key store carring the end entity certificates>;
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(keyStore, keyStorePassword);
SSLContext context = SSLContext.getInstance("TLCPv1.1");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());When create SSLContext instances, it allows to specify the following context protocols:
- TLCPv1.1, which indicates only TLCP 1.1 is supported.
- TLSv1.3, which indicates only TLS 1.3 is supported.
- TLCP, which indicates TLCP 1.1, TLS 1.3 and TLS 1.2 are supported.
Please read the official JSSE reference for understanding it deeply.
File: konajdk/README.md
Tencent Kona
Tencent Kona is a no-cost, production-ready distribution of the Open Java Development Kit (OpenJDK), Long-Term Support (LTS) with quarterly updates.
Kona serves as the default JDK at Tencent internally, optimized for extreme-scale of Big Data, Machine Learning and Cloud Computing workloads. It is also used to build and maintain a Tencent supported version of OpenJDK for Tencent customers and partners who wish to use OpenJDK to run their applications.
Kona also implements China's cryptographic algorithms, including SM2, SM3 and SM4, and secure communication protocol TLCP (or SMSSL). For more details on these features, please refer to the reference guide.
Supported JDK Releases
Tencent Kona currently supports the JDK Long-Term Support (LTS) releases 8, 11, 17, 21 and 25.
For more details, please go through the individual repository for each of these releases:
- Tencent Kona 8: https://github.com/Tencent/TencentKona-8
- Tencent Kona 11: https://github.com/Tencent/TencentKona-11
- Tencent Kona 17: https://github.com/Tencent/TencentKona-17
- Tencent Kona 21: https://github.com/Tencent/TencentKona-21
- Tencent Kona 25: https://github.com/Tencent/TencentKona-25
Supported System Platforms
Tencent Kona currently supports Linux/x86_64, Linux/aarch64, Windows/x86_64, macOS/x86_64 and macOS/aarch64.
License
Tencent Kona is under the same licensing terms as the upstream OpenJDK project. It is clearly a "friendly fork". Please find the license text for more details.