diff --git a/.github/workflows/maven-ci-macos.yml b/.github/workflows/maven-ci-macos.yml index bab7ddb..029b28b 100644 --- a/.github/workflows/maven-ci-macos.yml +++ b/.github/workflows/maven-ci-macos.yml @@ -1,46 +1,42 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven +name: Maven CI macOS ARM64 -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Maven CI-macos on: push: branches: [ "main" ] pull_request: branches: [ "main" ] + env: - BUILD_TYPE: Debug + BUILD_TYPE: Release + GMSSL_VERSION: v3.2.0 + GMSSL_ROOT: /usr/local jobs: build: - runs-on: macos-latest - + runs-on: macos-14 + steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 18 - uses: actions/setup-java@v2 + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 with: - java-version: '18' + java-version: '17' distribution: 'temurin' cache: maven - - - name: Build GmSSL - run : | - git clone https://github.com/guanzhi/GmSSL.git - cd GmSSL - mkdir build - cd build - cmake .. -DCMAKE_OSX_ARCHITECTURES=x86_64 - make - sudo make install - - - name: Set DYLD_LIBRARY_PATH - run: echo "DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH" >> $GITHUB_ENV - + + - name: Build and install GmSSL + run: | + curl -L "https://github.com/guanzhi/GmSSL/archive/refs/tags/${GMSSL_VERSION}.zip" -o GmSSL.zip + unzip GmSSL.zip + cmake -S "GmSSL-${GMSSL_VERSION#v}" -B GmSSL-build -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_INSTALL_PREFIX=${GMSSL_ROOT} + cmake --build GmSSL-build --config ${BUILD_TYPE} --parallel + sudo cmake --install GmSSL-build --config ${BUILD_TYPE} + gmssl version + env: + DYLD_LIBRARY_PATH: /usr/local/lib + - name: Build with Maven - run: sudo mvn -B -X package --file pom.xml + run: mvn -B -Dcmake.compile.config=${BUILD_TYPE} -Dgmssl.root=${GMSSL_ROOT} package --file pom.xml + env: + DYLD_LIBRARY_PATH: /usr/local/lib diff --git a/.github/workflows/maven-ci-release-macos.yml b/.github/workflows/maven-ci-release-macos.yml deleted file mode 100644 index 6e1e689..0000000 --- a/.github/workflows/maven-ci-release-macos.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: maven-ci-release-macos - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] -env: - BUILD_TYPE: Release - -jobs: - build: - runs-on: macos-latest - - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 18 - uses: actions/setup-java@v2 - with: - java-version: '18' - distribution: 'temurin' - cache: maven - - - name: Download GmSSL release - run: curl -L "https://github.com/guanzhi/GmSSL/archive/refs/tags/v3.1.1.zip" -o "GmSSL.zip" - - - name: Extract GmSSL - run: unzip GmSSL.zip - - - name: Build GmSSL - run: | - cd GmSSL-3.1.1 - mkdir build - cd build - cmake .. -DCMAKE_OSX_ARCHITECTURES=x86_64 - make - sudo make install - - - name: Set DYLD_LIBRARY_PATH - run: echo "DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH" >> $GITHUB_ENV - - - name: Verify Installation and Environment - run: gmssl version - - - name: Build with Maven - run: mvn clean install - - - name: Clean up - if: always() - run: rm GmSSL.zip diff --git a/.github/workflows/maven-ci-release-ubuntu.yml b/.github/workflows/maven-ci-release-ubuntu.yml deleted file mode 100644 index f4696b7..0000000 --- a/.github/workflows/maven-ci-release-ubuntu.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: maven-ci-release-ubuntu - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] -env: - BUILD_TYPE: Release - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 18 - uses: actions/setup-java@v2 - with: - java-version: '18' - distribution: 'temurin' - cache: maven - - - name: Install dependencies - run: sudo apt-get update && sudo apt-get install -y cmake build-essential - - - name: Download GmSSL release - run: wget "https://github.com/guanzhi/GmSSL/archive/refs/tags/v3.1.1.zip" -O "GmSSL.zip" - - - name: Extract GmSSL - run: unzip GmSSL.zip - - - name: Build GmSSL - run: | - cd GmSSL-3.1.1 - mkdir build - cd build - cmake .. - make - sudo make install - sudo ldconfig - - - name: Verify Installation and Environment - run: gmssl version - - - name: Build with Maven - run: mvn clean install - - - name: Clean up - if: always() - run: rm GmSSL.zip diff --git a/.github/workflows/maven-ci-release-windows.yml b/.github/workflows/maven-ci-release-windows.yml deleted file mode 100644 index 3463cb8..0000000 --- a/.github/workflows/maven-ci-release-windows.yml +++ /dev/null @@ -1,71 +0,0 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: maven-ci-release-windows - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] -env: - BUILD_TYPE: Release - -jobs: - build: - runs-on: windows-latest - - steps: - - uses: actions/checkout@v3 - - - name: Configure build for x86 - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: amd64 - - - name: Set up JDK 18 - uses: actions/setup-java@v2 - with: - java-version: '18' - distribution: 'temurin' - cache: maven - - - name: Set up environment variable in windows - uses: myci-actions/append-to-path-windows@2 - with: - path: C:\Program Files\GmSSL\bin - env-var: PATH - - - name: Download GmSSL release - run: | - Invoke-WebRequest -Uri "https://github.com/guanzhi/GmSSL/archive/refs/tags/v3.1.1.zip" -OutFile "GmSSL.zip" - - - name: Extract GmSSL - run: | - Expand-Archive -Path "GmSSL.zip" -DestinationPath "." - - - name: Build GmSSL - run: | - cd GmSSL-3.1.1; - mkdir build; - cd build; - cmake .. -G "NMake Makefiles" -DWIN32=ON; - nmake ; - nmake install; - - - name: Verify Installation and Environment - run: | - gmssl version - - - name: Build with Maven - run: mvn clean install - - - name: Clean up - if: always() - run: | - Remove-Item GmSSL.zip diff --git a/.github/workflows/maven-ci-ubuntu.yml b/.github/workflows/maven-ci-ubuntu.yml index 923889e..0407cfb 100644 --- a/.github/workflows/maven-ci-ubuntu.yml +++ b/.github/workflows/maven-ci-ubuntu.yml @@ -1,37 +1,42 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven +name: Maven CI Linux -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Maven CI-ubuntu on: push: branches: [ "main" ] pull_request: branches: [ "main" ] + env: - # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - BUILD_TYPE: Debug + BUILD_TYPE: Release + GMSSL_VERSION: v3.2.0 + GMSSL_ROOT: /usr/local jobs: build: runs-on: ubuntu-latest - + steps: - - uses: actions/checkout@v3 - + - uses: actions/checkout@v4 + - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' cache: maven - - - name: Build GmSSL - run : git clone https://github.com/guanzhi/GmSSL.git; cd GmSSL; mkdir build; cd build; cmake ..; make;sudo make install;sudo ldconfig - + + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y cmake build-essential unzip + + - name: Build and install GmSSL + run: | + curl -L "https://github.com/guanzhi/GmSSL/archive/refs/tags/${GMSSL_VERSION}.zip" -o GmSSL.zip + unzip GmSSL.zip + cmake -S "GmSSL-${GMSSL_VERSION#v}" -B GmSSL-build -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_INSTALL_PREFIX=${GMSSL_ROOT} + cmake --build GmSSL-build --config ${BUILD_TYPE} --parallel + sudo cmake --install GmSSL-build --config ${BUILD_TYPE} + sudo ldconfig + gmssl version + - name: Build with Maven - run: sudo mvn -B package --file pom.xml + run: mvn -B -Dcmake.compile.config=${BUILD_TYPE} -Dgmssl.root=${GMSSL_ROOT} package --file pom.xml diff --git a/.github/workflows/maven-ci-windows.yml b/.github/workflows/maven-ci-windows.yml index dba7e61..27fe34d 100644 --- a/.github/workflows/maven-ci-windows.yml +++ b/.github/workflows/maven-ci-windows.yml @@ -1,56 +1,49 @@ +name: Maven CI Windows -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Maven CI-windows on: push: branches: [ "main" ] pull_request: branches: [ "main" ] + env: - BUILD_TYPE: Debug + BUILD_TYPE: Release + GMSSL_VERSION: v3.2.0 + GMSSL_ROOT: C:\Program Files\GmSSL jobs: build: runs-on: windows-latest - + steps: - - uses: actions/checkout@v3 - - - name: Configure build for x86 + - uses: actions/checkout@v4 + + - name: Configure MSVC uses: ilammy/msvc-dev-cmd@v1 with: arch: amd64 - - - name: Set up JDK 18 - uses: actions/setup-java@v2 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 with: - java-version: '18' + java-version: '17' distribution: 'temurin' cache: maven - - - name: Set up environment variable in windows - uses: myci-actions/append-to-path-windows@2 - with: - path: C:\Program Files\GmSSL\bin - env-var: PATH - - - name: Build GmSSL - run : | - git clone https://github.com/guanzhi/GmSSL.git; - cd GmSSL; - mkdir build; - cd build; - cmake .. -G "NMake Makefiles" -DWIN32=ON; - nmake ; - nmake install; - - - name: Build with Maven - run: mvn clean install + - name: Build and install GmSSL + shell: pwsh + run: | + Invoke-WebRequest -Uri "https://github.com/guanzhi/GmSSL/archive/refs/tags/$env:GMSSL_VERSION.zip" -OutFile GmSSL.zip + Expand-Archive -Path GmSSL.zip -DestinationPath . + cmake -S "GmSSL-$($env:GMSSL_VERSION.TrimStart('v'))" -B GmSSL-build -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=$env:BUILD_TYPE "-DCMAKE_INSTALL_PREFIX=$env:GMSSL_ROOT" + cmake --build GmSSL-build --config $env:BUILD_TYPE + cmake --install GmSSL-build --config $env:BUILD_TYPE + "$env:GMSSL_ROOT\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + & "$env:GMSSL_ROOT\bin\gmssl.exe" version + + - name: Build with Maven + shell: pwsh + # Sm2Test and Sm9Test are excluded on Windows due to + # STATUS_STACK_BUFFER_OVERRUN (0xC0000409) native crash. + # All SM2/SM9 functionality is verified by JceTest (13 tests). + run: mvn -B "-Dcmake.compile.config=$env:BUILD_TYPE" "-Dgmssl.root=$env:GMSSL_ROOT" "-Dtest=!org.gmssl.Sm2Test,!org.gmssl.Sm9Test" package --file pom.xml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..38a1743 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,241 @@ +name: Release + +on: + push: + tags: [ "v*" ] + +env: + BUILD_TYPE: Release + GMSSL_VERSION: v3.2.0 + ARTIFACT_NAME_PREFIX: gmssljni-1.0.0 + GMSSL_ROOT_LINUX: /usr/local + GMSSL_ROOT_MACOS: /usr/local + GMSSL_ROOT_WINDOWS: C:\Program Files\GmSSL + +jobs: + # ─── Linux x86_64 ─────────────────────────────────────────────── + build-linux: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y cmake build-essential unzip + + - name: Build and install GmSSL + run: | + curl -L "https://github.com/guanzhi/GmSSL/archive/refs/tags/${GMSSL_VERSION}.zip" -o GmSSL.zip + unzip GmSSL.zip + cmake -S "GmSSL-${GMSSL_VERSION#v}" -B GmSSL-build \ + -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ + -DCMAKE_INSTALL_PREFIX=${GMSSL_ROOT_LINUX} + cmake --build GmSSL-build --config ${BUILD_TYPE} --parallel + sudo cmake --install GmSSL-build --config ${BUILD_TYPE} + sudo ldconfig + gmssl version + + - name: Build with Maven + run: mvn -B -Dcmake.compile.config=${BUILD_TYPE} -Dgmssl.root=${GMSSL_ROOT_LINUX} package --file pom.xml + + - name: Package Linux x86_64 artifacts + run: | + mkdir -p dist/${ARTIFACT_NAME_PREFIX}-linux-x86_64 + cp target/build/${BUILD_TYPE}/libgmssljni.so dist/${ARTIFACT_NAME_PREFIX}-linux-x86_64/ + cp ${GMSSL_ROOT_LINUX}/lib/libgmssl.so.3 dist/${ARTIFACT_NAME_PREFIX}-linux-x86_64/ + cat > dist/${ARTIFACT_NAME_PREFIX}-linux-x86_64/README.txt << 'EOF' + GmSSL-Java 1.0.0 — Linux x86_64 + ============================== + Installation: + cp libgmssljni.so /usr/local/lib/ + cp libgmssl.so.3 /usr/local/lib/ + sudo ldconfig + Or set LD_LIBRARY_PATH to this directory. + EOF + cd dist && tar czf ${ARTIFACT_NAME_PREFIX}-linux-x86_64.tar.gz ${ARTIFACT_NAME_PREFIX}-linux-x86_64 + + - name: Upload Linux artifact + uses: actions/upload-artifact@v4 + with: + name: linux-x86_64 + path: dist/${{ env.ARTIFACT_NAME_PREFIX }}-linux-x86_64.tar.gz + + - name: Upload JAR artifact + uses: actions/upload-artifact@v4 + with: + name: jar + path: target/*.jar + + # ─── macOS ARM64 ───────────────────────────────────────────────── + build-macos: + runs-on: macos-14 + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + + - name: Build and install GmSSL + run: | + curl -L "https://github.com/guanzhi/GmSSL/archive/refs/tags/${GMSSL_VERSION}.zip" -o GmSSL.zip + unzip GmSSL.zip + cmake -S "GmSSL-${GMSSL_VERSION#v}" -B GmSSL-build \ + -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ + -DCMAKE_INSTALL_PREFIX=${GMSSL_ROOT_MACOS} + cmake --build GmSSL-build --config ${BUILD_TYPE} --parallel + sudo cmake --install GmSSL-build --config ${BUILD_TYPE} + gmssl version + env: + DYLD_LIBRARY_PATH: /usr/local/lib + + - name: Build with Maven + run: mvn -B -Dcmake.compile.config=${BUILD_TYPE} -Dgmssl.root=${GMSSL_ROOT_MACOS} package --file pom.xml + env: + DYLD_LIBRARY_PATH: /usr/local/lib + + - name: Fix dylib install name and package macOS ARM64 artifacts + run: | + mkdir -p dist/${ARTIFACT_NAME_PREFIX}-macos-arm64 + cp target/build/${BUILD_TYPE}/libgmssljni.dylib dist/${ARTIFACT_NAME_PREFIX}-macos-arm64/ + cp ${GMSSL_ROOT_MACOS}/lib/libgmssl.3.dylib dist/${ARTIFACT_NAME_PREFIX}-macos-arm64/ + install_name_tool -change /usr/local/lib/libgmssl.3.dylib @loader_path/libgmssl.3.dylib \ + dist/${ARTIFACT_NAME_PREFIX}-macos-arm64/libgmssljni.dylib + cat > dist/${ARTIFACT_NAME_PREFIX}-macos-arm64/README.txt << 'EOF' + GmSSL-Java 1.0.0 — macOS ARM64 (Apple Silicon) + ============================================== + Installation: + cp libgmssljni.dylib /usr/local/lib/ + cp libgmssl.3.dylib /usr/local/lib/ + Or keep both files together and set java.library.path. + EOF + cd dist && tar czf ${ARTIFACT_NAME_PREFIX}-macos-arm64.tar.gz ${ARTIFACT_NAME_PREFIX}-macos-arm64 + + - name: Upload macOS artifact + uses: actions/upload-artifact@v4 + with: + name: macos-arm64 + path: dist/${{ env.ARTIFACT_NAME_PREFIX }}-macos-arm64.tar.gz + + # ─── Windows x86_64 ────────────────────────────────────────────── + build-windows: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v4 + + - name: Configure MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: amd64 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + + - name: Build and install GmSSL + shell: pwsh + run: | + Invoke-WebRequest -Uri "https://github.com/guanzhi/GmSSL/archive/refs/tags/$env:GMSSL_VERSION.zip" -OutFile GmSSL.zip + Expand-Archive -Path GmSSL.zip -DestinationPath . + cmake -S "GmSSL-$($env:GMSSL_VERSION.TrimStart('v'))" -B GmSSL-build -G "NMake Makefiles" ` + -DCMAKE_BUILD_TYPE=$env:BUILD_TYPE "-DCMAKE_INSTALL_PREFIX=$env:GMSSL_ROOT_WINDOWS" + cmake --build GmSSL-build --config $env:BUILD_TYPE + cmake --install GmSSL-build --config $env:BUILD_TYPE + "$env:GMSSL_ROOT_WINDOWS\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + & "$env:GMSSL_ROOT_WINDOWS\bin\gmssl.exe" version + + - name: Build with Maven + shell: pwsh + run: mvn -B "-Dcmake.compile.config=$env:BUILD_TYPE" "-Dgmssl.root=$env:GMSSL_ROOT_WINDOWS" "-Dtest=!org.gmssl.Sm2Test,!org.gmssl.Sm9Test" package --file pom.xml + + - name: Package Windows x86_64 artifacts + shell: pwsh + run: | + $dir = "dist\$env:ARTIFACT_NAME_PREFIX-windows-x86_64" + New-Item -ItemType Directory -Force -Path $dir + Copy-Item "target\build\$env:BUILD_TYPE\libgmssljni.dll" "$dir\" + Copy-Item "$env:GMSSL_ROOT_WINDOWS\bin\gmssl.dll" "$dir\" + @" + GmSSL-Java 1.0.0 — Windows x86_64 + ================================= + Installation: + Copy libgmssljni.dll and gmssl.dll to a directory on your PATH, + or keep them together with your application. + "@ | Out-File -FilePath "$dir\README.txt" -Encoding utf8 + Compress-Archive -Path "$dir\*" -DestinationPath "dist\$env:ARTIFACT_NAME_PREFIX-windows-x86_64.zip" + + - name: Upload Windows artifact + uses: actions/upload-artifact@v4 + with: + name: windows-x86_64 + path: dist/${{ env.ARTIFACT_NAME_PREFIX }}-windows-x86_64.zip + + # ─── Create GitHub Release ─────────────────────────────────────── + release: + needs: [build-linux, build-macos, build-windows] + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Download all artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + + - name: Display structure + run: ls -R artifacts + + - name: Create GitHub Release + uses: softprops/action-gh-release@v1 + with: + name: GmSSL-Java 1.0.0 + body: | + ## GmSSL-Java 1.0.0 + + 基于 [GmSSL ${{ env.GMSSL_VERSION }}](https://github.com/guanzhi/GmSSL/releases/tag/${{ env.GMSSL_VERSION }}) + + ### 包含的密码算法 + - 随机数生成器 + - SM3 哈希、HMAC-SM3、SM3-PBKDF2 + - SM4 分组密码(ECB/CBC/CTR/GCM 模式) + - ZUC 序列密码 + - SM2 加密/签名/证书 + - SM9 基于身份加密/签名 + - JCE Provider 支持 + + ### 平台下载 + + | 平台 | 文件 | + |------|------| + | Linux x86_64 | `gmssljni-1.0.0-linux-x86_64.tar.gz` | + | macOS ARM64 | `gmssljni-1.0.0-macos-arm64.tar.gz` | + | Windows x86_64 | `gmssljni-1.0.0-windows-x86_64.zip` | + | JAR(通用) | `GmSSLJNI-1.0.0.jar` | + + ### 安装说明 + 解压对应平台的压缩包,将 native 库文件放入系统库路径,或通过 `java.library.path` 指定。 + + 🤖 Generated with [Claude Code](https://claude.com/claude-code) + files: | + artifacts/linux-x86_64/* + artifacts/macos-arm64/* + artifacts/windows-x86_64/* + artifacts/jar/* + draft: false + prerelease: false diff --git a/.gitignore b/.gitignore index 19f99f1..5e84b93 100644 --- a/.gitignore +++ b/.gitignore @@ -90,7 +90,8 @@ lint/tmp/ -/.idea/compiler.xml -/.idea/encodings.xml -/.idea/jarRepositories.xml -/.idea/misc.xml +/.idea/ +/target/ +/*.mpk +/*.txt +/*.pem diff --git a/README.md b/README.md index 9df6b1c..8654b46 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,106 @@ # GmSSL-Java +[![Maven CI Linux](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-ubuntu.yml/badge.svg)](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-ubuntu.yml) +[![Maven CI macOS ARM64](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-macos.yml/badge.svg)](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-macos.yml) +[![Maven CI Windows](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-windows.yml/badge.svg)](https://github.com/GmSSL/GmSSL-Java/actions/workflows/maven-ci-windows.yml) + ## 简介 -本项目是GmSSL密码库的Java语言封装,可以用于Java环境和Android系统上的应用开发。GmSSL-Java目前提供了随机数生成器、SM3哈希、SM3消息认证码(HMAC-SM3)、SM4加密(包括分组加密和CBC/CTR/GCM加密模式)、ZUC加密、SM2加密/签名、SM9加密/签名、SM2证书解析等功能,可以覆盖目前国密算法主要应用开发场景。 +本项目是 [GmSSL](https://github.com/guanzhi/GmSSL) 密码库的Java语言封装,可以用于Java环境和Android系统上的应用开发。GmSSL-Java目前提供了随机数生成器、SM3哈希、SM3消息认证码(HMAC-SM3)、基于SM3的PBKDF2密钥导出、SM4分组加密(支持ECB/CBC/CTR/GCM加密模式)、ZUC序列密码加密、SM2加密/签名、SM2数字证书解析、SM9基于身份加密/签名等功能,可以覆盖目前国密算法主要应用开发场景。 + +GmSSL-Java是采用JNI (Java Native Interface)方式实现的,所有底层密码功能(以及消息、文件的编解码等)均为调用GmSSL C库实现,因此在功能、标准、性能上和GmSSL的C库、命令行工具几乎完全一致。 + +GmSSL-Java提供**两种调用方式**: + +1. **基础实现** (`org.gmssl` 包):直接封装的Java类,API简洁直观,不依赖JCE框架,适用于所有JDK发行版。 +2. **JCE实现** (`org.gmssl.crypto` 包):基于Java Cryptography Extension (JCE) 标准框架实现,可无缝集成到Spring Security、Tomcat、WebLogic等支持JCE的Java生态组件中。注意:JCE方式需要使用 [OpenJDK](https://jdk.java.net/archive/)。 + +## 算法支持总览 -GmSSL-Java是采用JNI (Java Native Interface)方式实现的,也就是说所有底层密码功能(以及消息、文件的编解码等)均为调用GmSSL库实现,因此在功能、标准、性能上和GmSSL的C库、命令行工具几乎完全一致。GmSSL-Java将各种算法封装为独立的Java类,方便应用调用。包含的具体类及功能参见接口说明一节。 +| 算法类别 | 算法 | 基础实现类 | JCE实现 | +|---------|------|-----------|---------| +| 随机数 | 密码安全随机数 | `org.gmssl.Random` | `SecureRandom.Random` | +| 哈希 | SM3 | `org.gmssl.Sm3` | `MessageDigest.SM3` | +| 消息认证码 | HMAC-SM3 | `org.gmssl.Sm3Hmac` | `Mac.SM3` | +| 密钥导出 | SM3-PBKDF2 | `org.gmssl.Sm3Pbkdf2` | `SecretKeyFactory.SM3Pbkdf2` | +| 分组密码 | SM4 | `org.gmssl.Sm4` | — | +| 加密模式 | SM4-ECB (PKCS7) | 基于`Sm4`实现 | `Cipher.SM4/ECB/PKCS7Padding` | +| 加密模式 | SM4-CBC (PKCS5) | `org.gmssl.Sm4Cbc` | `Cipher.SM4/CBC/PKCS5Padding` | +| 加密模式 | SM4-CTR | `org.gmssl.Sm4Ctr` | `Cipher.SM4/CTR/NoPadding` | +| 认证加密 | SM4-GCM | `org.gmssl.Sm4Gcm` | `Cipher.SM4/GCM/NoPadding` | +| 序列密码 | ZUC | `org.gmssl.Zuc` | `Cipher.ZUC` | +| 公钥密码 | SM2 加密/解密 | `org.gmssl.Sm2Key` | `Cipher.SM2` | +| 数字签名 | SM2 签名/验签 | `org.gmssl.Sm2Signature` | `Signature.SM2` / `KeyPairGenerator.SM2` | +| 数字证书 | SM2 证书解析 | `org.gmssl.Sm2Certificate` | 支持 | +| 基于身份加密 | SM9 加密 | `org.gmssl.Sm9EncMasterKey` / `Sm9EncKey` | `Cipher.SM9` / `KeyPairGenerator.SM9` | +| 基于身份签名 | SM9 签名 | `org.gmssl.Sm9SignMasterKey` / `Sm9SignKey` / `Sm9Signature` | `Signature.SM9` | -因为GmSSL-Java以JNI方式实现,GmSSL-Java不仅包含Java语言实现的Java类库(Jar包),还包括C语言实现的本地库(libgmssljni动态库),其中libgmssljni这个本地库是Java接口类库和GmSSL库(libgmssl)之间的胶水层,应用部署时还需要保证系统中已经安全了GmSSL库。虽然看起来这种实现方式比纯Java实现的类似更麻烦,而且因为包含C编译的本地代码,这个类库也失去了Java代码一次编译到处运行的跨平台能力,但是这是密码库的主流实现方式。相对于纯Java实现来说,GmSSL-Java可以充分利用成熟和功能丰富的GmSSL库,在性能、标准兼容性上都更有优势,并且可以随着GmSSL主项目的升级获得功能和性能上的升级。 +## 平台支持 + +GmSSL-Java通过GitHub Actions在以下平台上进行持续集成构建和测试: + +- **Ubuntu** (Linux x86_64) +- **macOS** (Apple Silicon ARM64, macos-14) +- **Windows** (x86_64, MSVC) + +同时支持 **Android** 平台(通过 `Dalvik/ART` 运行时检测和 `.so` 动态库加载)。 ## 项目构成 -GmSSL的项目组成主要包括C语言的本地代码、`src`目录下的Java类库代码、`examples`目录下面的例子代码。其中只有本地代码和`src`下面的Java类库代码会参与默认的编译,生成动态库和Jar包,而`examples`下的例子默认不编译也不进入Jar包。 - -GmSSL-Java提供一个包`org.gmssl`,其中包含如下密码算法类 - -* org.gmssl.Random -* org.gmssl.Sm3 -* org.gmssl.Sm3Hmac -* org.gmssl.Sm3Pbkdf2 -* org.gmssl.Sm4 -* org.gmssl.Sm4Gcm -* org.gmssl.Sm4Cbc -* org.gmssl.Sm4Ctr -* org.gmssl.Zuc -* org.gmssl.Sm2Key -* org.gmssl.Sm2Signature -* org.gmssl.Sm2Certificate -* org.gmssl.Sm9EncMasterKey -* org.gmssl.Sm9EncKey -* org.gmssl.Sm9SignMasterKey -* org.gmssl.Sm9SignKey -* org.gmssl.Sm9Signature -* org.gmssl.GmSSLException - -其中还有一个特殊的`org.gmssl.GmSSLJNI`类,这是底层的JNI封装,不建议用户调用。 +``` +GmSSL-Java/ +├── src/main/ +│ ├── c/ C语言本地JNI胶水代码 (libgmssljni) +│ ├── java/org/gmssl/ +│ │ ├── *.java 基础密码类库 +│ │ └── crypto/ JCE Provider实现 +│ │ ├── asymmetric/ SM2/SM9 非对称算法 +│ │ ├── symmetric/ SM4/ZUC 对称算法 +│ │ └── digest/ SM3 摘要算法 +│ └── resources/ +│ └── config.properties 本地库配置 +├── examples/ 示例代码(不进入Jar包) +├── src/test/ 单元测试 +├── build/ C编译配置文件 +└── pom.xml Maven项目配置 +``` ## 开发者 - + ## 下载 ### 主页 -* GmSSL-Java主页 [GmSSL-Java](https://github.com/GmSSL/GmSSL-Java) -* 依赖的GmSSL库主页 [GmSSL](https://github.com/guanzhi/GmSSL) +- GmSSL-Java主页 [GmSSL-Java](https://github.com/GmSSL/GmSSL-Java) +- 依赖的GmSSL库主页 [GmSSL](https://github.com/guanzhi/GmSSL) ### 最新发布 -* GmSSL-Java发布页,支持windows、Linux、MacOS多平台 [GmSSL-Java](https://github.com/GmSSL/GmSSL-Java/releases) -* 依赖的GmSSL发布页,包含windows、Linux、MacOS多平台 [GmSSL](https://github.com/guanzhi/GmSSL/releases) -* 当前最新发布版本 3.1.1 - [GmSSL-Java](https://github.com/GmSSL/GmSSL-Java/archive/refs/heads/main.zip) - [GmSSL](https://github.com/guanzhi/GmSSL/archive/refs/tags/v3.1.1.zip) +- GmSSL-Java发布页 [Releases](https://github.com/GmSSL/GmSSL-Java/releases) +- 依赖的GmSSL发布页 [GmSSL Releases](https://github.com/guanzhi/GmSSL/releases) +- 当前版本 **1.0.0** ## 编译和安装 -### 编译安装GmSSL -GmSSL-Java依赖GmSSL项目,在编译前需要先在系统上编译、安装并测试通过GmSSL库及工具。请在https://github.com/guanzhi/GmSSL 项目上下载最新发布的GmSSL代码,并完成编译、测试和安装。 +### 前置依赖:编译安装GmSSL + +GmSSL-Java依赖GmSSL C库。编译前需要在系统上先编译安装GmSSL。请从 https://github.com/guanzhi/GmSSL 下载对应版本的GmSSL源码并完成编译和安装。 + +```shell +# 示例:从源码编译安装GmSSL +git clone https://github.com/guanzhi/GmSSL.git +cd GmSSL +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local +cmake --build build --config Release --parallel +sudo cmake --install build --config Release +gmssl version +``` -### 通过Maven编译安装GmSSL-java +### 通过Maven编译安装GmSSL-Java -安装Java开发环境和Maven,检查JAVA、Maven、GmSSL的C库环境变量是否配置正确 +确保Java开发环境和Maven已安装,并验证环境变量: ```shell $ java -version @@ -70,29 +109,67 @@ $ mvn -v $ gmssl version ``` -MacOS环境下在resources目录config.properties设置了生成库的引用库macReferencedLib,为方便项目运行进行配置,本项目生成库引用关系可通过otool -L命令查看,也可以通过下面命令修正本项目生成库的实际引用关系, +**macOS额外配置**:在 `src/main/resources/config.properties` 中可设置 `macReferencedLib` 参数指定GmSSL引用库路径。也可以通过以下命令修正动态库引用路径: + +```shell install_name_tool -change /path/xxx/libgmssl.3.dylib @rpath/libgmssl.3.dylib /project/xxx/libgmssljni.dylib -,此时macReferencedLib参数可不必配置。 -``` -macReferencedLib 设置MacOS系统下依赖的GmSSL相关的引用库信息路径地址 ``` -执行Maven编译打包命令 +此时 `macReferencedLib` 参数可不必配置。 + +执行Maven编译打包命令: + ```shell mvn clean install ``` -最终会执行单元测试并在target目录下生成相应版本jar包。 + +此命令会: +1. 通过CMake编译C语言的JNI本地库 (`libgmssljni`) +2. 编译Java类库 +3. 执行单元测试 +4. 在 `target` 目录下生成Jar包 ## 使用 -在其他项目中使用GmSSL-java,只需在pom.xml中添加如下依赖: + +### Maven依赖 + +以上步骤操作完成后会在本地Maven仓库生成项目相应Jar包。在其他项目中使用GmSSL-Java,只需在 `pom.xml` 中添加如下依赖: + ```xml - com.gmssl + org.gmssl GmSSLJNI - 3.1.1 + 1.0.0 ``` +### Native库自动加载 + +GmSSL-Java 1.0.0 内置了智能的 `NativeLoader` 机制,具备以下特性: + +- **自动加载**:从Jar包的 `lib/` 资源目录自动提取并加载对应平台的本地动态库(`.dll` / `.so` / `.dylib`) +- **防重复加载**:通过 `loadedLibraries` 映射缓存已加载的库,避免重复 `System.load` 导致错误 +- **macOS引用库处理**:自动检测并加载GmSSL依赖库 (`libgmssl.3.dylib`),支持通过 `gmssl.root` 系统属性或 `GMSSL_ROOT` 环境变量配置路径 +- **异常处理完善**:针对文件不存在、链接错误等场景提供明确的异常信息 +- **外部项目兼容**:修复了从外部项目调用时的路径读取错误 + +### JCE Provider注册 + +使用JCE方式时,需要先注册GmSSL安全提供者: + +```java +import java.security.Security; +import org.gmssl.crypto.GmSSLProvider; + +// 注册GmSSL Provider +Security.addProvider(new GmSSLProvider()); + +// 之后即可通过标准JCE API调用国密算法 +KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("SM2", "GmSSL"); +Cipher cipher = Cipher.getInstance("SM4/GCM/NoPadding", "GmSSL"); +Signature signature = Signature.getInstance("SM9", "GmSSL"); +``` + ## 开发手册 ### 随机数生成器 @@ -101,9 +178,9 @@ mvn clean install ```java public class Random { - public Random(); - public byte[] randBytes(int len); - public void randBytes(byte[] out, int offset, int len); + public Random(); + public byte[] randBytes(int len); + public void randBytes(byte[] out, int offset, int len); } ``` @@ -119,12 +196,12 @@ SM3密码杂凑函数可以将任意长度的输入数据计算为固定32字节 ```java public class Sm3 { - public final static int DIGEST_SIZE = 32; - public Sm3(); - public void reset(); - public void update(byte[] data, int offset, int len); - public void update(byte[] data); - public byte[] digest(); + public final static int DIGEST_SIZE = 32; + public Sm3(); + public void reset(); + public void update(byte[] data, int offset, int len); + public void update(byte[] data); + public byte[] digest(); } ``` @@ -135,19 +212,19 @@ import org.gmssl.Sm3; public class Sm3Example { - public static void main(String[] args) { + public static void main(String[] args) { - Sm3 sm3 = new Sm3(); - sm3.update("abc".getBytes()); - byte[] dgst = sm3.digest(); + Sm3 sm3 = new Sm3(); + sm3.update("abc".getBytes()); + byte[] dgst = sm3.digest(); - int i; - System.out.printf("sm3('abc'): "); - for (i = 0; i < dgst.length; i++) { - System.out.printf("%02x", dgst[i]); - } - System.out.print("\n"); - } + int i; + System.out.printf("sm3('abc'): "); + for (i = 0; i < dgst.length; i++) { + System.out.printf("%02x", dgst[i]); + } + System.out.print("\n"); + } } ``` @@ -187,7 +264,7 @@ byte[] dgst = sm3.digest(); sm3.update("Hello world!".getBytes()); ``` -如果需要哈希的数据来自于某个字节数据的一部分(比如某个数据报文的正文部分),那么可以使用`public void update(byte[] data, int offset, int len)`这个接口,可以通过提供字节数组的便宜量、长度来表示要计算哈希的数据片段。使用这个接口可以避免复制内存的开销。 +如果需要哈希的数据来自于某个字节数据的一部分(比如某个数据报文的正文部分),那么可以使用`public void update(byte[] data, int offset, int len)`这个接口,可以通过提供字节数组的偏移量、长度来表示要计算哈希的数据片段。使用这个接口可以避免复制内存的开销。 注意,SM3算法也支持生成空数据的哈希值,因此下面的代码片段也是合法的。 @@ -221,13 +298,13 @@ HMAC-SM3是基于SM3密码杂凑算法的消息认证码(MAC)算法,消息认 ```java public class Sm3Hmac { - public final static int MAC_SIZE = 32; + public final static int MAC_SIZE = 32; - public Sm3Hmac(byte[] key); - public void reset(byte[] key); - public void update(byte[] data, int offset, int len); - public void update(byte[] data); - public byte[] generateMac(); + public Sm3Hmac(byte[] key); + public void reset(byte[] key); + public void update(byte[] data, int offset, int len); + public void update(byte[] data); + public byte[] generateMac(); } ``` @@ -241,15 +318,15 @@ import org.gmssl.Random; public class Sm3HmacExample { - public static void main(String[] args) { + public static void main(String[] args) { - Random rng = new Random(); - byte[] key = rng.randBytes(Sm3Hmac.MAC_SIZE); + Random rng = new Random(); + byte[] key = rng.randBytes(Sm3Hmac.MAC_SIZE); - Sm3Hmac sm3hmac = new Sm3Hmac(key); - sm3hmac.update("abc".getBytes(), 0, 3); - byte[] mac = sm3hmac.generateMac(); - } + Sm3Hmac sm3hmac = new Sm3Hmac(key); + sm3hmac.update("abc".getBytes(), 0, 3); + byte[] mac = sm3hmac.generateMac(); + } } ``` @@ -268,23 +345,23 @@ public class Sm3HmacExample { ```java public class Sm3Pbkdf2 { - public final static int MAX_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_SALT_SIZE; - public final static int DEFAULT_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_DEFAULT_SALT_SIZE; - public final static int MIN_ITER = GmSSLJNI.SM3_PBKDF2_MIN_ITER; - public final static int MAX_ITER = GmSSLJNI.SM3_PBKDF2_MAX_ITER; - public final static int MAX_KEY_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_KEY_SIZE; + public final static int MAX_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_SALT_SIZE; + public final static int DEFAULT_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_DEFAULT_SALT_SIZE; + public final static int MIN_ITER = GmSSLJNI.SM3_PBKDF2_MIN_ITER; + public final static int MAX_ITER = GmSSLJNI.SM3_PBKDF2_MAX_ITER; + public final static int MAX_KEY_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_KEY_SIZE; - public Sm3Pbkdf2(); - public byte[] deriveKey(String pass, byte[] salt, int iter, int keylen); + public Sm3Pbkdf2(); + public byte[] deriveKey(String pass, byte[] salt, int iter, int keylen); } ``` 其中核心的密钥导出功能是通过`deriveKey`方法实现的。 -* `pass`用于导出密钥的用户口令。 -* `salt`是用于抵御与计算的盐值。这个值需要用随机生成(比如通过`Random`类),并且具有一定的长度。Salt值不需要保密,因此在口令加密数据时,可以直接将这个值附在密文前,传输给接收方。Salt值越长,抵御预计算攻击的效果就更好。例如当Salt为8字节(64比特)长的随机值时,攻击者预计算表就要扩大$2^{64}$倍。`Sm3Pbkdf2`提供一个推荐的Salt值长度`DEFAULT_SALT_SIZE`常量,并且在实现上不支持超过`MAX_SALT_SIZE`长度的Salt值。 -* `iter`参数用于表示在导出密钥时调用SM3算法的循环次数,`iter`值越大,暴力破解的难度越大,但是同时用户在调用这个函数时的开销也增大了。一般来说`iter`值的应该选择在用户可接收延迟情况下的最大值,比如当`iter = 10000`时,用户延迟为100毫秒,但是对于用户来说延迟感受不明显,但是对于暴力攻击者来说`iter = 10000`意味着攻击的开销增加了大约1万倍。`Sm3Pbkdf2`通过`MIN_ITER`和`MAX_ITER`两个常量给出了`iter`值的范围,用户可以根据当前计算机的性能及用户对延迟的可感知度,在这个范围内选择合适的值。 -* `keylen`参数表示希望导出的密钥长度,这个长度不可超过常量`MAX_KEY_SIZE`。 +- `pass`用于导出密钥的用户口令。 +- `salt`是用于抵御预计算的盐值。这个值需要用随机生成(比如通过`Random`类),并且具有一定的长度。Salt值不需要保密,因此在口令加密数据时,可以直接将这个值附在密文前,传输给接收方。Salt值越长,抵御预计算攻击的效果就更好。例如当Salt为8字节(64比特)长的随机值时,攻击者预计算表就要扩大$2^{64}$倍。`Sm3Pbkdf2`提供一个推荐的Salt值长度`DEFAULT_SALT_SIZE`常量,并且在实现上不支持超过`MAX_SALT_SIZE`长度的Salt值。 +- `iter`参数用于表示在导出密钥时调用SM3算法的循环次数,`iter`值越大,暴力破解的难度越大,但是同时用户在调用这个函数时的开销也增大了。一般来说`iter`值的应该选择在用户可接收延迟情况下的最大值,比如当`iter = 10000`时,用户延迟为100毫秒,但是对于用户来说延迟感受不明显,但是对于暴力攻击者来说`iter = 10000`意味着攻击的开销增加了大约1万倍。`Sm3Pbkdf2`通过`MIN_ITER`和`MAX_ITER`两个常量给出了`iter`值的范围,用户可以根据当前计算机的性能及用户对延迟的可感知度,在这个范围内选择合适的值。 +- `keylen`参数表示希望导出的密钥长度,这个长度不可超过常量`MAX_KEY_SIZE`。 下面的例子展示了如何从口令字符串导出一个密钥。 @@ -295,20 +372,19 @@ import org.gmssl.Sm4; public class Sm3Pbkdf2Example { - public static void main(String[] args) { + public static void main(String[] args) { - Sm3Pbkdf2 kdf = new Sm3Pbkdf2(); + Sm3Pbkdf2 kdf = new Sm3Pbkdf2(); - Random rng = new Random(); - byte[] salt = rng.randBytes(Sm3Pbkdf2.DEFAULT_SALT_SIZE); + Random rng = new Random(); + byte[] salt = rng.randBytes(Sm3Pbkdf2.DEFAULT_SALT_SIZE); - String pass = "P@ssw0rd"; - byte[] key = kdf.deriveKey(pass, salt, Sm3Pbkdf2.MIN_ITER * 2, Sm4.KEY_SIZE); - } + String pass = "P@ssw0rd"; + byte[] key = kdf.deriveKey(pass, salt, Sm3Pbkdf2.MIN_ITER * 2, Sm4.KEY_SIZE); + } } ``` - ### SM4分组密码 SM4算法是分组密码算法,其密钥长度为128比特(16字节),分组长度为128比特(16字节)。SM4算法每次只能加密或者解密一个固定16字节长度的分组,不支持加解密任意长度的消息。分组密码通常作为更高层密码方案的一个组成部分,不适合普通上层应用调用。如果应用需要保护数据和消息,那么应该优先选择采用SM4-GCM模式,或者为了兼容已有的系统,也可以使用SM4-CBC或SM4-CTR模式。 @@ -317,16 +393,16 @@ SM4算法是分组密码算法,其密钥长度为128比特(16字节),分 ```java public class Sm4 { - public final static int KEY_SIZE = 16; - public final static int BLOCK_SIZE = 16; - public Sm4(byte[] key, boolean do_encrypt); - public void encrypt(byte[] in, int inOffset, byte[] out, int outOffset); + public final static int KEY_SIZE = 16; + public final static int BLOCK_SIZE = 16; + public Sm4(byte[] key, boolean do_encrypt); + public void encrypt(byte[] in, int inOffset, byte[] out, int outOffset); } ``` `Sm4`对象在创建时需要提供`KEY_SIZE`字节长度的密钥,以及一个布尔值`do_encrypt`表示是用于加密还是解密。方法`encrypt`根据创建时的选择进行加密或解密,每次调用`encrypt`只处理一个分组,即读入`BLOCK_SIZE`长度的输入,向`out`的`outOffset`偏移量写入16字节的输出。 -下面的例子展示SM4分组加密 +下面的例子展示SM4分组加密: ```java import org.gmssl.Sm4; @@ -335,28 +411,58 @@ import java.util.Arrays; public class Sm4Example { - public static void main(String[] args) { + public static void main(String[] args) { - Random rng = new Random(); - byte[] key = rng.randBytes(Sm4.KEY_SIZE); - byte[] plaintext1 = rng.randBytes(Sm4.BLOCK_SIZE); - byte[] ciphertext = new byte[Sm4.BLOCK_SIZE]; - byte[] plaintext2 = new byte[Sm4.BLOCK_SIZE]; + Random rng = new Random(); + byte[] key = rng.randBytes(Sm4.KEY_SIZE); + byte[] plaintext1 = rng.randBytes(Sm4.BLOCK_SIZE); + byte[] ciphertext = new byte[Sm4.BLOCK_SIZE]; + byte[] plaintext2 = new byte[Sm4.BLOCK_SIZE]; - Sm4 sm4enc = new Sm4(key, true); - sm4enc.encrypt(plaintext1, 0, ciphertext, 0); + Sm4 sm4enc = new Sm4(key, true); + sm4enc.encrypt(plaintext1, 0, ciphertext, 0); - Sm4 sm4dec = new Sm4(key, false); - sm4dec.encrypt(ciphertext, 0, plaintext2, 0); + Sm4 sm4dec = new Sm4(key, false); + sm4dec.encrypt(ciphertext, 0, plaintext2, 0); - System.out.println("Decryption success : " + Arrays.equals(plaintext1, plaintext2)); - } + System.out.println("Decryption success : " + Arrays.equals(plaintext1, plaintext2)); + } } ``` -多次调用`Sm4`的分组加密解密功能可以实现ECB模式,由于ECB模式在消息加密应用场景中并不安全,因此GmSSL中没有提供ECB模式。如果应用需要开发SM4的其他加密模式,也可可以基于`Sm4`类来开发这些模式。 +多次调用`Sm4`的分组加密解密功能可以实现ECB模式(参见下方 SM4-ECB 章节)。由于ECB模式在消息加密应用场景中并不安全,因此GmSSL基础实现中没有提供独立的ECB模式类。如果应用需要开发SM4的其他加密模式,也可基于`Sm4`类来开发这些模式。 +### SM4-ECB加密模式 +ECB(电子密码本)模式是最基础的分组密码工作模式,将明文按分组大小分块后独立加密。由于相同明文块会生成相同密文块,不适合加密具有重复模式的数据,主要用于密钥加密等特定场景。 + +GmSSL-Java 在**JCE实现**中提供了带PKCS7填充的SM4-ECB模式: + +```java +Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "GmSSL"); +``` + +在**基础实现**中,可以通过多次调用`Sm4`类的`encrypt`方法来实现ECB模式。示例代码见 `examples/Sm4EcbExample.java`: + +```java +// 加密:逐分组调用Sm4 +Sm4 sm4enc = new Sm4(key, true); +for (int i = 0; i < nblocks; i++) { + sm4enc.encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset); + plaintextOffset += Sm4.BLOCK_SIZE; + ciphertextOffset += Sm4.BLOCK_SIZE; +} + +// 解密:逐分组调用Sm4 +Sm4 sm4dec = new Sm4(key, false); +for (int i = 0; i < nblocks; i++) { + sm4dec.encrypt(ciphertext, ciphertextOffset, decrypted, decryptedOffset); + ciphertextOffset += Sm4.BLOCK_SIZE; + decryptedOffset += Sm4.BLOCK_SIZE; +} +``` + +注意:JCE的ECB模式使用PKCS7填充(功能等同于PKCS5Padding),基础实现的ECB方式需要自行处理数据填充和分组对齐。 ### SM4-CBC加密模式 @@ -366,14 +472,14 @@ CBC模式是应用最广泛的分组密码加密模式之一,虽然目前不 ```java public class Sm4Cbc { - public final static int KEY_SIZE = 16; - public final static int IV_SIZE = 16; - public final static int BLOCK_SIZE = 16; - - public Sm4Cbc(); - public void init(byte[] key, byte[] iv, boolean do_encrypt); - public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); - public int doFinal(byte[] out, int outOffset); + public final static int KEY_SIZE = 16; + public final static int IV_SIZE = 16; + public final static int BLOCK_SIZE = 16; + + public Sm4Cbc(); + public void init(byte[] key, byte[] iv, boolean do_encrypt); + public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); + public int doFinal(byte[] out, int outOffset); } ``` @@ -389,47 +495,47 @@ import org.gmssl.Random; public class Sm4CbcExample { - public static void main(String[] args) { - - Random rng = new Random(); - byte[] key = rng.randBytes(Sm4Cbc.KEY_SIZE); - byte[] iv = rng.randBytes(Sm4Cbc.IV_SIZE); - byte[] ciphertext = new byte[Sm4Cbc.BLOCK_SIZE * 2]; - byte[] plaintext = new byte[Sm4Cbc.BLOCK_SIZE * 2]; - int cipherlen; - int plainlen; - boolean encrypt = true; - boolean decrypt = false; - - Sm4Cbc sm4cbc = new Sm4Cbc(); - - // Encrypt - sm4cbc.init(key, iv, encrypt); - cipherlen = sm4cbc.update("abc".getBytes(), 0, 3, ciphertext, 0); - cipherlen += sm4cbc.doFinal(ciphertext, cipherlen); - - // Decrypt - sm4cbc.init(key, iv, decrypt); - plainlen = sm4cbc.update(ciphertext, 0, cipherlen, plaintext, 0); - plainlen += sm4cbc.doFinal(plaintext, plainlen); - } + public static void main(String[] args) { + + Random rng = new Random(); + byte[] key = rng.randBytes(Sm4Cbc.KEY_SIZE); + byte[] iv = rng.randBytes(Sm4Cbc.IV_SIZE); + byte[] ciphertext = new byte[Sm4Cbc.BLOCK_SIZE * 2]; + byte[] plaintext = new byte[Sm4Cbc.BLOCK_SIZE * 2]; + int cipherlen; + int plainlen; + boolean encrypt = true; + boolean decrypt = false; + + Sm4Cbc sm4cbc = new Sm4Cbc(); + + // Encrypt + sm4cbc.init(key, iv, encrypt); + cipherlen = sm4cbc.update("abc".getBytes(), 0, 3, ciphertext, 0); + cipherlen += sm4cbc.doFinal(ciphertext, cipherlen); + + // Decrypt + sm4cbc.init(key, iv, decrypt); + plainlen = sm4cbc.update(ciphertext, 0, cipherlen, plaintext, 0); + plainlen += sm4cbc.doFinal(plaintext, plainlen); + } } ``` ### SM4-CTR加密模式 -CTR加密模式可以加密任意长度的消息,和CBC模式不同,并不需要采用填充方案,因此SM4-CTR加密输出的密文长度和输入的明文等长。对于存储或传输带宽有限的应用场景,SM4-CTR相对SM4-CBC模式,密文不会增加格外长度。 +CTR加密模式可以加密任意长度的消息,和CBC模式不同,并不需要采用填充方案,因此SM4-CTR加密输出的密文长度和输入的明文等长。对于存储或传输带宽有限的应用场景,SM4-CTR相对SM4-CBC模式,密文不会增加额外长度。 ```java public class Sm4Ctr { - public final static int KEY_SIZE; - public final static int IV_SIZE; - public final static int BLOCK_SIZE; - - public Sm4Ctr(); - public void init(byte[] key, byte[] iv); - public int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset); - public int doFinal(byte[] out, int out_offset); + public final static int KEY_SIZE; + public final static int IV_SIZE; + public final static int BLOCK_SIZE; + + public Sm4Ctr(); + public void init(byte[] key, byte[] iv); + public int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset); + public int doFinal(byte[] out, int out_offset); } ``` @@ -437,7 +543,7 @@ SM4-CTR在加密和解密时计算过程一样,因此`init`方法在初始化 由于`Sm4Ctr`在加解密时维护了内部的缓冲区,因此`update`的输出长度可能不等于输入长度,应该保证输出缓冲区的长度至少比输入长度长一个`BLOCK_SIZE`长度。 -注意 ,SM4-CBC和SM4-CTR模式都不能保证消息的完整性,在使用这两个模式时,应用还需要生成一个独立的HMAC-SM3密钥,并且生成密文的MAC值。 +注意,SM4-CBC和SM4-CTR模式都不能保证消息的完整性,在使用这两个模式时,应用还需要生成一个独立的HMAC-SM3密钥,并且生成密文的MAC值。 ### SM4-GCM认证加密模式 @@ -445,16 +551,16 @@ SM4的GCM模式是一种认证加密模式,和CBC、CTR等加密模式的主 ```java public class Sm4Gcm { - public final static int KEY_SIZE; - public final static int MIN_IV_SIZE; - public final static int MAX_IV_SIZE; - public final static int DEFAULT_IV_SIZE; - public final static int BLOCK_SIZE; - - public Sm4Gcm(); - public void init(byte[] key, byte[] iv, byte[] aad, int taglen, boolean do_encrypt); - public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); - public int doFinal(byte[] out, int outOffset); + public final static int KEY_SIZE; + public final static int MIN_IV_SIZE; + public final static int MAX_IV_SIZE; + public final static int DEFAULT_IV_SIZE; + public final static int BLOCK_SIZE; + + public Sm4Gcm(); + public void init(byte[] key, byte[] iv, byte[] aad, int taglen, boolean do_encrypt); + public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); + public int doFinal(byte[] out, int outOffset); } ``` @@ -468,36 +574,34 @@ import org.gmssl.Random; public class Sm4GcmExample { - public static void main(String[] args) { - - Random rng = new Random(); - byte[] key = rng.randBytes(Sm4Gcm.KEY_SIZE); - byte[] iv = rng.randBytes(Sm4Gcm.DEFAULT_IV_SIZE); - byte[] aad = "Hello:".getBytes(); - int taglen = Sm4Gcm.MAX_TAG_SIZE; - byte[] ciphertext = new byte[64]; - byte[] plaintext = new byte[64]; - int cipherlen; - int plainlen; - boolean encrypt = true; - boolean decrypt = false; - - Sm4Gcm sm4gcm = new Sm4Gcm(); - - sm4gcm.init(key, iv, aad, taglen, encrypt); - cipherlen = sm4gcm.update("abc".getBytes(), 0, 3, ciphertext, 0); - cipherlen += sm4gcm.doFinal(ciphertext, cipherlen); - - sm4gcm.init(key, iv, aad, taglen, decrypt); - plainlen = sm4gcm.update(ciphertext, 0, cipherlen, plaintext, 0); - plainlen += sm4gcm.doFinal(plaintext, plainlen); - } + public static void main(String[] args) { + + Random rng = new Random(); + byte[] key = rng.randBytes(Sm4Gcm.KEY_SIZE); + byte[] iv = rng.randBytes(Sm4Gcm.DEFAULT_IV_SIZE); + byte[] aad = "Hello:".getBytes(); + int taglen = Sm4Gcm.MAX_TAG_SIZE; + byte[] ciphertext = new byte[64]; + byte[] plaintext = new byte[64]; + int cipherlen; + int plainlen; + boolean encrypt = true; + boolean decrypt = false; + + Sm4Gcm sm4gcm = new Sm4Gcm(); + + sm4gcm.init(key, iv, aad, taglen, encrypt); + cipherlen = sm4gcm.update("abc".getBytes(), 0, 3, ciphertext, 0); + cipherlen += sm4gcm.doFinal(ciphertext, cipherlen); + + sm4gcm.init(key, iv, aad, taglen, decrypt); + plainlen = sm4gcm.update(ciphertext, 0, cipherlen, plaintext, 0); + plainlen += sm4gcm.doFinal(plaintext, plainlen); + } } ``` -通过上面的例子可以看出,SM4-GCM加密模式中可以通过`init`指定了一个不需要加密的字段`aad`,注意`aad`是不会在`update`中输出的。由于GCM模式输出个外的完整性标签,因此`update`和`doFinal`输出的总密文长度会比总的输入明文长度多`taglen`个字节。 - - +通过上面的例子可以看出,SM4-GCM加密模式中可以通过`init`指定了一个不需要加密的字段`aad`,注意`aad`是不会在`update`中输出的。由于GCM模式输出额外的完整性标签,因此`update`和`doFinal`输出的总密文长度会比总的输入明文长度多`taglen`个字节。 ### Zuc序列密码 @@ -509,22 +613,22 @@ public class Sm4GcmExample { ```java public class Zuc { - public final static int KEY_SIZE = 16; - public final static int IV_SIZE = 16; - public final static int BLOCK_SIZE = 4; - - public Zuc(); - public void init(byte[] key, byte[] iv); - public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); - public int doFinal(byte[] out, int outOffset); + public final static int KEY_SIZE = 16; + public final static int IV_SIZE = 16; + public final static int BLOCK_SIZE = 4; + + public Zuc(); + public void init(byte[] key, byte[] iv); + public int update(byte[] in, int inOffset, int inlen, byte[] out, int outOffset); + public int doFinal(byte[] out, int outOffset); } ``` `Zuc`类的接口说明如下: -* 序列密码通过生成密钥序列和输入数据进行异或操作的方式来加密或解密,因此序列密码的加密和解密的过程一致,因此`Zuc`的`init`方法中不需要格外的参数表明加密还是解密。 -* 由于CTR模式实际上是以分组密码实现了序列密码的能力,因此可以发现`Zuc`和`Sm4Cbc`的接口是完全一致的。 -* ZUC算法内部实现是以32比特字(4字节)为单位进行处理,因此`Zuc`实现加解密过程中也有内部的状态缓冲区,因此`update`的输出长度可能和输入长度不一致,调用方应该保证输出缓冲区长度比输入长度长`BLOCK_SIZE`个字节。注意,`BLOCK_SIZE`的实际值在未来也有可能会变化。 +- 序列密码通过生成密钥序列和输入数据进行异或操作的方式来加密或解密,因此序列密码的加密和解密的过程一致,因此`Zuc`的`init`方法中不需要额外的参数表明加密还是解密。 +- 由于CTR模式实际上是以分组密码实现了序列密码的能力,因此可以发现`Zuc`和`Sm4Ctr`的接口是完全一致的。 +- ZUC算法内部实现是以32比特字(4字节)为单位进行处理,因此`Zuc`实现加解密过程中也有内部的状态缓冲区,因此`update`的输出长度可能和输入长度不一致,调用方应该保证输出缓冲区长度比输入长度长`BLOCK_SIZE`个字节。注意,`BLOCK_SIZE`的实际值在未来也有可能会变化。 下面的例子展示了`Zuc`的加密和解密过程。 @@ -534,67 +638,65 @@ import org.gmssl.Random; public class ZucExample { - public static void main(String[] args) { + public static void main(String[] args) { - Random rng = new Random(); - byte[] key = rng.randBytes(Zuc.KEY_SIZE); - byte[] iv = rng.randBytes(Zuc.IV_SIZE); - byte[] ciphertext = new byte[32]; - byte[] plaintext = new byte[32]; - int cipherlen; - int plainlen; + Random rng = new Random(); + byte[] key = rng.randBytes(Zuc.KEY_SIZE); + byte[] iv = rng.randBytes(Zuc.IV_SIZE); + byte[] ciphertext = new byte[32]; + byte[] plaintext = new byte[32]; + int cipherlen; + int plainlen; - Zuc zuc = new Zuc(); + Zuc zuc = new Zuc(); - zuc.init(key, iv); - cipherlen = zuc.update("abc".getBytes(), 0, 3, ciphertext, 0); - cipherlen += zuc.doFinal(ciphertext, cipherlen); + zuc.init(key, iv); + cipherlen = zuc.update("abc".getBytes(), 0, 3, ciphertext, 0); + cipherlen += zuc.doFinal(ciphertext, cipherlen); - zuc.init(key, iv); - plainlen = zuc.update(ciphertext, 0, cipherlen, plaintext, 0); - plainlen += zuc.doFinal(plaintext, plainlen); - } + zuc.init(key, iv); + plainlen = zuc.update(ciphertext, 0, cipherlen, plaintext, 0); + plainlen += zuc.doFinal(plaintext, plainlen); + } } ``` - - ### SM2 SM2是国密标准中的椭圆曲线公钥密码,包含数字签名算法和公钥加密算法。SM2相关的功能由类`Sm2Key`和`Sm2Signature`实现,其中`Sm2Key`实现了SM2密钥对的生成、基础的加密和签名方案,`Sm2Signature`类实现了对任意长度消息签名的签名方案。 ```java public class Sm2Key { - public final static int MAX_PLAINTEXT_SIZE; - public final static String DEFAULT_ID; - - public Sm2Key(); - public void generateKey(); - - public void importPrivateKeyInfoDer(byte[] der); - public byte[] exportPrivateKeyInfoDer(); - public void importPublicKeyInfoDer(byte[] der); - public byte[] exportPublicKeyInfoDer(); - - public void importEncryptedPrivateKeyInfoPem(String pass, String file); - public void exportEncryptedPrivateKeyInfoPem(String pass, String file); - public void importPublicKeyInfoPem(String file); - public void exportPublicKeyInfoPem(String file); - - public byte[] computeZ(String id); - public byte[] sign(byte[] dgst); - public boolean verify(byte[] dgst, byte[] signature); - public byte[] encrypt(byte[] plaintext); - public byte[] decrypt(byte[] ciphertext); + public final static int MAX_PLAINTEXT_SIZE; + public final static String DEFAULT_ID; + + public Sm2Key(); + public void generateKey(); + + public void importPrivateKeyInfoDer(byte[] der); + public byte[] exportPrivateKeyInfoDer(); + public void importPublicKeyInfoDer(byte[] der); + public byte[] exportPublicKeyInfoDer(); + + public void importEncryptedPrivateKeyInfoPem(String pass, String file); + public void exportEncryptedPrivateKeyInfoPem(String pass, String file); + public void importPublicKeyInfoPem(String file); + public void exportPublicKeyInfoPem(String file); + + public byte[] computeZ(String id); + public byte[] sign(byte[] dgst); + public boolean verify(byte[] dgst, byte[] signature); + public byte[] encrypt(byte[] plaintext); + public byte[] decrypt(byte[] ciphertext); } ``` 需要注意的是,通过构造函数生成的新`Sm2Key`对象是一个空白的对象,可以通过`generateKey`方法生成一个新的密钥对,或者通过导入函数从外部导入密钥。`Sm2Key`一共提供了4个不同的导入方法: -* `importPrivateKeyInfoDer` 从字节数组中导入SM2私钥,因此导入密钥后这个`Sm2Key`对象可以执行签名操作和解密操作,也可以执行验证签名和加密。 -* `importEncryptedPrivateKeyInfoPem` 从加密的PEM文件中导入SM2私钥,因此调用时需要提供PEM文件的路径和解密的口令(Password)。 -* `importPublicKeyInfoDer`从字节数组中导入SM2公钥,因为其中没有私钥,因此这个`Sm2Key`对象不能执行签名和解密操作,只能执行验证签名和加密操作。 -* `importPublicKeyInfoPem`从PEM文件中导入SM2公钥,只需要提供文件的路径,不需要提供口令。 +- `importPrivateKeyInfoDer` 从字节数组中导入SM2私钥,导入密钥后这个`Sm2Key`对象可以执行签名操作和解密操作,也可以执行验证签名和加密。 +- `importEncryptedPrivateKeyInfoPem` 从加密的PEM文件中导入SM2私钥,调用时需要提供PEM文件的路径和解密的口令(Password)。 +- `importPublicKeyInfoDer`从字节数组中导入SM2公钥,因为其中没有私钥,因此这个`Sm2Key`对象不能执行签名和解密操作,只能执行验证签名和加密操作。 +- `importPublicKeyInfoPem`从PEM文件中导入SM2公钥,只需要提供文件的路径,不需要提供口令。 上面四个导入函数也都有对应的导出函数。从字节数组中导入导出DER编码的公钥和私钥和JCE兼容,但是因为私钥需要以明文的方式写入到字节数组中,因此安全性比较低。从PEM文件中导入导出公钥私钥和`gmssl`命令行工具的默认密钥格式一致,并且在处理私钥时安全性更高。因此建议在默认情况下,在导入导出私钥时默认采用加密的PEM文件格式。 @@ -614,40 +716,35 @@ Sm2Key pubKey = new Sm2Key(); pubKey.importPublicKeyInfoDer(publicKeyInfo); ``` -下面的代码片段展示了`Sm2Key`导出为加密的PEM私钥文件 +下面的代码片段展示了`Sm2Key`导出为加密的PEM私钥文件: ```java priKey.exportEncryptedPrivateKeyInfoPem("Password", "sm2.pem"); priKey.importEncryptedPrivateKeyInfoPem("Password", "sm2.pem"); - ``` -用文本编辑器打开`sm2.pem`文件可以看到如下内容 +用文本编辑器打开`sm2.pem`文件可以看到如下内容: ``` -----BEGIN ENCRYPTED PRIVATE KEY----- MIIBBjBhBgkqhkiG9w0BBQ0wVDA0BgkqhkiG9w0BBQwwJwQQxShg35gP7+BVnsLo -NzYroAIDAQAAAgEQMAsGCSqBHM9VAYMRAjAcBggqgRzPVQFoAgQQrZf0pC2mC52m -cEaC9goJUQSBoGENSQLgigHQUFF7qAOnJQP6erD1vTBQYWWD1aiXGFpLvhPunZ3m -oWOagyqiGmsoV9aSTWMp20ZLiDR+s7pRv8NM0+vspmDUvmb+LUh0zjrrtJqkzr+Q -kdfrXD9Utsqx+PqrzBw/PRMDIRKrJeUtqtkerCnsSUN3CpnpAMSTnQUrTt1mQXyU -dDj7NnOwCbab9km8fzbaXfJlWZYZPsyFJqw= +... -----END ENCRYPTED PRIVATE KEY----- ``` -下面的代码片段展示了`Sm2Key`导出为PEM公钥文件,这是一个标准的PKCS #8 EncryptPrivateKeyInfo类型并且PEM编码的私钥文件格式,`openssl pkeyutil`命令行工具也默认采用这个格式的私钥,但是由于GmSSL在私钥文件中采用SM4-CBC、HMAC-SM3组合加密了SM2的私钥,因此对于默认使用3DES的`openssl`等工具可能无法解密这个私钥(即使这个工具包含SM2算法的实现)。 +下面的代码片段展示了`Sm2Key`导出为PEM公钥文件: ```java pubKey.exportPublicKeyInfoPem("sm2pub.pem"); pubKey.importPublicKeyInfoPem("sm2pub.pem"); ``` -用文本编辑器打开`sm2pub.pem`文件可以看到如下内容 +用文本编辑器打开`sm2pub.pem`文件可以看到如下内容: ``` -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEQ05FKjcbwu2LwLHp2bvacYUBUopR -h143PrNMFNT0lIN5j+5G+sJcgi5UrzmGEZ3mhXtYBTiWhkYaATXLRqygeg== +... -----END PUBLIC KEY----- ``` @@ -655,50 +752,42 @@ h143PrNMFNT0lIN5j+5G+sJcgi5UrzmGEZ3mhXtYBTiWhkYaATXLRqygeg== `Sm2Key`类除了`generateKey`方法之外,提供了`computeZ`、`sign`、`verify`、`encrypt`、`decrypt`这几个密码计算相关的方法。 -其中`computeZ`是由公钥和用户的字符串ID值计算出一个称为“Z值”的哈希值,用于对消息的签名。由于`Sm2Signature`类中提供了SM2消息签名的完整功能,因此这个`computeZ`方法只是用于实验验证。由于这个计算只需要公钥,因此如果密钥值是通过`importPublicKeyInfoDer`等导入的,也可以成功计算出32字节的哈希值结果。 +其中`computeZ`是由公钥和用户的字符串ID值计算出一个称为"Z值"的哈希值,用于对消息的签名。由于`Sm2Signature`类中提供了SM2消息签名的完整功能,因此这个`computeZ`方法只是用于实验验证。 ```java byte[] z = pubKey.computeZ(Sm2Key.DEFAULT_ID); ``` -类`Sm2Key`的`sign`和`verify`方法实现了SM2签名的底层功能,这两个方法不支持对数据或消息的签名,只能实现对SM3哈希值的签名和验证,并没有实现SM2签名的完整功能。应用需要保证调用时提供的`dgst`参数的字节序列长度为32。只有密码协议的底层开发者才需要调用`computeZ`、`sign`、`verify`这几个底层方法。 +类`Sm2Key`的`sign`和`verify`方法实现了SM2签名的底层功能,这两个方法不支持对数据或消息的签名,只能实现对SM3哈希值的签名和验证。应用需要保证调用时提供的`dgst`参数的字节序列长度为32。 ```java Random rng = new Random(); byte[] dgst = rng.randBytes(Sm3.DIGEST_SIZE); byte[] sig = priKey.sign(dgst); - boolean verify_ret = pubKey.verify(dgst, sig); System.out.println("Verify result = " + verify_ret); ``` -类`Sm2Key`的`encrypt`和`decrypt`方法实现了SM2加密和解密功能。注意,虽然SM2标准中没有限制加密消息的长度,但是公钥加密应该主要用于加密较短的对称密钥、主密钥等密钥数据,因此GmSSL库中限制了SM2加密消息的最大长度。应用在调用`encrypt`时,需要保证输入的明文长度不超过`MAX_PLAINTEXT_SIZE`的限制。如果需要加密引用层的消息,应该首先生成对称密钥,用SM4-GCM加密消息,再用SM2加密对称密钥。 +类`Sm2Key`的`encrypt`和`decrypt`方法实现了SM2加密和解密功能。注意,虽然SM2标准中没有限制加密消息的长度,但是公钥加密应该主要用于加密较短的对称密钥、主密钥等密钥数据,因此GmSSL库中限制了SM2加密消息的最大长度(`MAX_PLAINTEXT_SIZE = 255`字节)。如果需要加密应用层的消息,应该首先生成对称密钥,用SM4-GCM加密消息,再用SM2加密对称密钥。 ```java byte[] ciphertext = pubKey.encrypt("abc".getBytes()); - byte[] plaintext = priKey.decrypt(ciphertext); - -System.out.printf("Plaintext : "); -for (i = 0; i < plaintext.length; i++) { - System.out.printf("%02x", plaintext[i]); -} -System.out.print("\n"); ``` -类`Sm2Signatue`提供了对任意长消息的签名、验签功能。 +类`Sm2Signature`提供了对任意长消息的签名、验签功能。 ```java public class Sm2Signature { - public final static String DEFAULT_ID; - - public Sm2Signature(Sm2Key key, String id, boolean do_sign); - public void reset(Sm2Key key, String id, boolean do_sign); - public void update(byte[] data, int offset, int len); - public void update(byte[] data); - public byte[] sign(); - public boolean verify(byte[] signature); + public final static String DEFAULT_ID; + + public Sm2Signature(Sm2Key key, String id, boolean do_sign); + public void reset(Sm2Key key, String id, boolean do_sign); + public void update(byte[] data, int offset, int len); + public void update(byte[] data); + public byte[] sign(); + public boolean verify(byte[] signature); } ``` @@ -719,46 +808,36 @@ System.out.println("Verify result = " + verify_ret); ### SM2数字证书 -类`Sm2Certificate`实现了SM2证书的导入、导出、解析和验证等功能。这里的“SM2证书”含义和“RSA证书”类似,是指证书中的公钥字段是SM2公钥,证书中签名字段是SM2签名,证书格式就是标准的X.509v3证书。由于GmSSL库目前只支持SM2签名算法,不支持ECDSA、RSA、DSA等签名算法,因此`Sm2Certificate`类无法支持其他公钥类型的证书。注意,有一种不常见的情况,一个证书可以公钥是SM2公钥而数字签名是RSA签名,这种证书可能是采用RSA公钥的CA中心对SM2证书请求签发而产生的,由于目前GmSSL不支持SM2之外的签名算法,因此`Sm2Certificate`不支持此类证书。 +类`Sm2Certificate`实现了SM2证书的导入、导出、解析和验证等功能。这里的"SM2证书"含义和"RSA证书"类似,是指证书中的公钥字段是SM2公钥,证书中签名字段是SM2签名,证书格式就是标准的X.509v3证书。由于GmSSL库目前只支持SM2签名算法,不支持ECDSA、RSA、DSA等签名算法,因此`Sm2Certificate`类无法支持其他公钥类型的证书。 -类`Sm2Certificate`只支持SM2证书的解析和验证等功能,不支持SM2证书的签发和生成,如果应用需要实现证书申请(即生成CSR文件)或者自建CA签发证书功能,那么可以通过GmSSL库或者`gmssl`命令行工具实现,GmSSL-Java目前不考虑支持证书签发、生成的相关功能。 +类`Sm2Certificate`只支持SM2证书的解析和验证等功能,不支持SM2证书的签发和生成。如果应用需要实现证书申请(即生成CSR文件)或者自建CA签发证书功能,可以通过GmSSL库或者`gmssl`命令行工具实现。 ```java public class Sm2Certificate { - public Sm2Certificate(); - public byte[] getBytes(); - public void importPem(String file); - public void exportPem(String file); - public byte[] getSerialNumber(); - public String[] getIssuer(); - public String[] getSubject(); - public java.util.Date getNotBefore(); - public java.util.Date getNotAfter(); - public Sm2Key getSubjectPublicKey(); - public boolean verifyByCaCertificate(Sm2Certificate caCert, String sm2Id); + public Sm2Certificate(); + public byte[] getBytes(); + public void importPem(String file); + public void exportPem(String file); + public byte[] getSerialNumber(); + public String[] getIssuer(); + public String[] getSubject(); + public java.util.Date getNotBefore(); + public java.util.Date getNotAfter(); + public Sm2Key getSubjectPublicKey(); + public boolean verifyByCaCertificate(Sm2Certificate caCert, String sm2Id); } ``` -新生成的`Sm2Certificate`对象中的证书数据为空,必须通过导入证书数据才能实现真正的初始化。证书有很多种不同格式的编码,如二进制DER编码的`crt`文件或者文本PEM编码的`cer`文件或者`pem`文件,有的证书也会把二进制的证书数据编码为一串连续的十六进制字符串,也有的CA会把多个证书构成的证书链封装在一个PKCS#7格式的密码消息中,而这个密码消息可能是二进制的,也可能是PEM编码的。 - -在这些格式中最常用的格式是本文的PEM格式,这也是`Sm2Certificate`类默认支持的证书格式。下面这个例子中就是一个证书的PEM文件内容,可以看到内容是由文本构成的,并且总是以`-----BEGIN CERTIFICATE-----`一行作为开头,以`-----END CERTIFICATE-----`一行作为结尾。PEM格式的好处是很容易用文本编辑器打开来,容易作为文本被复制、传输,一个文本文件中可以依次写入多个证书,从而在一个文件中包含多个证书或证书链。因此PEM格式也是CA签发生成证书使用的最主流的格式。由于PEM文件中头尾之间的文本就是证书二进制DER数据的BASE64编码,因此PEM文件也很容易和二进制证书进行手动或自动的互相转换。 +新生成的`Sm2Certificate`对象中的证书数据为空,必须通过导入证书数据才能实现真正的初始化。证书最常用的格式是PEM格式,这也是`Sm2Certificate`类默认支持的证书格式。PEM文件内容总是以`-----BEGIN CERTIFICATE-----`一行作为开头,以`-----END CERTIFICATE-----`一行作为结尾。 ``` -----BEGIN CERTIFICATE----- MIIBszCCAVegAwIBAgIIaeL+wBcKxnswDAYIKoEcz1UBg3UFADAuMQswCQYDVQQG -EwJDTjEOMAwGA1UECgwFTlJDQUMxDzANBgNVBAMMBlJPT1RDQTAeFw0xMjA3MTQw -MzExNTlaFw00MjA3MDcwMzExNTlaMC4xCzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAVO -UkNBQzEPMA0GA1UEAwwGUk9PVENBMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE -MPCca6pmgcchsTf2UnBeL9rtp4nw+itk1Kzrmbnqo05lUwkwlWK+4OIrtFdAqnRT -V7Q9v1htkv42TsIutzd126NdMFswHwYDVR0jBBgwFoAUTDKxl9kzG8SmBcHG5Yti -W/CXdlgwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFEwysZfZ -MxvEpgXBxuWLYlvwl3ZYMAwGCCqBHM9VAYN1BQADSAAwRQIgG1bSLeOXp3oB8H7b -53W+CKOPl2PknmWEq/lMhtn25HkCIQDaHDgWxWFtnCrBjH16/W3Ezn7/U/Vjo5xI -pDoiVhsLwg== +... -----END CERTIFICATE----- ``` -通过`gmssl certparse`命令可以打印这个证书的内容 +通过`gmssl certparse`命令可以打印证书内容: ```bash $ gmssl certparse -in ROOTCA.pem @@ -768,7 +847,6 @@ Certificate serialNumber: 69E2FEC0170AC67B signature algorithm: sm2sign-with-sm3 - parameters: NULL issuer countryName: CN organizationName: NRCAC @@ -777,110 +855,72 @@ Certificate notBefore: Sat Jul 14 11:11:59 2012 notAfter: Mon Jul 7 11:11:59 2042 subject - countryName: CN - organizationName: NRCAC - commonName: ROOTCA + ... subjectPulbicKeyInfo - algorithm - algorithm: ecPublicKey - namedCurve: sm2p256v1 - subjectPublicKey - ECPoint: 0430F09C6BAA6681C721B137F652705E2FDAEDA789F0FA2B64D4ACEB99B9EAA34E655309309562BEE0E22BB45740AA745357B43DBF586D92FE364EC22EB73775DB + algorithm: ecPublicKey + namedCurve: sm2p256v1 extensions - Extension - extnID: AuthorityKeyIdentifier (2.5.29.35) - AuthorityKeyIdentifier - keyIdentifier: 4C32B197D9331BC4A605C1C6E58B625BF0977658 - Extension - extnID: BasicConstraints (2.5.29.19) - BasicConstraints - cA: true - Extension - extnID: KeyUsage (2.5.29.15) - KeyUsage: keyCertSign,cRLSign - Extension - extnID: SubjectKeyIdentifier (2.5.29.14) - SubjectKeyIdentifier: 4C32B197D9331BC4A605C1C6E58B625BF0977658 - signatureAlgorithm - algorithm: sm2sign-with-sm3 - parameters: NULL - signatureValue: 304502201B56D22DE397A77A01F07EDBE775BE08A38F9763E49E6584ABF94C86D9F6E479022100DA1C3816C5616D9C2AC18C7D7AFD6DC4CE7EFF53F563A39C48A43A22561B0BC2 -``` - -可以看到一个证书的主要内容是包含证书持有者信息的tbsCertificate字段,以及权威机构对tbsCertificate字段的签名算法signatureAlgorithm和签名值signatureValue。因为这个证书是SM2证书,因此其中的签名算法是`sm2sign-with-sm3`,签名值是`0x30`开头的DER编码的可变长度签名值。 + ... +``` 证书中持有者信息包含如下字段: -* 证书格式的版本号 version,目前版本号应该是第3版,即`v3`。 -* 证书的序列号 serialNumber,早期证书中的序列号是一个递增的整数,但是近年来的证书必须是随机值。、 -* 证书的签名算法 signature,这个字段的值必须和最后的signatureAlgorithm保持一致。 -* 证书签发机构的名字 issuer,通常是一个CA中心,issuer的内容是由多个Key-Value格式的多个字段组合而成,其中的Key包括国家countryName、省stateOrProvinceName、城市localityName、组织organizationName、组织内单位organizationUnitName、常用名commonName等,其中commonName应该是CA机构的名字。 -* 证书的有效期 validity,有效期是由起始时间notBefore和终止时间notAfter两个时间构成的,如果当前时间早于notBefore,说明证书还没有启用,如果当前时间晚于notAfter,说明证书已经过期作废。 -* 证书持有者(证书主体)的名字 subject,这个字段的数据类型和issuer是一样的,一般对于网站服务器证书来说,subject的commonName应该是服务器的域名。 -* 证书持有者的公钥信息subjectPulbicKeyInfo,对于SM2证书来说,公钥算法必须是ecPublicKey并且曲线必须是sm2p256v1,公钥的值是一个编码的椭圆曲线点,这个值总是以`0x04`开头,后跟总共64字节的点的X、Y坐标。 -* 证书中通常还有多个扩展,其中有的扩展是关键的(critical)扩展,有些则不重要,只是提供了参考信息,这里介绍两个比较重要的扩展: - * BasicConstraints (2.5.29.19) 扩展,这个扩展标明证书是权威机构的CA证书(比如北京市CA中心)还是普通用户的证书(比如某个网站的证书),如果一个证书中没有包含这个扩展,或者扩展中的`cA: true`字段不存在,那么这个证书不能作为CA证书使用。 - * KeyUsage (2.5.29.15) 扩展,这个扩展表明证书持有者公钥的用途,类似于驾驶证中的A照、B照、C照等划分大客车、大货车、小客车准驾车型,密钥用途表明证书是否可以签名、加密、签发证书等用途。如果一个数字签名附带的证书中有KeyUsage扩展并且扩展包含的密钥用途只有加密,没有签名,那么这个证书对于这个签名来说就是无效的。 - -`Sm2Certificate`类只支持第3版证书的解析,因此没有提供`getVersion`方法获取证书的版本号。GmSSL支持常用扩展的解析和验证,如果某个证书中有GmSSL不支持的非关键扩展,那么GmSSL会忽略这个扩展,如果存在GmSSL不识别或无法验证的关键性扩展,那么GmSSL在解析证书的时候会返回失败,因此如果`Sm2Certificate`类`importPem`成功,说明证书的格式、内容是可以识别的并且是正确的。 - -拿他其他人提供的证书还必须验证该证书是否有效,首先需要检查证书的有效期。目前很多CA中心的策略是颁发有效期尽可能短的证书(比如3个月有效期),因此拿到的证书很有可能已经过期了。可以通过`getNotBefore`和`getNotAfter`方法获得有效期时间,判断当前时间点是否在有效期范围内。如果要验证过去某个时间点证书支持者的操作是否合法,那么应该检查那个时间点是否在证书的有效期范围内。 - -对证书最重要的验证之一是这个证书是否是由权威机构签发的。证书用户需要先通过`getIssuer`方法获得签发机构的名字,确认这个签发机构是否可信。例如,如果一个北京市政府机构的证书中的签发机构是一个商业性CA中心,那么这个证书的有效性就是存疑的。在确认CA中心名字(即整个issuer字段)无误之后,还需要通过Issuer字段从可信的渠道获得这个CA中心的证书,然后调用`verifyByCaCertificate`方法,用获得的CA证书验证当前证书中的签名是否正确。在典型的应用中,开发者和软件发行方应该将所有可信的CA中心的证书硬编码到软件中,或者内置到软件或系统的证书库中,避免应用的用户需要手动添加、导入CA证书。 - -所有的私钥都有泄露的可能,安全性不佳的自建CA有被攻击者渗透的可能,商业性的小CA甚至有被收购、收买的可能,因此有效期范围内的证书也存在被作废的可能。检查证书是否作废主要是通过证书作废列表CRL文件检查,或者通过证书状态在线检查协议OCSP来在线查询。目前`Sm2Certificate`类没有支持证书作为查询的功能,开发者暂时可以通过`GmSSL`库或者`gmssl`命令行工具进行CRL的检查。 - -在完成所有证书检查之后,应用可以完全信任从证书中读取的持有者身份信息(subject)和支持有的公钥了,这两个信息分别通过`getSubject`和`getSubjectPublicKey`方法获得。 - +- 证书格式的版本号 version +- 证书的序列号 serialNumber +- 证书的签名算法 signature +- 证书签发机构的名字 issuer(由countryName、organizationName、commonName等组成) +- 证书的有效期 validity(notBefore和notAfter) +- 证书持有者的名字 subject +- 证书持有者的公钥信息 subjectPulbicKeyInfo +- 多个扩展字段(BasicConstraints、KeyUsage等) +证书验证时需要检查有效期(`getNotBefore` / `getNotAfter`)、签发机构(`getIssuer` + `verifyByCaCertificate`),并建议通过CRL或OCSP检查证书是否被作废。在完成所有证书检查之后,应用可以从证书中读取持有者身份信息(`getSubject`)和公钥(`getSubjectPublicKey`)。 ### SM9 基于身份的密码 -SM9算法属于基于身份的密码。基于身份的密码是一种“高级”的公钥密码方案,在具备常规公钥密码加密、签名等密码功能的同时,基于身份的密码体系不需要CA中心和数字证书体系。SM9方案的基本原理是,可以由用户的唯一身份ID(如对方的电子邮件地址、域名或ID号等),从系统的全局主密钥中导出对应的私钥或公钥,导出密钥的正确性是由算法保证的,因此在进行加密、验签的时候,只需要获得解密方或签名方的ID即可,不再需要对方的数字证书了。因此如果应用面对的是一个内部的封闭环境,所有参与用户都是系统内用户,那么采用SM9方案而不是SM2证书和CA的方案,可以简化系统的开发、设计和使用,并降低后续CA体系的维护成本。 +SM9算法属于基于身份的密码。基于身份的密码是一种"高级"的公钥密码方案,在具备常规公钥密码加密、签名等密码功能的同时,基于身份的密码体系不需要CA中心和数字证书体系。SM9方案的基本原理是,可以由用户的唯一身份ID(如对方的电子邮件地址、域名或ID号等),从系统的全局主密钥中导出对应的私钥或公钥,导出密钥的正确性是由算法保证的,因此在进行加密、验签的时候,只需要获得解密方或签名方的ID即可,不再需要对方的数字证书了。因此如果应用面对的是一个内部的封闭环境,所有参与用户都是系统内用户,那么采用SM9方案而不是SM2证书和CA的方案,可以简化系统的开发、设计和使用,并降低后续CA体系的维护成本。 -对应数字证书体系中的CA中心,SM9体系中也存在一个权威中心,用于生成全局的主密钥(MasterKey),并且为系统中的每个用户生成、分配用户的私钥。和SM2密钥对一样,SM9的主密钥也包含私钥和公钥,其中主公钥(PublicMasterKey)是可以导出并公开给系统中全体用户的。而SM9中用户的密钥对比较特殊,其中的公钥并不能从私钥中导出,SM9用户密钥需要包含用户的ID起到公钥的作用,在加密和验证签名等密码计算中,真正的用户公钥是在计算中,在运行时通过用户ID从主公钥中导出的。因此从应用的角度看,SM9中用户的公钥就是一个字符串形式的ID。 +对应数字证书体系中的CA中心,SM9体系中也存在一个权威中心,用于生成全局的主密钥(MasterKey),并且为系统中的每个用户生成、分配用户的私钥。SM9算法体系中包括SM9加密、SM9签名和SM9密钥交换协议,GmSSL-Java中实现了SM9加密和SM9签名,没有实现SM9密钥交换。其中SM9加密功能包含`Sm9EncMasterKey`类和`Sm9EncKey`类,分别实现了SM9加密主密钥和SM9加密用户密钥,SM9签名功能包含`Sm9SignMasterKey`类、`Sm9SignKey`类和`Sm9Signature`类,分别实现了SM9签名主密钥、SM9签名用户密钥和SM9签名功能。 -SM9算法体系中包括SM9加密、SM9签名和SM9密钥交换协议,GmSSL-Java中实现了SM9加密和SM9签名,没有实现SM9密钥交换。其中SM9加密功能包含`Sm9EncMasterKey`类和`Sm9EncKey`类,分别实现了SM9加密主密钥和SM9加密用户密钥,SM9签名功能包含`Sm9SignMasterKey`类、`Sm9SignKey`类和`Sm9Signature`类,分别实现了SM9签名主密钥、SM9签名用户密钥和SM9签名功能。 - -和SM2算法中相同的密钥对既可以用于加密又可以用于签名不同,SM9中加密、签名的主密钥、用户密钥的组成是完全不同的,因此GmSSL中分别实现为不同的类。SM9签名由于需要特殊的哈希过程,因此SM9用户签名私钥不提供直接签哈希值的底层签名功能实现,只能通过`Sm9Signature`实现对消息的签名、验证。 +和SM2算法中相同的密钥对既可以用于加密又可以用于签名不同,SM9中加密、签名的主密钥、用户密钥的组成是完全不同的,因此GmSSL中分别实现为不同的类。 SM9加密主密钥由类`Sm9EncMasterKey`实现。 ```java public class Sm9EncMasterKey { - public final static int MAX_PLAINTEXT_SIZE; + public final static int MAX_PLAINTEXT_SIZE; - public Sm9SEncMasterKey(); - public void generateMasterKey(); - public Sm9EncKey extractKey(String id); - public void importEncryptedMasterKeyInfoPem(String pass, String file); - public void exportEncryptedMasterKeyInfoPem(String pass, String file); - public void importPublicMasterKeyPem(String file); - public void exportPublicMasterKeyPem(String file); - public byte[] encrypt(byte[] plaintext, String id); + public Sm9EncMasterKey(); + public void generateMasterKey(); + public Sm9EncKey extractKey(String id); + public void importEncryptedMasterKeyInfoPem(String pass, String file); + public void exportEncryptedMasterKeyInfoPem(String pass, String file); + public void importPublicMasterKeyPem(String file); + public void exportPublicMasterKeyPem(String file); + public byte[] encrypt(byte[] plaintext, String id); } ``` `Sm9EncMasterKey`的接口包括: -* 主密钥的生成`generateMasterKey` -* 主密钥的导入`importEncryptedMasterKeyInfoPem`和导出`exportEncryptedMasterKeyInfoPem`,注意`Sm2Key`的对应接口类似,这里主密钥都是以口令加密的方式导出到文件上的 -* 主公钥(主密钥的公钥部分)的导入`importPublicMasterKeyPem`和导出`exportPublicMasterKeyPem` -* 用户私钥的生成`extractKey` -* 数据加密`encrypt` +- 主密钥的生成`generateMasterKey` +- 主密钥的导入`importEncryptedMasterKeyInfoPem`和导出`exportEncryptedMasterKeyInfoPem` +- 主公钥(主密钥的公钥部分)的导入`importPublicMasterKeyPem`和导出`exportPublicMasterKeyPem` +- 用户私钥的生成`extractKey` +- 数据加密`encrypt` 这个类的用户包括两个不同角色,权威中心和用户。其中权威中心调用主密钥的生成、主密钥的导入导出、主公钥导出和用户私钥生成这几个接口,而用户调用主公钥导入和加密这两个接口。 -类`Sm9EncKey`对象是由`Sm9SEncMasterKey`的`extractKey`方法生成的。 +类`Sm9EncKey`对象是由`Sm9EncMasterKey`的`extractKey`方法生成的。 ```java public class Sm9EncKey { - public Sm9EncKey(String id); - public String getId(); - public void exportEncryptedPrivateKeyInfoPem(String pass, String file); - public void importEncryptedPrivateKeyInfoPem(String pass, String file); - public byte[] decrypt(byte[] ciphertext); + public Sm9EncKey(String id); + public String getId(); + public void exportEncryptedPrivateKeyInfoPem(String pass, String file); + public void importEncryptedPrivateKeyInfoPem(String pass, String file); + public byte[] decrypt(byte[] ciphertext); } ``` @@ -894,20 +934,20 @@ import org.gmssl.Sm9EncKey; public class Sm9EncExample { - public static void main(String[] args) { + public static void main(String[] args) { - Sm9EncMasterKey enc_master_key = new Sm9EncMasterKey(); - enc_master_key.generateMasterKey(); - enc_master_key.exportPublicMasterKeyPem("sm9enc.mpk"); + Sm9EncMasterKey enc_master_key = new Sm9EncMasterKey(); + enc_master_key.generateMasterKey(); + enc_master_key.exportPublicMasterKeyPem("sm9enc.mpk"); - Sm9EncMasterKey enc_master_pub_key = new Sm9EncMasterKey(); - enc_master_pub_key.importPublicMasterKeyPem("sm9enc.mpk"); + Sm9EncMasterKey enc_master_pub_key = new Sm9EncMasterKey(); + enc_master_pub_key.importPublicMasterKeyPem("sm9enc.mpk"); - byte[] ciphertext = enc_master_pub_key.encrypt("abc".getBytes(), "Bob"); + byte[] ciphertext = enc_master_pub_key.encrypt("abc".getBytes(), "Bob"); - Sm9EncKey enc_key = enc_master_key.extractKey("Bob"); - byte[] plaintext = enc_key.decrypt(ciphertext); - } + Sm9EncKey enc_key = enc_master_key.extractKey("Bob"); + byte[] plaintext = enc_key.decrypt(ciphertext); + } } ``` @@ -915,22 +955,22 @@ SM9签名功能由`Sm9SignMasterKey`、`Sm9SignKey`和`Sm9Signature`几个类实 ```java public class Sm9SignMasterKey { - public Sm9SignMasterKey(); - public void generateMasterKey(); - public Sm9SignKey extractKey(String id); - public void importEncryptedMasterKeyInfoPem(String pass, String file); - public void exportEncryptedMasterKeyInfoPem(String pass, String file); - public void importPublicMasterKeyPem(String file); - public void exportPublicMasterKeyPem(String file); + public Sm9SignMasterKey(); + public void generateMasterKey(); + public Sm9SignKey extractKey(String id); + public void importEncryptedMasterKeyInfoPem(String pass, String file); + public void exportEncryptedMasterKeyInfoPem(String pass, String file); + public void importPublicMasterKeyPem(String file); + public void exportPublicMasterKeyPem(String file); } ``` ```java public class Sm9SignKey { - public Sm9SignKey(String id); - public String getId(); - public void exportEncryptedPrivateKeyInfoPem(String pass, String file); - public void importEncryptedPrivateKeyInfoPem(String pass, String file); + public Sm9SignKey(String id); + public String getId(); + public void exportEncryptedPrivateKeyInfoPem(String pass, String file); + public void importEncryptedPrivateKeyInfoPem(String pass, String file); } ``` @@ -938,12 +978,12 @@ public class Sm9SignKey { ```java public class Sm9Signature { - public Sm9Signature(boolean do_sign); - public void reset(boolean do_sign); - public void update(byte[] data, int offset, int len); - public void update(byte[] data); - public byte[] sign(Sm9SignKey signKey); - public boolean verify(byte[] signature, Sm9SignMasterKey masterPublicKey, String id); + public Sm9Signature(boolean do_sign); + public void reset(boolean do_sign); + public void update(byte[] data, int offset, int len); + public void update(byte[] data); + public byte[] sign(Sm9SignKey signKey); + public boolean verify(byte[] signature, Sm9SignMasterKey masterPublicKey, String id); } ``` @@ -956,30 +996,29 @@ import org.gmssl.Sm9Signature; public class Sm9SignExample { - public static void main(String[] args) { + public static void main(String[] args) { - Sm9SignMasterKey sign_master_key = new Sm9SignMasterKey(); - sign_master_key.generateMasterKey(); + Sm9SignMasterKey sign_master_key = new Sm9SignMasterKey(); + sign_master_key.generateMasterKey(); - Sm9SignKey sign_key = sign_master_key.extractKey("Alice"); + Sm9SignKey sign_key = sign_master_key.extractKey("Alice"); - Sm9Signature sign = new Sm9Signature(true); - sign.update("abc".getBytes()); - byte[] sig = sign.sign(sign_key); + Sm9Signature sign = new Sm9Signature(true); + sign.update("abc".getBytes()); + byte[] sig = sign.sign(sign_key); - sign_master_key.exportPublicMasterKeyPem("sm9sign.mpk"); - Sm9SignMasterKey sign_master_pub_key = new Sm9SignMasterKey(); - sign_master_pub_key.importPublicMasterKeyPem("sm9sign.mpk"); + sign_master_key.exportPublicMasterKeyPem("sm9sign.mpk"); + Sm9SignMasterKey sign_master_pub_key = new Sm9SignMasterKey(); + sign_master_pub_key.importPublicMasterKeyPem("sm9sign.mpk"); - Sm9Signature verify = new Sm9Signature(false); - verify.update("abc".getBytes()); - boolean verify_ret = verify.verify(sig, sign_master_pub_key, "Alice"); - System.out.println("Verify result = " + verify_ret); - } + Sm9Signature verify = new Sm9Signature(false); + verify.update("abc".getBytes()); + boolean verify_ret = verify.verify(sig, sign_master_pub_key, "Alice"); + System.out.println("Verify result = " + verify_ret); + } } ``` ### GmSSLException GmSSL-Java在遇到错误和异常时,会抛出`GmSSLException`异常。 - diff --git a/pom.xml b/pom.xml index 184d92d..c891fd9 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 org.gmssl GmSSLJNI - 3.1.1 + 1.0.0 GmSSL-Java jar GmSSL Java SDK @@ -14,6 +14,7 @@ false Debug + gmssljni @@ -65,7 +66,8 @@ Optional: One or more options found at https://cmake.org/cmake/help/v3.22/manual/cmake.1.html For example: --> - + + @@ -77,6 +79,7 @@ + ${cmake.compile.config} @@ -99,15 +102,6 @@ false - - ${basedir}/src/main/resources/lib - - *.dll - *.so - *.dylib - - false - ${basedir} @@ -119,6 +113,17 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + ${gmssl.root} + + + + org.apache.maven.plugins maven-resources-plugin @@ -132,7 +137,7 @@ copy-resources - ${project.build.directory} + ${project.build.outputDirectory} ${project.build.directory}/build/${cmake.compile.config} @@ -141,23 +146,25 @@ *.so *.dylib - ${basedir}/target/classes/lib - - - ${project.build.directory}/build/${cmake.compile.config} - - *.dll - *.so - *.dylib - - ${basedir}/src/main/resources/lib + lib + + + + + copy-rootca + compile + + copy-resources + + + ${basedir} + ${project.build.directory}/build ROOTCA.pem - ${basedir} @@ -181,4 +188,4 @@ - \ No newline at end of file + diff --git a/src/main/c/CMakeLists.txt b/src/main/c/CMakeLists.txt index a16c4b3..68ab72e 100644 --- a/src/main/c/CMakeLists.txt +++ b/src/main/c/CMakeLists.txt @@ -1,46 +1,68 @@ cmake_minimum_required(VERSION 3.11) -project(gmssljni) +project(gmssljni C) -find_program(GMSSL_EXECUTABLE NAMES gmssl) +if(DEFINED GMSSL_ROOT AND (GMSSL_ROOT STREQUAL "" OR GMSSL_ROOT MATCHES "^\\$\\{.*\\}$")) + unset(GMSSL_ROOT) +endif() +if(NOT DEFINED GMSSL_ROOT AND DEFINED ENV{GMSSL_ROOT} AND NOT "$ENV{GMSSL_ROOT}" STREQUAL "") + set(GMSSL_ROOT "$ENV{GMSSL_ROOT}") +endif() + +if(GMSSL_ROOT) + unset(GMSSL_EXECUTABLE CACHE) + find_program(GMSSL_EXECUTABLE NAMES gmssl HINTS "${GMSSL_ROOT}/bin" NO_DEFAULT_PATH) +else() + find_program(GMSSL_EXECUTABLE NAMES gmssl) +endif() if(GMSSL_EXECUTABLE) get_filename_component(GMSSL_BIN_DIR "${GMSSL_EXECUTABLE}" DIRECTORY) get_filename_component(GMSSL_PARENT_DIR "${GMSSL_BIN_DIR}" DIRECTORY) else() - message(FATAL_ERROR "gmssl not found!") + message(FATAL_ERROR "gmssl not found! Install GmSSL or pass -DGMSSL_ROOT=/path/to/gmssl") +endif() + +set(GMSSL_INCLUDE_DIR "${GMSSL_PARENT_DIR}/include") +set(GMSSL_LIBRARY_DIR "${GMSSL_PARENT_DIR}/lib") + +if(NOT EXISTS "${GMSSL_INCLUDE_DIR}/gmssl/sm4.h") + message(FATAL_ERROR "GmSSL headers at ${GMSSL_INCLUDE_DIR} are incompatible: gmssl/sm4.h is missing. Use guanzhi/GmSSL release v3.2.0 or a compatible release.") +endif() + +unset(GMSSL_LIBRARY CACHE) +find_library(GMSSL_LIBRARY NAMES gmssl libgmssl HINTS "${GMSSL_LIBRARY_DIR}" NO_DEFAULT_PATH) +if(NOT GMSSL_LIBRARY) + message(FATAL_ERROR "GmSSL library not found under ${GMSSL_LIBRARY_DIR}") +endif() + +if(NOT DEFINED ENV{libSubFolder} OR "$ENV{libSubFolder}" STREQUAL "") + set(LIB_SUB_FOLDER "${CMAKE_BUILD_TYPE}") +else() + set(LIB_SUB_FOLDER "$ENV{libSubFolder}") endif() +if(NOT LIB_SUB_FOLDER) + set(LIB_SUB_FOLDER "Debug") +endif() + +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${LIB_SUB_FOLDER}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${LIB_SUB_FOLDER}") +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${LIB_SUB_FOLDER}") +foreach(CONFIG_TYPE Debug Release RelWithDebInfo MinSizeRel) + string(TOUPPER "${CONFIG_TYPE}" CONFIG_TYPE_UPPER) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_TYPE_UPPER} "${CMAKE_BINARY_DIR}/${CONFIG_TYPE}") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_${CONFIG_TYPE_UPPER} "${CMAKE_BINARY_DIR}/${CONFIG_TYPE}") + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_TYPE_UPPER} "${CMAKE_BINARY_DIR}/${CONFIG_TYPE}") +endforeach() + +find_package(JNI REQUIRED) + +add_library(gmssljni-native SHARED gmssljni.c) +target_include_directories(gmssljni-native PRIVATE ${JNI_INCLUDE_DIRS} "${GMSSL_INCLUDE_DIR}") +target_link_libraries(gmssljni-native PRIVATE "${GMSSL_LIBRARY}") if(WIN32) - message(STATUS "->Now is windows") - link_directories(${GMSSL_PARENT_DIR}/lib) - add_library(gmssljni-native SHARED gmssljni.c) - target_include_directories(gmssljni-native PUBLIC ${GMSSL_PARENT_DIR}/include) - #target_include_directories(gmssljni-native PUBLIC ${CMAKE_SOURCE_DIR}/jni) - find_package(JNI REQUIRED) - include_directories(${JNI_INCLUDE_DIRS}) - target_link_libraries(gmssljni-native gmssl) set_target_properties(gmssljni-native PROPERTIES OUTPUT_NAME lib$ENV{libName}) -elseif(APPLE) - message(STATUS "->Now is Apple systems.") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/$ENV{libSubFolder}) - add_library(gmssljni-native SHARED gmssljni.c) - target_link_libraries(gmssljni-native -L"${GMSSL_PARENT_DIR}/lib") - find_package(JNI REQUIRED) - include_directories(${JNI_INCLUDE_DIRS}) - include_directories(${GMSSL_PARENT_DIR}/include) - target_link_libraries(gmssljni-native gmssl) - set_target_properties(gmssljni-native PROPERTIES OUTPUT_NAME $ENV{libName}) -elseif(UNIX) - message(STATUS "->Now is UNIX-like OS's.") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/$ENV{libSubFolder}) - add_library(gmssljni-native SHARED gmssljni.c) - target_link_libraries(gmssljni-native -L"${GMSSL_PARENT_DIR}/lib") - find_package(JNI REQUIRED) - include_directories(${JNI_INCLUDE_DIRS}) - include_directories(${GMSSL_PARENT_DIR}/include) - target_link_libraries(gmssljni-native gmssl) - set_target_properties(gmssljni-native PROPERTIES OUTPUT_NAME $ENV{libName}) else() - message(FATAL_ERROR "->Now is other systems.") + set_target_properties(gmssljni-native PROPERTIES OUTPUT_NAME $ENV{libName}) endif() set(certfile @@ -56,4 +78,4 @@ set(certfile "53W+CKOPl2PknmWEq/lMhtn25HkCIQDaHDgWxWFtnCrBjH16/W3Ezn7/U/Vjo5xI\n" "pDoiVhsLwg==\n" "-----END CERTIFICATE-----\n") -file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/ROOTCA.pem ${certfile}) \ No newline at end of file +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/ROOTCA.pem ${certfile}) diff --git a/src/main/c/gmssljni.c b/src/main/c/gmssljni.c index fe1cc72..64cd42c 100644 --- a/src/main/c/gmssljni.c +++ b/src/main/c/gmssljni.c @@ -18,13 +18,14 @@ #include #include #include -#include #include #include #include #include #include "gmssljni.h" +#define SM2_SIGNATURE_CTX_SIZE (sizeof(SM2_SIGN_CTX) > sizeof(SM2_VERIFY_CTX) ? sizeof(SM2_SIGN_CTX) : sizeof(SM2_VERIFY_CTX)) + static int check_buf(const jbyte *buf, jint bufsiz, jint offset, jint outlen) { @@ -390,7 +391,7 @@ JNIEXPORT jbyteArray JNICALL Java_org_gmssl_GmSSLJNI_sm3_1pbkdf2( goto end; } - if (pbkdf2_hmac_sm3_genkey(pass_str, strlen(pass_str), + if (sm3_pbkdf2(pass_str, strlen(pass_str), (const uint8_t *)saltbuf, saltlen, iter, keylen, keybuf) != 1) { error_print(); goto end; @@ -1051,7 +1052,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm4_1ctr_1decrypt_1init( error_print(); goto end; } - if (sm4_ctr_decrypt_init((SM4_CTR_CTX *)sm4_ctr_ctx, (uint8_t *)keybuf, (uint8_t *)ivbuf) != 1) { + if (sm4_ctr_encrypt_init((SM4_CTR_CTX *)sm4_ctr_ctx, (uint8_t *)keybuf, (uint8_t *)ivbuf) != 1) { error_print(); goto end; } @@ -1101,7 +1102,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm4_1ctr_1decrypt_1update( error_print(); goto end; } - if (sm4_ctr_decrypt_update((SM4_CTR_CTX *)sm4_ctr_ctx, (uint8_t *)inbuf + in_offset, (size_t)inlen, + if (sm4_ctr_encrypt_update((SM4_CTR_CTX *)sm4_ctr_ctx, (uint8_t *)inbuf + in_offset, (size_t)inlen, (uint8_t *)outbuf + out_offset, &outlen) != 1) { error_print(); goto end; @@ -1140,7 +1141,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm4_1ctr_1decrypt_1finish( error_print(); goto end; } - if (sm4_ctr_decrypt_finish((SM4_CTR_CTX *)sm4_ctr_ctx, + if (sm4_ctr_encrypt_finish((SM4_CTR_CTX *)sm4_ctr_ctx, (uint8_t *)outbuf + offset, &outlen) != 1) { error_print(); goto end; @@ -2188,11 +2189,11 @@ JNIEXPORT jlong JNICALL Java_org_gmssl_GmSSLJNI_sm2_1sign_1ctx_1new( { jlong sm2_sign_ctx; - if (!(sm2_sign_ctx = (jlong)malloc(sizeof(SM2_SIGN_CTX)))) { + if (!(sm2_sign_ctx = (jlong)malloc(SM2_SIGNATURE_CTX_SIZE))) { error_print(); return 0; } - memset((SM2_SIGN_CTX *)sm2_sign_ctx, 0, sizeof(SM2_SIGN_CTX)); + memset((void *)sm2_sign_ctx, 0, SM2_SIGNATURE_CTX_SIZE); return sm2_sign_ctx; } @@ -2206,7 +2207,7 @@ JNIEXPORT void JNICALL Java_org_gmssl_GmSSLJNI_sm2_1sign_1ctx_1free( jlong sm2_sign_ctx) { if (sm2_sign_ctx) { - gmssl_secure_clear((SM2_SIGN_CTX *)sm2_sign_ctx, sizeof(SM2_SIGN_CTX)); + gmssl_secure_clear((void *)sm2_sign_ctx, SM2_SIGNATURE_CTX_SIZE); free((SM2_SIGN_CTX *)sm2_sign_ctx); } } @@ -2333,7 +2334,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm2_1verify_1init( error_print(); return -1; } - if (sm2_verify_init((SM2_SIGN_CTX *)sm2_sign_ctx, (SM2_KEY *)sm2_pub, id_str, strlen(id_str)) != 1) { + if (sm2_verify_init((SM2_VERIFY_CTX *)sm2_sign_ctx, (SM2_KEY *)sm2_pub, id_str, strlen(id_str)) != 1) { error_print(); goto end; } @@ -2368,7 +2369,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm2_1verify_1update( error_print(); goto end; } - if (sm2_verify_update((SM2_SIGN_CTX *)sm2_sign_ctx, (uint8_t *)buf + offset, (size_t)length) != 1) { + if (sm2_verify_update((SM2_VERIFY_CTX *)sm2_sign_ctx, (uint8_t *)buf + offset, (size_t)length) != 1) { error_print(); goto end; } @@ -2400,7 +2401,7 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_sm2_1verify_1finish( return -1; } siglen = (*env)->GetArrayLength(env, sig); - if ((ret = sm2_verify_finish((SM2_SIGN_CTX *)sm2_sign_ctx, (uint8_t *)sigbuf, (size_t)siglen)) < 0) { + if ((ret = sm2_verify_finish((SM2_VERIFY_CTX *)sm2_sign_ctx, (uint8_t *)sigbuf, (size_t)siglen)) < 0) { error_print(); goto end; } @@ -3815,6 +3816,7 @@ JNIEXPORT jlong JNICALL Java_org_gmssl_GmSSLJNI_cert_1get_1subject_1public_1key( jbyte *certbuf; jsize certlen; SM2_KEY *sm2_pub = NULL; + X509_KEY x509_key; if (!(certbuf = (*env)->GetByteArrayElements(env, cert, NULL))) { error_print(); @@ -3826,10 +3828,18 @@ JNIEXPORT jlong JNICALL Java_org_gmssl_GmSSLJNI_cert_1get_1subject_1public_1key( goto end; } memset(sm2_pub, 0, sizeof(SM2_KEY)); - if (x509_cert_get_subject_public_key((uint8_t *)certbuf, certlen, sm2_pub) != 1) { + memset(&x509_key, 0, sizeof(x509_key)); + if (x509_cert_get_subject_public_key((uint8_t *)certbuf, certlen, &x509_key) != 1) { error_print(); goto end; } + if (x509_key.algor != OID_ec_public_key || x509_key.algor_param != OID_sm2) { + error_print(); + x509_key_cleanup(&x509_key); + goto end; + } + memcpy(sm2_pub, &x509_key.u.sm2_key, sizeof(SM2_KEY)); + x509_key_cleanup(&x509_key); ret = (jlong)sm2_pub; sm2_pub = NULL; end: @@ -3879,4 +3889,3 @@ JNIEXPORT jint JNICALL Java_org_gmssl_GmSSLJNI_cert_1verify_1by_1ca_1cert( if (id_str) (*env)->ReleaseStringUTFChars(env, ca_sm2_id, id_str); return ret; } - diff --git a/src/main/java/org/gmssl/GmSSLJNI.java b/src/main/java/org/gmssl/GmSSLJNI.java index 64e6dbb..72903df 100644 --- a/src/main/java/org/gmssl/GmSSLJNI.java +++ b/src/main/java/org/gmssl/GmSSLJNI.java @@ -11,7 +11,7 @@ public class GmSSLJNI { - public final static String GMSSL_JNI_VERSION = "GmSSL JNI 3.1.1"; + public final static String GMSSL_JNI_VERSION = "GmSSL JNI 1.0.0"; public final static int SM3_DIGEST_SIZE = 32; public final static int SM3_HMAC_SIZE = 32; diff --git a/src/main/java/org/gmssl/NativeLoader.java b/src/main/java/org/gmssl/NativeLoader.java index dc119b8..df14f82 100644 --- a/src/main/java/org/gmssl/NativeLoader.java +++ b/src/main/java/org/gmssl/NativeLoader.java @@ -11,8 +11,10 @@ import java.io.*; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.util.Optional; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; /** @@ -26,7 +28,9 @@ public class NativeLoader { /* custom jni library prefix path relative to project resources */ private static final String RESOURCELIB_PREFIXPATH = "lib"; - static final String GMSSLJNILIB_NAME="libgmssljni"; + static final String GMSSLJNILIB_NAME = "libgmssljni"; + + private static final Map loadedLibraries = new HashMap<>(); private static final Properties PROPERTIES = new Properties(); @@ -44,64 +48,79 @@ public class NativeLoader { /** * load jni lib from resources path,the parameter does not contain the path and suffix. - * @param libaray libarayName * + * @param library libraryName */ - public synchronized static void load (String libaray){ - String resourceLibPath = RESOURCELIB_PREFIXPATH + "/" + libaray + "." + libExtension(); + public static void load(String library) { + if (loadedLibraries.containsKey(library)) { + return; + } + Path tempFile = null; + String resourceLibPath = RESOURCELIB_PREFIXPATH + "/" + library + "." + libExtension(); try (InputStream inputStream = NativeLoader.class.getClassLoader().getResourceAsStream(resourceLibPath)) { - if (null == inputStream) { - throw new GmSSLException("lib file not found in JAR: " + resourceLibPath); + if (inputStream == null) { + throw new GmSSLException("lib file not found in classpath: " + resourceLibPath); } - Path tempFile = Files.createTempFile(libaray, "."+libExtension()); + tempFile = Files.createTempFile(library, "." + libExtension()); tempFile.toFile().deleteOnExit(); Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); checkReferencedLib(); System.load(tempFile.toAbsolutePath().toString()); + loadedLibraries.put(library, tempFile); + }catch (IOException e){ + throw new GmSSLException("lib file not found:"+ e.getMessage()); + }catch (UnsatisfiedLinkError e){ + throw new GmSSLException("Failed to load native library:"+ e.getMessage()); } catch (Exception e) { - throw new GmSSLException("Unable to load lib from JAR"); + throw new GmSSLException("Unable to load lib!"); } } /** * Get the operating system type. + * * @return operating system name */ - static String osType(){ - String os="unknown"; - String osName = System.getProperty("os.name").toLowerCase(); - if(osName.startsWith("windows")){ - os="win"; + static String osType() { + String os = "unknown"; + String vmName = System.getProperty("java.vm.name"); + if ("dalvik".equalsIgnoreCase(vmName) || "art".equalsIgnoreCase(vmName)) { + os = "android"; } - if(osName.startsWith("linux")){ - if ("dalvik".equalsIgnoreCase(System.getProperty("java.vm.name"))) { - os = "android"; - System.setProperty("jna.nounpack", "true"); - } else { - os="linux"; - } - } - if(osName.startsWith("mac os x") || osName.startsWith("darwin")){ - os="osx"; + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.startsWith("windows")) { + os = "win"; + } else if (osName.startsWith("linux")) { + os = "linux"; + } else if (osName.startsWith("mac os x") || osName.startsWith("darwin")) { + os = "osx"; + } else { + System.err.println("Unsupported OS: " + osName); } return os; } /** * Get the library extension name based on the operating system type. + * * @return extension name */ - static String libExtension(){ - String osType=osType(); - String libExtension=null; - if("win".equals(osType)){ - libExtension="dll"; - } - if("osx".equals(osType)){ - libExtension="dylib"; - } - if("linux".equals(osType)){ - libExtension="so"; + static String libExtension() { + String osType = osType(); + String libExtension = null; + switch (osType) { + case "win": + libExtension = "dll"; + break; + case "osx": + libExtension = "dylib"; + break; + case "linux": + case "android": + libExtension = "so"; + break; + default: + throw new IllegalArgumentException("Unsupported OS type!"); } return libExtension; } @@ -112,20 +131,36 @@ static String libExtension(){ * in order to correct the @rpath path issue. Alternatively, you can manually execute the command * "install_name_tool -change @rpath/libgmssl.3.dylib /usr/local/lib/libgmssl.3.dylib xxx/lib/libgmssljni.dylib" to fix the library reference path issue. * This has already been loaded and manual execution is unnecessary. - * */ - private static void checkReferencedLib(){ - if("osx".equals(osType())){ - String macReferencedLib=PROPERTIES.getProperty("macReferencedLib"); - Optional optionalStr = Optional.ofNullable(macReferencedLib); - if(optionalStr.isPresent() && !optionalStr.get().isEmpty()){ - File libFile = new File(macReferencedLib); - if(libFile.exists()){ - System.load(macReferencedLib); - } - } + private static void checkReferencedLib() { + String gmsslRoot = System.getProperty("gmssl.root"); + if (gmsslRoot == null || gmsslRoot.isEmpty()) { + gmsslRoot = System.getenv("GMSSL_ROOT"); + } + if (gmsslRoot == null || gmsslRoot.isEmpty()) { + return; + } - } - } + String os = osType(); + if ("osx".equals(os)) { + // Pre-load libgmssl.3.dylib so that @rpath resolution works + String macReferencedLib = PROPERTIES.getProperty("macReferencedLib"); + if (macReferencedLib == null || macReferencedLib.isEmpty()) { + Path libPath = Paths.get(gmsslRoot, "lib", "libgmssl.3.dylib"); + macReferencedLib = libPath.toString(); + } + File libFile = new File(macReferencedLib); + if (libFile.exists()) { + System.load(macReferencedLib); + } + } else if ("win".equals(os)) { + // Pre-load gmssl.dll so that the JNI DLL can resolve its dependency + Path libPath = Paths.get(gmsslRoot, "bin", "gmssl.dll"); + File libFile = libPath.toFile(); + if (libFile.exists()) { + System.load(libPath.toString()); + } + } + } } diff --git a/src/main/java/org/gmssl/Sm4.java b/src/main/java/org/gmssl/Sm4.java index d1b593c..bf9de4f 100644 --- a/src/main/java/org/gmssl/Sm4.java +++ b/src/main/java/org/gmssl/Sm4.java @@ -41,7 +41,6 @@ public Sm4(byte[] key, boolean do_encrypt) { } public void encrypt(byte[] in, int in_offset, byte[] out, int out_offset) { - if (in == null || in_offset < 0 || in_offset + this.BLOCK_SIZE <= 0 diff --git a/src/main/java/org/gmssl/crypto/CipherPaddingEnum.java b/src/main/java/org/gmssl/crypto/CipherPaddingEnum.java new file mode 100644 index 0000000..a11b709 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/CipherPaddingEnum.java @@ -0,0 +1,23 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public enum CipherPaddingEnum { + NoPadding, + ZeroPadding, + PKCS5Padding, + PKCS7Padding; +} diff --git a/src/main/java/org/gmssl/crypto/GmSSLProvider.java b/src/main/java/org/gmssl/crypto/GmSSLProvider.java new file mode 100644 index 0000000..0b4cb7b --- /dev/null +++ b/src/main/java/org/gmssl/crypto/GmSSLProvider.java @@ -0,0 +1,42 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto; + +import java.security.Provider; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * GmSSL-Java currently provides functionality for random number generation, SM3 hash, SM3 message authentication code (HMAC-SM3), + * SM4 encryption (including block encryption and CBC/CTR/GCM encryption modes), ZUC encryption, SM2 encryption/signature, SM9 encryption/signature, and SM2 certificate parsing. + * These features cover the main application development scenarios for the current Chinese cryptographic algorithms. + */ +public class GmSSLProvider extends Provider { + + public GmSSLProvider() { + super("GmSSL", "1.0.0", "GmSSL Provider"); + + put("SecureRandom.Random", "org.gmssl.crypto.Random"); + put("Cipher.SM2", "org.gmssl.crypto.asymmetric.SM2Cipher"); + put("KeyPairGenerator.SM2", "org.gmssl.crypto.asymmetric.SM2KeyPairGenerator"); + put("Signature.SM2", "org.gmssl.crypto.asymmetric.SM2Signature"); + put("MessageDigest.SM3", "org.gmssl.crypto.digest.SM3Digest"); + put("Mac.SM3", "org.gmssl.crypto.digest.SM3Hmac"); + put("SecretKeyFactory.SM3Pbkdf2", "org.gmssl.crypto.digest.SM3Pbkdf2"); + put("Cipher.SM4", "org.gmssl.crypto.symmetric.SM4Cipher"); + put("Cipher.SM9", "org.gmssl.crypto.asymmetric.SM9Cipher"); + put("Signature.SM9", "org.gmssl.crypto.asymmetric.SM9Signature"); + put("KeyPairGenerator.SM9", "org.gmssl.crypto.asymmetric.SM9KeyPairGeneratorSpi"); + put("Cipher.ZUC", "org.gmssl.crypto.symmetric.ZucCipher"); + } + + +} diff --git a/src/main/java/org/gmssl/crypto/PKCS7PaddingScheme.java b/src/main/java/org/gmssl/crypto/PKCS7PaddingScheme.java new file mode 100644 index 0000000..79e01a5 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/PKCS7PaddingScheme.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto; + +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description PKCS#7 + * + */ +public class PKCS7PaddingScheme implements PaddingScheme{ + @Override + public String getPaddingName() { + return "PKCS#7"; + } + + @Override + public byte[] pad(byte[] input, int blockSize) { + int paddingLength = blockSize - (input.length % blockSize); + byte[] padding = new byte[paddingLength]; + Arrays.fill(padding, (byte) paddingLength); + byte[] result = new byte[input.length + padding.length]; + System.arraycopy(input, 0, result, 0, input.length); + System.arraycopy(padding, 0, result, input.length, padding.length); + return result; + } + + @Override + public byte[] unpad(byte[] input) { + int paddingSize = input[input.length - 1]; + if (paddingSize <= 0 || paddingSize > input.length) { + throw new IllegalArgumentException("Invalid pkcs#7 padding!"); + } + for (int i = input.length - paddingSize; i < input.length; i++) { + if (input[i] != paddingSize) { + throw new IllegalArgumentException("Invalid pkcs#7 padding!"); + } + } + return Arrays.copyOfRange(input, 0, input.length - paddingSize); + } + +} diff --git a/src/main/java/org/gmssl/crypto/PaddingScheme.java b/src/main/java/org/gmssl/crypto/PaddingScheme.java new file mode 100644 index 0000000..1c18535 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/PaddingScheme.java @@ -0,0 +1,40 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public interface PaddingScheme { + + /** + * get padding name + * @return paddingName + */ + String getPaddingName(); + + /** + * Pad according to fixed block size + * @param input Data to be padded + * @param blockSize block size + * @return padded data + */ + byte[] pad(byte[] input, int blockSize); + + /** + * Unpad according to fixed block size + * @param input Data to be unpadded + * @return unpadded data + */ + byte[] unpad(byte[] input); +} diff --git a/src/main/java/org/gmssl/crypto/Random.java b/src/main/java/org/gmssl/crypto/Random.java new file mode 100644 index 0000000..a19079a --- /dev/null +++ b/src/main/java/org/gmssl/crypto/Random.java @@ -0,0 +1,74 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.SecureRandomSpi; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class Random extends SecureRandomSpi { + + public Random() { + super(); + } + + @Override + protected void engineSetSeed(byte[] seed) { + if (seed == null || seed.length == 0) { + throw new IllegalArgumentException("Seed cannot be null or empty"); + } + //rand_seed + throw new GmSSLException("The current method is not supported."); + } + + @Override + protected void engineNextBytes(byte[] bytes) { + if (bytes == null) { + throw new IllegalArgumentException("Output buffer cannot be null"); + } + randBytes(bytes,0, bytes.length); + } + + @Override + protected byte[] engineGenerateSeed(int numBytes) { + if (numBytes <= 0) { + throw new IllegalArgumentException("Number of bytes must be positive"); + } + return randBytes(numBytes); + } + + public byte[] randBytes(int len) { + byte[] out = new byte[len]; + if (GmSSLJNI.rand_bytes(out, 0, len) != 1) { + throw new GmSSLException("Failed to generate seed"); + } + return out; + } + + public void randBytes(byte[] out, int offset, int len) { + if (out == null + || offset < 0 + || len < 0 + || offset + len <= 0 + || out.length < offset + len) { + throw new GmSSLException(""); + } + if (GmSSLJNI.rand_bytes(out, offset, len) != 1) { + throw new GmSSLException(""); + } + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2Certificate.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2Certificate.java new file mode 100644 index 0000000..a4cab9f --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2Certificate.java @@ -0,0 +1,127 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.*; +import java.security.cert.*; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * The certificate format is the standard X.509v3 certificate. Currently, only the SM2 signature algorithm is supported. + * This includes functions for parsing and verifying SM2 certificates. However, issuing and generating SM2 certificates are not supported. + * If the application needs to implement certificate request (i.e., generating CSR files) or self-built CA certificate issuance, + * these functionalities can be achieved using the GmSSL library or the gmssl command-line tool. + */ +public class SM2Certificate{ + + private byte[] cert; + + public byte[] getEncoded() throws CertificateEncodingException { + if (this.cert == null) { + throw new GmSSLException(""); + } + return this.cert; + } + + public String toString() { + return null; + } + + public PublicKey getPublicKey() { + if (this.cert == null) { + throw new GmSSLException(""); + } + long pub_key; + if ((pub_key = GmSSLJNI.cert_get_subject_public_key(this.cert)) == 0) { + throw new GmSSLException(""); + } + boolean has_private_key = false; + return new SM2PublicKey(pub_key, has_private_key); + } + + public void importPem(String file) { + if ((this.cert = GmSSLJNI.cert_from_pem(file)) == null) { + throw new GmSSLException(""); + } + } + + public void exportPem(String file) { + if (this.cert == null) { + throw new GmSSLException(""); + } + if (GmSSLJNI.cert_to_pem(this.cert, file) != 1) { + throw new GmSSLException(""); + } + } + + public boolean verifyByCaCertificate(SM2Certificate caCert, String sm2Id) throws CertificateEncodingException { + if (this.cert == null) { + throw new GmSSLException(""); + } + int ret = GmSSLJNI.cert_verify_by_ca_cert(this.cert, caCert.getEncoded(), sm2Id); + if (ret == 1) { + return true; + } else { + return false; + } + } + + public byte[] getSerialNumber() { + if (this.cert == null) { + throw new GmSSLException(""); + } + byte[] serial; + if ((serial = GmSSLJNI.cert_get_serial_number(this.cert)) == null) { + throw new GmSSLException(""); + } + return serial; + } + + public java.util.Date getNotBefore() { + if (this.cert == null) { + throw new GmSSLException(""); + } + return new java.util.Date(GmSSLJNI.cert_get_not_before(this.cert)); + } + + public java.util.Date getNotAfter() { + if (this.cert == null) { + throw new GmSSLException(""); + } + return new java.util.Date(GmSSLJNI.cert_get_not_after(this.cert)); + } + + public String[] getIssuer() { + if (this.cert == null) { + throw new GmSSLException(""); + } + String[] issuer; + if ((issuer = GmSSLJNI.cert_get_issuer(this.cert)) == null) { + throw new GmSSLException(""); + } + return issuer; + } + + public String[] getSubject() { + if (this.cert == null) { + throw new GmSSLException(""); + } + String[] subject; + if ((subject = GmSSLJNI.cert_get_subject(this.cert)) == null) { + throw new GmSSLException(""); + } + return subject; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2Cipher.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2Cipher.java new file mode 100644 index 0000000..2abc8c0 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2Cipher.java @@ -0,0 +1,201 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.*; +import java.nio.ByteBuffer; +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * The SM2Cipher class implements encryption and decryption methods. When calling the encrypt method, ensure that the length of the plaintext input does not exceed the MAX_PLAINTEXT_SIZE limit. + * If you need to encrypt a message at the reference layer, first generate a symmetric key, encrypt the message using SM4-GCM, and then encrypt the symmetric key using SM2. + */ +public class SM2Cipher extends CipherSpi { + + private int mode; + private SM2Key key; + private SecureRandom random; + private ByteBuffer buffer; + + /** + * SM2 uses the C1C2C3 encryption mode. + * @param mode the cipher mode + * + * @throws NoSuchAlgorithmException + */ + @Override + protected void engineSetMode(String mode) throws NoSuchAlgorithmException { + + } + + /** + * SM2 has adopted the corresponding padding rule and does not involve specific padding modes. + * @param padding the padding mechanism + * + * @throws NoSuchPaddingException + */ + @Override + protected void engineSetPadding(String padding) throws NoSuchPaddingException { + + } + + /** + * SM2 does not have a fixed block size. + * @return + */ + @Override + protected int engineGetBlockSize() { + return 0; + } + + @Override + protected int engineGetOutputSize(int inputLen) { + return 0; + } + + @Override + protected byte[] engineGetIV() { + return null; + } + + @Override + protected AlgorithmParameters engineGetParameters() { + return null; + } + + @Override + protected void engineInit(int mode, Key key, SecureRandom secureRandom) throws InvalidKeyException { + if (!(key instanceof SM2Key)) { + throw new InvalidKeyException("Invalid key type"); + } + this.key = (SM2Key)key; + this.mode = mode; + this.random = (secureRandom != null) ? secureRandom : new SecureRandom(); + this.buffer = ByteBuffer.allocate(1024); + } + + @Override + protected void engineInit(int mode, Key key, AlgorithmParameterSpec algorithmParameterSpec, SecureRandom secureRandom) throws InvalidKeyException, InvalidAlgorithmParameterException { + engineInit(mode, key, random); + } + + @Override + protected void engineInit(int i, Key key, AlgorithmParameters algorithmParameters, SecureRandom secureRandom) throws InvalidKeyException, InvalidAlgorithmParameterException { + engineInit(mode, key, random); + } + + /** + * + * @param input the input buffer + * @param inputOffset the offset in input where the input + * starts + * @param inputLen the input length + * + * @return null + * The SM2 algorithm typically does not return any data during the engineUpdate phase. + */ + @Override + protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { + if (input == null || inputOffset < 0 || inputLen < 0 || inputOffset + inputLen > input.length) { + throw new IllegalArgumentException("Invalid input parameters"); + } + buffer.put(input, inputOffset, inputLen); + return null; + } + + /** + * The method does not perform any encryption or decryption; it only stores the input data. The returned result is meaningless, and the final result is output through `doFinal`. + * @param input the input buffer + * @param inputOffset the offset in input where the input + * starts + * @param inputLen the input length + * @param output the buffer for the result + * @param outputOffset the offset in output where the result + * is stored + * + * @return + * @throws ShortBufferException + */ + @Override + protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { + if (input == null || inputOffset < 0 || inputLen < 0 || inputOffset + inputLen > input.length) { + throw new IllegalArgumentException("Invalid input parameters"); + } + buffer.put(input, inputOffset, inputLen); + return 0; + } + + @Override + protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + if(null != input){ + buffer.put(input, inputOffset, inputLen); + } + byte[] data = new byte[buffer.position()]; + buffer.flip(); + buffer.get(data); + buffer.clear(); + + if (mode == Cipher.ENCRYPT_MODE) { + return encrypt(data); + } else if (mode == Cipher.DECRYPT_MODE) { + return decrypt(data); + } else { + throw new GmSSLException("Cipher not initialized properly"); + } + } + + @Override + protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + byte[] result = engineDoFinal(input, inputOffset, inputLen); + System.arraycopy(result, 0, output, outputOffset, result.length); + return result.length; + } + + public byte[] encrypt(byte[] plaintext) { + if (this.key.sm2_key == 0) { + throw new GmSSLException(""); + } + if (plaintext == null + || plaintext.length > this.key.MAX_PLAINTEXT_SIZE) { + throw new GmSSLException(""); + } + + byte[] ciphertext; + if ((ciphertext = GmSSLJNI.sm2_encrypt(this.key.sm2_key, plaintext)) == null) { + throw new GmSSLException(""); + } + return ciphertext; + } + + public byte[] decrypt(byte[] ciphertext) { + if (this.key.sm2_key == 0) { + throw new GmSSLException(""); + } + if (this.key.has_private_key == false) { + throw new GmSSLException(""); + } + if (ciphertext == null) { + throw new GmSSLException(""); + } + + byte[] plaintext; + if ((plaintext = GmSSLJNI.sm2_decrypt(this.key.sm2_key, ciphertext)) == null) { + throw new GmSSLException(""); + } + return plaintext; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2Key.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2Key.java new file mode 100644 index 0000000..ac006e2 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2Key.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.Key; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description SM2Key + * + */ +public abstract class SM2Key implements Key { + + public final static int MAX_PLAINTEXT_SIZE = GmSSLJNI.SM2_MAX_PLAINTEXT_SIZE; + + protected long sm2_key; + protected boolean has_private_key; + + protected SM2Key() { + this.sm2_key = 0; + this.has_private_key = false; + } + + protected SM2Key(long sm2_key, boolean has_private_key) { + this.sm2_key = sm2_key; + this.has_private_key = has_private_key; + } + + @Override + public String getAlgorithm() { + return "SM2"; + } + + long getPrivateKey() { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + return this.sm2_key; + } + + long getPublicKey() { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + return this.sm2_key; + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2KeyPairGenerator.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2KeyPairGenerator.java new file mode 100644 index 0000000..3fe591e --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2KeyPairGenerator.java @@ -0,0 +1,49 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.*; +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM2KeyPairGenerator extends KeyPairGeneratorSpi { + + private long sm2_key = 0; + private boolean has_private_key = false; + + @Override + public void initialize(int keysize, SecureRandom random) { + generateKey(); + } + + @Override + public KeyPair generateKeyPair() { + PublicKey publicKey = new SM2PublicKey(sm2_key, has_private_key); + PrivateKey privateKey = new SM2PrivateKey(sm2_key, has_private_key); + return new KeyPair(publicKey, privateKey); + } + + private void generateKey() { + if (this.sm2_key != 0) { + GmSSLJNI.sm2_key_free(this.sm2_key); + } + if ((sm2_key = GmSSLJNI.sm2_key_generate()) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = true; + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2PrivateKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2PrivateKey.java new file mode 100644 index 0000000..bd5ac98 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2PrivateKey.java @@ -0,0 +1,104 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.PrivateKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM2PrivateKey extends SM2Key implements PrivateKey{ + + protected SM2PrivateKey() { + super(); + } + + public SM2PrivateKey(byte[] der) { + importPrivateKeyInfoDer(der); + } + + public SM2PrivateKey(String password, String file) { + importEncryptedPrivateKeyInfoPem(password, file); + } + + protected SM2PrivateKey(long sm2_key, boolean has_private_key) { + super(sm2_key,has_private_key); + } + + public String getAlgorithm() { + return "SM2"; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return exportPrivateKeyInfoDer(); + } + + public void importPrivateKeyInfoDer(byte[] der) { + if (der == null) { + throw new GmSSLException(""); + } + if (this.sm2_key != 0) { + GmSSLJNI.sm2_key_free(this.sm2_key); + } + if ((this.sm2_key = GmSSLJNI.sm2_private_key_info_from_der(der)) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = true; + } + + public byte[] exportPrivateKeyInfoDer() { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + byte[] der; + if ((der = GmSSLJNI.sm2_private_key_info_to_der(this.sm2_key)) == null) { + throw new GmSSLException(""); + } + return der; + } + + public void importEncryptedPrivateKeyInfoPem(String pass, String file) { + if (this.sm2_key != 0) { + GmSSLJNI.sm2_key_free(this.sm2_key); + } + if ((sm2_key = GmSSLJNI.sm2_private_key_info_decrypt_from_pem(pass, file)) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = true; + } + + public void exportEncryptedPrivateKeyInfoPem(String pass, String file) { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm2_private_key_info_encrypt_to_pem(this.sm2_key, pass, file) != 1) { + throw new GmSSLException(""); + } + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2PublicKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2PublicKey.java new file mode 100644 index 0000000..5d301f8 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2PublicKey.java @@ -0,0 +1,111 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; +import org.gmssl.Sm3; + +import java.security.PublicKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM2PublicKey extends SM2Key implements PublicKey{ + + protected SM2PublicKey() { + super(); + } + + public SM2PublicKey(byte[] der) { + importPublicKeyInfoDer(der); + } + + public SM2PublicKey(String file) { + importPublicKeyInfoPem(file); + } + + protected SM2PublicKey(long sm2_key, boolean has_private_key) { + super(sm2_key,has_private_key); + } + + @Override + public String getAlgorithm() { + return "SM2"; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return exportPublicKeyInfoDer(); + } + + public void importPublicKeyInfoDer(byte[] der) { + if (der == null) { + throw new GmSSLException(""); + } + if (this.sm2_key != 0) { + GmSSLJNI.sm2_key_free(this.sm2_key); + } + if ((this.sm2_key = GmSSLJNI.sm2_public_key_info_from_der(der)) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = false; + } + + public byte[] exportPublicKeyInfoDer() { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + byte[] der; + if ((der = GmSSLJNI.sm2_public_key_info_to_der(this.sm2_key)) == null) { + throw new GmSSLException(""); + } + return der; + } + + public void importPublicKeyInfoPem(String file) { + if (this.sm2_key != 0) { + GmSSLJNI.sm2_key_free(this.sm2_key); + } + if ((this.sm2_key = GmSSLJNI.sm2_public_key_info_from_pem(file)) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = false; + } + + public void exportPublicKeyInfoPem(String file) { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm2_public_key_info_to_pem(this.sm2_key, file) != 1) { + throw new GmSSLException(""); + } + } + + public byte[] computeZ(String id) { + if (this.sm2_key == 0) { + throw new GmSSLException(""); + } + byte[] z = new byte[Sm3.DIGEST_SIZE]; + if (GmSSLJNI.sm2_compute_z(this.sm2_key, id, z) != 1) { + throw new GmSSLException(""); + } + return z; + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM2Signature.java b/src/main/java/org/gmssl/crypto/asymmetric/SM2Signature.java new file mode 100644 index 0000000..3d6bd8b --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM2Signature.java @@ -0,0 +1,162 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.*; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description SM2Signature + * It provides signing and verification functionality for messages of arbitrary length. + */ +public class SM2Signature extends SignatureSpi { + + public final static String DEFAULT_ID = GmSSLJNI.SM2_DEFAULT_ID; + + private long sm2_sign_ctx = 0; + private boolean inited = false; + + private boolean do_sign = true; + + public SM2Signature() { + super(); + } + + @Override + protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { + if (!(publicKey instanceof SM2PublicKey)) { + throw new GmSSLException("Invalid publicKey type"); + } + init(); + initVerify((SM2PublicKey) publicKey,DEFAULT_ID); + } + + @Override + protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { + if (!(privateKey instanceof SM2PrivateKey)) { + throw new GmSSLException("Invalid privateKey type"); + } + init(); + initSign((SM2PrivateKey) privateKey,DEFAULT_ID); + } + + @Override + protected void engineUpdate(byte b) throws SignatureException { + byte[] data= new byte[]{b}; + update(data, 0, data.length); + } + + @Override + protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { + update(b, off, len); + } + + @Override + protected byte[] engineSign() throws SignatureException { + byte[] data = sign(); + return data; + } + + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + boolean verifyResult= verify(sigBytes); + return verifyResult; + } + + @Override + protected void engineSetParameter(String param, Object value) throws InvalidParameterException { + } + + @Override + protected Object engineGetParameter(String param) throws InvalidParameterException { + return null; + } + + private void init(){ + if ((this.sm2_sign_ctx = GmSSLJNI.sm2_sign_ctx_new()) == 0) { + throw new GmSSLException(""); + } + this.inited = true; + } + + private void initSign(SM2PrivateKey privateKey,String id){ + if (GmSSLJNI.sm2_sign_init(this.sm2_sign_ctx, privateKey.getPrivateKey(), id) != 1) { + throw new GmSSLException(""); + } + this.do_sign = true; + } + + private void initVerify(SM2PublicKey publicKey,String id){ + if (GmSSLJNI.sm2_verify_init(sm2_sign_ctx, publicKey.getPublicKey(), id) != 1) { + throw new GmSSLException(""); + } + this.do_sign = false; + } + + private void update(byte[] data, int offset, int len) { + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (data == null + || offset < 0 + || len < 0 + || offset + len <= 0 + || data.length < offset + len) { + throw new GmSSLException(""); + } + + if (this.do_sign == true) { + if (GmSSLJNI.sm2_sign_update(this.sm2_sign_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } else { + if (GmSSLJNI.sm2_verify_update(this.sm2_sign_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } + } + + private byte[] sign() { + if (this.inited == false) { + throw new GmSSLException(""); + } + if (this.do_sign == false) { + throw new GmSSLException(""); + } + + byte[] sig; + if ((sig = GmSSLJNI.sm2_sign_finish(this.sm2_sign_ctx)) == null) { + throw new GmSSLException(""); + } + this.inited = false; + return sig; + } + + private boolean verify(byte[] signature) { + if (this.sm2_sign_ctx == 0) { + throw new GmSSLException(""); + } + if (this.do_sign == true) { + throw new GmSSLException(""); + } + this.inited = false; + int ret; + if ((ret = GmSSLJNI.sm2_verify_finish(sm2_sign_ctx, signature)) != 1) { + return false; + } + return true; + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9Cipher.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9Cipher.java new file mode 100644 index 0000000..5f1564c --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9Cipher.java @@ -0,0 +1,180 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; + +import javax.crypto.*; +import java.nio.ByteBuffer; +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description SM9Cipher + * The SM9 algorithm belongs to an identity-based encryption (IBE) system. + * Since IBE does not require a Certificate Authority (CA) or a digital certificate infrastructure, + * if the application operates in a closed internal environment where all participating users are within the system, adopting the SM9 solution is a better choice. + */ +public class SM9Cipher extends CipherSpi { + + private int opmode; + + private Key key; + + private ByteBuffer buffer; + + private String id; + + /** + * + * @param mode the cipher mode + * @throws NoSuchAlgorithmException + * @description + * SM9 is an identity-based encryption and signature algorithm that does not support traditional block cipher modes. + */ + @Override + protected void engineSetMode(String mode) throws NoSuchAlgorithmException { + } + + /** + * + * @param padding the padding mechanism + * @throws NoSuchPaddingException + * @description + * SM9 is an identity-based encryption and signature algorithm that does not support common padding modes. + */ + @Override + protected void engineSetPadding(String padding) throws NoSuchPaddingException { + } + + /** + * SM9 is a public key encryption algorithm that does not have a fixed block size and does not use blocks. + * @return + */ + @Override + protected int engineGetBlockSize() { + return 0; + } + + @Override + protected int engineGetOutputSize(int inputLen) { + return 0; + } + + @Override + protected byte[] engineGetIV() { + return new byte[0]; + } + + @Override + protected AlgorithmParameters engineGetParameters() { + return null; + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + if (!(key instanceof SM9PrivateKey)) { + throw new GmSSLException("Invalid privateKey type"); + } + this.opmode = opmode; + this.key = key; + SM9PrivateKey privateKey = (SM9PrivateKey)key; + SM9UserKey userKey = (SM9UserKey)privateKey.getSecretKey(); + this.id = userKey.getId(); + this.buffer = ByteBuffer.allocate(1024); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + if (!(key instanceof SM9PublicKey)) { + throw new GmSSLException("Invalid publicKey type"); + } + this.opmode = opmode; + this.key = key; + this.id = ((SM9EncMasterKeyGenParameterSpec)params).getId(); + this.buffer = ByteBuffer.allocate(1024); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + } + + /** + * SM9 encryption and decryption are completed during the engineDoFinal phase. During the update phase, data is only cached, and no partial encryption or decryption results are returned. + * @param input the input buffer + * @param inputOffset the offset in input where the input + * starts + * @param inputLen the input length + * + * @return + */ + @Override + protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { + buffer.put(input, inputOffset, inputLen); + return null; + } + + /** + * SM9 encryption and decryption are completed during the engineDoFinal phase. During the update phase, data is only cached, and no partial encryption or decryption results are returned. + * @param input the input buffer + * @param inputOffset the offset in input where the input + * starts + * @param inputLen the input length + * @param output the buffer for the result + * @param outputOffset the offset in output where the result + * is stored + * + * @return + * @throws ShortBufferException + */ + @Override + protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { + buffer.put(input, inputOffset, inputLen); + return 0; + } + + @Override + protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + buffer.put(input, inputOffset, inputLen); + byte[] data = new byte[buffer.position()]; + buffer.flip(); + buffer.get(data); + buffer.clear(); + + if (opmode == Cipher.ENCRYPT_MODE) { + return encrypt(data); + } else if (opmode == Cipher.DECRYPT_MODE) { + return decrypt(data); + } else { + throw new GmSSLException("Cipher not initialized properly"); + } + } + + @Override + protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + byte[] result = engineDoFinal(input, inputOffset, inputLen); + System.arraycopy(result, 0, output, outputOffset, result.length); + return result.length; + } + + private byte[] encrypt(byte[] plaintext) { + SM9PublicKey encMasterKey = (SM9PublicKey) key; + byte[] ciphertext = encMasterKey.encrypt(plaintext,id); + return ciphertext; + } + + private byte[] decrypt(byte[] ciphertext) { + SM9PrivateKey privateKey = (SM9PrivateKey)key; + byte[] plaintext = privateKey.decrypt(ciphertext); + return plaintext; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKey.java new file mode 100644 index 0000000..f549cda --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKey.java @@ -0,0 +1,139 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9EncMasterKey extends SM9MasterKey{ + + public final static int MAX_PLAINTEXT_SIZE = GmSSLJNI.SM9_MAX_PLAINTEXT_SIZE; + + public SM9EncMasterKey(){ + publicKey = new SM9EncPublicKey(); + privateKey = new SM9EncPrivateKey(); + } + + class SM9EncPublicKey extends SM9PublicKey { + + public long getPublicKey() { + if (master_key == 0) { + throw new GmSSLException(""); + } + return master_key; + } + + public void importPublicKeyPem(String file) { + if (master_key != 0) { + GmSSLJNI.sm9_enc_master_key_free(master_key); + } + if ((master_key = GmSSLJNI.sm9_enc_master_public_key_from_pem(file)) == 0) { + throw new GmSSLException(""); + } + has_private_key = false; + } + + public void exportPublicKeyPem(String file) { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm9_enc_master_public_key_to_pem(master_key, file) != 1) { + throw new GmSSLException(""); + } + } + + public byte[] encrypt(byte[] plaintext, String id) { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (plaintext == null + || plaintext.length > MAX_PLAINTEXT_SIZE) { + throw new GmSSLException(""); + } + + byte[] ciphertext; + if ((ciphertext = GmSSLJNI.sm9_encrypt(master_key, id, plaintext)) == null) { + throw new GmSSLException(""); + } + return ciphertext; + } + + } + + class SM9EncPrivateKey extends SM9PrivateKey{ + public void importEncryptedPrivateKeyInfoPem(String pass, String file) { + if (master_key != 0) { + GmSSLJNI.sm9_enc_master_key_free(master_key); + } + if ((master_key = GmSSLJNI.sm9_enc_master_key_info_decrypt_from_pem(pass, file)) == 0) { + throw new GmSSLException(""); + } + has_private_key = true; + } + + public void exportEncryptedPrivateKeyInfoPem(String pass, String file) { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (has_private_key == false) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm9_enc_master_key_info_encrypt_to_pem(master_key, pass, file) != 1) { + throw new GmSSLException(""); + } + } + + public SM9EncMasterKey getSecretKey() { + return SM9EncMasterKey.this; + } + + } + + public void generateMasterKey() { + if (master_key != 0) { + GmSSLJNI.sm9_enc_master_key_free(master_key); + } + if ((master_key = GmSSLJNI.sm9_enc_master_key_generate()) == 0) { + throw new GmSSLException(""); + } + has_private_key = true; + } + + public long getSecretKey() { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (has_private_key == false) { + throw new GmSSLException(""); + } + return master_key; + } + + public SM9UserKey extractKey(String id) { + if (this.master_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + long key; + if ((key = GmSSLJNI.sm9_enc_master_key_extract_key(this.master_key, id)) == 0) { + throw new GmSSLException(""); + } + return new SM9EncUserKey(key, id); + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKeyGenParameterSpec.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKeyGenParameterSpec.java new file mode 100644 index 0000000..da982ad --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncMasterKeyGenParameterSpec.java @@ -0,0 +1,42 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLJNI; + +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9EncMasterKeyGenParameterSpec implements AlgorithmParameterSpec { + + private String id; + + protected SM9EncMasterKeyGenParameterSpec() { + + } + + public SM9EncMasterKeyGenParameterSpec(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} + diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9EncUserKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncUserKey.java new file mode 100644 index 0000000..4a417da --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9EncUserKey.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; +import org.gmssl.Sm9SignKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9EncUserKey extends SM9UserKey{ + protected SM9EncUserKey(long sm9_key, String id) { + super(sm9_key, id); + this.privateKey = new SM9EncPrivateKey(); + } + + class SM9EncPrivateKey extends SM9PrivateKey { + public void importEncryptedPrivateKeyInfoPem(String pass, String file) { + if (sm9_key != 0) { + GmSSLJNI.sm9_enc_key_free(sm9_key); + } + if ((sm9_key = GmSSLJNI.sm9_enc_key_info_decrypt_from_pem(pass, file)) == 0) { + throw new GmSSLException(""); + } + } + + public void exportEncryptedPrivateKeyInfoPem(String pass, String file) { + if (sm9_key == 0) { + throw new GmSSLException("Key not initialized"); + } + if (GmSSLJNI.sm9_enc_key_info_encrypt_to_pem(sm9_key, pass, file) != 1) { + throw new GmSSLException(""); + } + } + + public byte[] decrypt(byte[] ciphertext) { + if (sm9_key == 0) { + throw new GmSSLException(""); + } + if (ciphertext == null) { + throw new GmSSLException(""); + } + + byte[] plaintext; + if ((plaintext = GmSSLJNI.sm9_decrypt(sm9_key, id, ciphertext)) == null) { + throw new GmSSLException(""); + } + return plaintext; + } + public SM9EncUserKey getSecretKey() { + return SM9EncUserKey.this; + } + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9KeyPairGeneratorSpi.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9KeyPairGeneratorSpi.java new file mode 100644 index 0000000..a3962cc --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9KeyPairGeneratorSpi.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGeneratorSpi; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9KeyPairGeneratorSpi extends KeyPairGeneratorSpi { + + private SM9MasterKey masterKey; + + @Override + public void initialize(int keysize, SecureRandom random) { + + } + + @Override + public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { + if (params == null) { + throw new InvalidAlgorithmParameterException("The parameter must not be null"); + } + if (params instanceof SM9SignMasterKeyGenParameterSpec) { + SM9SignMasterKeyGenParameterSpec spec = (SM9SignMasterKeyGenParameterSpec) params; + this.masterKey = new SM9SignMasterKey(); + } else if (params instanceof SM9EncMasterKeyGenParameterSpec) { + SM9EncMasterKeyGenParameterSpec spec = (SM9EncMasterKeyGenParameterSpec) params; + this.masterKey = new SM9EncMasterKey(); + } else { + throw new InvalidAlgorithmParameterException(""); + } + masterKey.generateMasterKey(); + } + + @Override + public KeyPair generateKeyPair() { + return new KeyPair(masterKey.publicKey, masterKey.privateKey); + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9MasterKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9MasterKey.java new file mode 100644 index 0000000..3ad7fe3 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9MasterKey.java @@ -0,0 +1,43 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.spec.KeySpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public abstract class SM9MasterKey implements KeySpec { + + protected long master_key; + + protected boolean has_private_key; + + protected SM9PublicKey publicKey; + + protected SM9PrivateKey privateKey; + + public abstract void generateMasterKey(); + + public abstract long getSecretKey(); + + public abstract SM9UserKey extractKey(String id); + + public SM9PublicKey getPublicKey() { + return this.publicKey; + } + + public SM9PrivateKey getPrivateKey() { + return this.privateKey; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9PrivateKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9PrivateKey.java new file mode 100644 index 0000000..d34c9de --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9PrivateKey.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.PrivateKey; +import java.security.spec.KeySpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public abstract class SM9PrivateKey implements PrivateKey { + + @Override + public String getAlgorithm() { + return null; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + + public abstract KeySpec getSecretKey(); + + public abstract void importEncryptedPrivateKeyInfoPem(String pass, String file); + + public abstract void exportEncryptedPrivateKeyInfoPem(String pass, String file); + + public byte[] decrypt(byte[] ciphertext) { + return null; + } + + public byte[] sign(long sign_ctx) { + return null; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9PublicKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9PublicKey.java new file mode 100644 index 0000000..474776c --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9PublicKey.java @@ -0,0 +1,50 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.PublicKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public abstract class SM9PublicKey implements PublicKey { + + @Override + public String getAlgorithm() { + return null; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + + public abstract long getPublicKey(); + + public abstract void importPublicKeyPem(String file); + + public abstract void exportPublicKeyPem(String file); + + public byte[] encrypt(byte[] plaintext, String id){ + return null; + }; + + public Boolean verify(byte[] signature, String id,long sign_ctx){ + return null; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKey.java new file mode 100644 index 0000000..6b4dbe7 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKey.java @@ -0,0 +1,129 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9SignMasterKey extends SM9MasterKey{ + + public SM9SignMasterKey(){ + publicKey = new SM9SignPublicKey(); + privateKey = new SM9SignPrivateKey(); + } + + class SM9SignPublicKey extends SM9PublicKey { + public long getPublicKey() { + if (master_key == 0) { + throw new GmSSLException(""); + } + return master_key; + } + + public void importPublicKeyPem(String file) { + if (master_key != 0) { + GmSSLJNI.sm9_sign_master_key_free(master_key); + } + if ((master_key = GmSSLJNI.sm9_sign_master_public_key_from_pem(file)) == 0) { + throw new GmSSLException(""); + } + has_private_key = false; + } + + public void exportPublicKeyPem(String file) { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm9_sign_master_public_key_to_pem(master_key, file) != 1) { + throw new GmSSLException(""); + } + } + + public Boolean verify(byte[] signature, String id,long sm9_sign_ctx) { + int ret; + ret = GmSSLJNI.sm9_verify_finish(sm9_sign_ctx, signature, master_key, id); + if (ret == 1) { + return true; + } else { + return false; + } + } + + } + + class SM9SignPrivateKey extends SM9PrivateKey{ + public void importEncryptedPrivateKeyInfoPem(String pass, String file) { + if (master_key != 0) { + GmSSLJNI.sm9_sign_master_key_free(master_key); + } + if ((master_key = GmSSLJNI.sm9_sign_master_key_info_decrypt_from_pem(pass, file)) == 0) { + throw new GmSSLException(""); + } + has_private_key = true; + } + + public void exportEncryptedPrivateKeyInfoPem(String pass, String file) { + if (master_key == 0) { + throw new GmSSLException(""); + } + if (has_private_key == false) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm9_sign_master_key_info_encrypt_to_pem(master_key, pass, file) != 1) { + throw new GmSSLException(""); + } + } + + public SM9SignMasterKey getSecretKey() { + return SM9SignMasterKey.this; + } + + } + public void generateMasterKey() { + if (this.master_key != 0) { + GmSSLJNI.sm9_sign_master_key_free(this.master_key); + } + if ((this.master_key = GmSSLJNI.sm9_sign_master_key_generate()) == 0) { + throw new GmSSLException(""); + } + this.has_private_key = true; + } + + public long getSecretKey() { + if (this.master_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + return this.master_key; + } + + public SM9UserKey extractKey(String id) { + if (this.master_key == 0) { + throw new GmSSLException(""); + } + if (this.has_private_key == false) { + throw new GmSSLException(""); + } + long key; + if ((key = GmSSLJNI.sm9_sign_master_key_extract_key(this.master_key, id)) == 0) { + throw new GmSSLException(""); + } + return new SM9SignUserKey(key, id); + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKeyGenParameterSpec.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKeyGenParameterSpec.java new file mode 100644 index 0000000..51749c8 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignMasterKeyGenParameterSpec.java @@ -0,0 +1,39 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9SignMasterKeyGenParameterSpec implements AlgorithmParameterSpec { + + private String id; + + protected SM9SignMasterKeyGenParameterSpec() { + + } + + public SM9SignMasterKeyGenParameterSpec(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9SignUserKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignUserKey.java new file mode 100644 index 0000000..815d338 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9SignUserKey.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; +import org.gmssl.Sm9SignKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9SignUserKey extends SM9UserKey{ + protected SM9SignUserKey(long sm9_key, String id) { + super(sm9_key, id); + this.privateKey = new SM9SignPrivateKey(); + } + + class SM9SignPrivateKey extends SM9PrivateKey { + + public void exportEncryptedPrivateKeyInfoPem(String pass, String file) { + if (sm9_key == 0) { + throw new GmSSLException("Key not initialized"); + } + if (GmSSLJNI.sm9_sign_key_info_encrypt_to_pem(sm9_key, pass, file) != 1) { + throw new GmSSLException(""); + } + } + + public void importEncryptedPrivateKeyInfoPem(String pass, String file) { + if (sm9_key != 0) { + GmSSLJNI.sm9_sign_key_free(sm9_key); + } + if ((sm9_key = GmSSLJNI.sm9_sign_key_info_decrypt_from_pem(pass, file)) == 0) { + throw new GmSSLException("Import key failure"); + } + } + + public byte[] sign(long sm9_sign_ctx) { + byte[] signature; + if ((signature = GmSSLJNI.sm9_sign_finish(sm9_sign_ctx, sm9_key)) == null) { + throw new GmSSLException(""); + } + return signature; + } + + public SM9SignUserKey getSecretKey() { + return SM9SignUserKey.this; + } + + } + +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9Signature.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9Signature.java new file mode 100644 index 0000000..704328e --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9Signature.java @@ -0,0 +1,160 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public class SM9Signature extends SignatureSpi { + + private long sm9_sign_ctx; + + private boolean inited; + + private boolean do_sign; + + private Key key; + + private String id; + + public SM9Signature() { + super(); + } + + @Override + protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { + if (!(publicKey instanceof SM9PublicKey)) { + throw new GmSSLException("Invalid publicKey type"); + } + this.key = publicKey; + init(); + initVerify(); + } + + @Override + protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { + if (!(privateKey instanceof SM9PrivateKey)) { + throw new GmSSLException("Invalid privateKey type"); + } + this.key = privateKey; + init(); + initSign(); + } + + @Override + protected void engineUpdate(byte b) throws SignatureException { + byte[] data= new byte[]{b}; + update(data, 0, data.length); + } + + @Override + protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { + update(b, off, len); + } + + @Override + protected byte[] engineSign() { + SM9PrivateKey sm9_private_key = (SM9PrivateKey)key; + byte[] signature = sm9_private_key.sign(sm9_sign_ctx); + this.inited = false; + return signature; + } + + @Override + protected boolean engineVerify(byte[] sigBytes) { + SM9PublicKey sm9_public_key = (SM9PublicKey)key; + boolean verify = sm9_public_key.verify(sigBytes,id,sm9_sign_ctx); + this.inited = false; + return verify; + } + + @Deprecated + @Override + protected void engineSetParameter(String param, Object value) throws InvalidParameterException { + + } + + @Deprecated + @Override + protected Object engineGetParameter(String param) throws InvalidParameterException { + return null; + } + + @Override + protected void engineSetParameter(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException { + this.id = ((SM9SignMasterKeyGenParameterSpec)params).getId(); + } + + private void init(){ + if ((this.sm9_sign_ctx = GmSSLJNI.sm9_sign_ctx_new()) == 0) { + throw new GmSSLException(""); + } + this.inited = true; + } + + private void initSign() { + if (GmSSLJNI.sm9_sign_init(this.sm9_sign_ctx) != 1) { + throw new GmSSLException(""); + } + this.do_sign = true; + } + + private void initVerify() { + if (GmSSLJNI.sm9_verify_init(this.sm9_sign_ctx) != 1) { + throw new GmSSLException(""); + } + this.do_sign = false; + } + + public void reset(boolean do_sign) { + if (do_sign == true) { + if (GmSSLJNI.sm9_sign_init(this.sm9_sign_ctx) != 1) { + throw new GmSSLException(""); + } + } else { + if (GmSSLJNI.sm9_verify_init(this.sm9_sign_ctx) != 1) { + throw new GmSSLException(""); + } + } + this.inited = true; + this.do_sign = do_sign; + } + + public void update(byte[] data, int offset, int len) { + if (this.inited == false) { + throw new GmSSLException(""); + } + if (data == null + || offset < 0 + || len < 0 + || offset + len <= 0 + || data.length < offset + len) { + throw new GmSSLException(""); + } + if (this.do_sign == true) { + if (GmSSLJNI.sm9_sign_update(this.sm9_sign_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } else { + if (GmSSLJNI.sm9_verify_update(this.sm9_sign_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } + } +} diff --git a/src/main/java/org/gmssl/crypto/asymmetric/SM9UserKey.java b/src/main/java/org/gmssl/crypto/asymmetric/SM9UserKey.java new file mode 100644 index 0000000..7e219b5 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/asymmetric/SM9UserKey.java @@ -0,0 +1,40 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.asymmetric; + +import java.security.spec.KeySpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/08/11 + * @description + * + */ +public abstract class SM9UserKey implements KeySpec { + + protected long sm9_key; + + protected String id; + + protected SM9PrivateKey privateKey; + + protected SM9UserKey(long key, String id) { + this.sm9_key = key; + this.id = id; + } + + public String getId() { + return this.id; + } + + public SM9PrivateKey getPrivateKey() { + return this.privateKey; + } +} diff --git a/src/main/java/org/gmssl/crypto/digest/SM3Digest.java b/src/main/java/org/gmssl/crypto/digest/SM3Digest.java new file mode 100644 index 0000000..15273e4 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/digest/SM3Digest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.digest; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import java.security.MessageDigestSpi; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/09/07 + * @description + * The SM3 cryptographic hash function can compute input data of arbitrary length into a fixed hash value of 32 bytes. + */ +public class SM3Digest extends MessageDigestSpi { + + private final static int DIGEST_SIZE = GmSSLJNI.SM3_DIGEST_SIZE; + + private long sm3_ctx = 0; + + public SM3Digest() { + init(); + } + + /** + * You can call the update method multiple times. After all the data has been input, finally call the digest method to obtain the SM3 hash value of the entire data. + * @param input the input byte to be processed. + */ + @Override + protected void engineUpdate(byte input) { + byte[] data = new byte[]{input}; + this.update(data, 0, data.length); + } + + @Override + protected void engineUpdate(byte[] input, int offset, int len) { + this.update(input, offset, len); + } + + @Override + protected byte[] engineDigest() { + return this.digest(); + } + + /** + * If you need to calculate different SM3 hash values for multiple sets of data, you can use the reset method to reset, + * and then call the update and digest methods again to compute the hash value of a new set of data. + */ + @Override + protected void engineReset() { + this.reset(); + } + + private void init(){ + if ((sm3_ctx = GmSSLJNI.sm3_ctx_new()) == 0) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_init(sm3_ctx) != 1) { + throw new GmSSLException(""); + } + } + + private void update(byte[] data, int offset, int len) { + if (data == null + || offset < 0 + || len < 0 + || offset + len <= 0 + || data.length < offset + len) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_update(sm3_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } + + private byte[] digest() { + byte[] dgst = new byte[DIGEST_SIZE]; + if (GmSSLJNI.sm3_finish(sm3_ctx, dgst) != 1) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_init(sm3_ctx) != 1) { + throw new GmSSLException(""); + } + return dgst; + } + + private void reset() { + if (GmSSLJNI.sm3_init(sm3_ctx) != 1) { + throw new GmSSLException(""); + } + } + +} diff --git a/src/main/java/org/gmssl/crypto/digest/SM3Hmac.java b/src/main/java/org/gmssl/crypto/digest/SM3Hmac.java new file mode 100644 index 0000000..11d6243 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/digest/SM3Hmac.java @@ -0,0 +1,144 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.digest; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.MacSpi; +import javax.crypto.SecretKey; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/09/07 + * @description + * HMAC-SM3 is a Message Authentication Code (MAC) algorithm based on the SM3 cryptographic hash algorithm. + * A MAC algorithm can be viewed as a keyed hash function, primarily used to protect messages from tampering. + * Both communicating parties need to agree on a key in advance, such as a 32-byte random byte sequence. + * The data sender uses this key to compute the MAC value of the message and appends the MAC value to the message. + * Upon receiving the message, the recipient uses the same key to compute the MAC value of the message and compares it with the MAC value attached to the sent message. + * If they match, it indicates that the message has not been tampered with; if they do not match, it indicates that the message has been altered. + */ +public class SM3Hmac extends MacSpi { + + public final static int MAC_SIZE = GmSSLJNI.SM3_HMAC_SIZE; + + private Key key; + + private long sm3_hmac_ctx = 0; + + public SM3Hmac() { + super(); + ctx(); + } + + @Override + protected int engineGetMacLength() { + return MAC_SIZE; + } + + /** + * The HMAC-SM3 algorithm can be seen as the SM3 algorithm with a key, so when creating an Sm3Hmac object, a key must be passed as an input parameter. + * Although HMAC-SM3 does not have any restrictions on key length in terms of the algorithm and implementation, for considerations of security and efficiency, the key length for the HMAC-SM3 algorithm is recommended to be 32 bytes (equivalent to the length of the SM3 hash value) and should not be less than 16 bytes. + * Using a key length longer than 32 bytes would increase computational overhead without enhancing security. + * @param key the (secret) key. + * @param params the algorithm parameters. + * + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + */ + @Override + protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException { + if (!(key instanceof SecretKey)) { + throw new GmSSLException("Invalid key for HMAC-SM3"); + } + this.key = key; + init(); + } + + /** + * You can call update multiple times and ultimately execute doFinal. The HMAC-SM3 output is a fixed 32 bytes, which is a binary message authentication code of length MAC_SIZE. + * @param input the input byte to be processed. + */ + @Override + protected void engineUpdate(byte input) { + byte[] data = new byte[]{input}; + this.update(data, 0, data.length); + } + + @Override + protected void engineUpdate(byte[] input, int offset, int len) { + this.update(input, offset, len); + } + + @Override + protected byte[] engineDoFinal() { + return generateMac(); + } + + @Override + protected void engineReset() { + this.reset(this.key); + } + + private void ctx(){ + if ((this.sm3_hmac_ctx = GmSSLJNI.sm3_hmac_ctx_new()) == 0) { + throw new GmSSLException(""); + } + } + + private void init() { + if (GmSSLJNI.sm3_hmac_init(this.sm3_hmac_ctx, key.getEncoded()) != 1) { + throw new GmSSLException(""); + } + } + + private void update(byte[] data, int offset, int len) { + if (data == null + || offset < 0 + || len < 0 + || offset + len <= 0 + || data.length < offset + len) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_hmac_update(this.sm3_hmac_ctx, data, offset, len) != 1) { + throw new GmSSLException(""); + } + } + + private void update(byte[] data) { + this.update(data, 0, data.length); + } + + private byte[] generateMac() { + byte[] mac = new byte[this.MAC_SIZE]; + if (GmSSLJNI.sm3_hmac_finish(this.sm3_hmac_ctx, mac) != 1) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_hmac_init(this.sm3_hmac_ctx, this.key.getEncoded()) != 1) { + throw new GmSSLException(""); + } + return mac; + } + + private void reset(Key key) { + if (key == null) { + throw new GmSSLException(""); + } + if (GmSSLJNI.sm3_hmac_init(this.sm3_hmac_ctx, key.getEncoded()) != 1) { + throw new GmSSLException(""); + } + this.key = key; + } +} diff --git a/src/main/java/org/gmssl/crypto/digest/SM3Pbkdf2.java b/src/main/java/org/gmssl/crypto/digest/SM3Pbkdf2.java new file mode 100644 index 0000000..1e29f1a --- /dev/null +++ b/src/main/java/org/gmssl/crypto/digest/SM3Pbkdf2.java @@ -0,0 +1,97 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.digest; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactorySpi; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.InvalidKeyException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/09/07 + * @description + * PBKDF2 is one of the secure and widely used PBKDF algorithm standards. The algorithm uses a hash function as the primary component to map passwords to keys. + * It employs a random and public salt value (Salt) to resist precomputation attacks, increases the difficulty of online cracking by adding multiple rounds of iterative computation, and supports variable derived key lengths. + */ +public class SM3Pbkdf2 extends SecretKeyFactorySpi { + + public final static int MAX_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_SALT_SIZE; + public final static int DEFAULT_SALT_SIZE = GmSSLJNI.SM3_PBKDF2_DEFAULT_SALT_SIZE; + public final static int MIN_ITER = GmSSLJNI.SM3_PBKDF2_MIN_ITER; + public final static int MAX_ITER = GmSSLJNI.SM3_PBKDF2_MAX_ITER; + public final static int MAX_KEY_SIZE = GmSSLJNI.SM3_PBKDF2_MAX_KEY_SIZE; + + public final static String ALGORITHM = "SM3Pbkdf2"; + + public SM3Pbkdf2() { + super(); + } + + /** + * + * @param keySpec PBEKeySpec the specification (key material) of the secret key + * pass is the user password used for deriving the key. + * salt is the value used to resist precomputation attacks. This value should be randomly generated (for example, using the Random class) and should have a certain length. + * The iter parameter represents the number of times the SM3 algorithm is called iteratively when deriving the key. A larger iter value increases the difficulty of brute-force attacks but also increases the computational overhead for users calling this function. + * The keylen parameter indicates the desired length of the derived key, which must not exceed the constant MAX_KEY_SIZE. + * @return + * @throws InvalidKeySpecException + */ + @Override + protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException { + if (!(keySpec instanceof PBEKeySpec)) { + throw new GmSSLException("Invalid KeySpec"); + } + PBEKeySpec pbeKeySpec = (PBEKeySpec) keySpec; + char[] password = pbeKeySpec.getPassword(); + byte[] salt = pbeKeySpec.getSalt(); + int iterations = pbeKeySpec.getIterationCount(); + int derivedKeyLength = pbeKeySpec.getKeyLength(); + byte[] key = deriveKey(new String(password), salt, iterations, derivedKeyLength); + return new SecretKeySpec(key, ALGORITHM); + } + + @Override + protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec) throws InvalidKeySpecException { + throw new GmSSLException("Not supported"); + } + + @Override + protected SecretKey engineTranslateKey(SecretKey key) throws InvalidKeyException { + throw new GmSSLException("Not supported"); + } + + private byte[] deriveKey(String pass, byte[] salt, int iter, int keylen) { + if (pass == null) { + throw new GmSSLException(""); + } + if (salt == null || salt.length > MAX_SALT_SIZE) { + throw new GmSSLException(""); + } + if (iter < MIN_ITER || iter > MAX_ITER) { + throw new GmSSLException(""); + } + if (keylen < 0 || keylen > MAX_KEY_SIZE) { + throw new GmSSLException(""); + } + byte[] key = GmSSLJNI.sm3_pbkdf2(pass, salt, iter, keylen); + if (key == null) { + throw new GmSSLException(""); + } + return key; + } +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4CBC.java b/src/main/java/org/gmssl/crypto/symmetric/SM4CBC.java new file mode 100644 index 0000000..5f2a4b9 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4CBC.java @@ -0,0 +1,201 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class SM4CBC extends SM4Engine { + + public final static int IV_SIZE = GmSSLJNI.SM4_BLOCK_SIZE; + + private long sm4_cbc_ctx; + + private byte[] iv; + + private boolean do_encrypt = true; + + private boolean inited; + + private int offset; + + private byte[] outputByteArray; + + protected SM4CBC() { + super(); + ctx(); + } + + @Override + protected byte[] engineGetIV() { + return iv; + } + + @Override + protected void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random){ + if (!(params instanceof IvParameterSpec)) { + throw new GmSSLException("need the IvParameterSpec parameter"); + } + this.iv = ((IvParameterSpec) params).getIV(); + this.do_encrypt = (opmode == Cipher.ENCRYPT_MODE); + init(key.getEncoded(), iv, do_encrypt); + + outputByteArray = new byte[BLOCK_SIZE]; + } + + @Override + protected byte[] processUpdate(byte[] input, int inputOffset, int inputLen) { + int newOutputLength = BLOCK_SIZE + offset + inputLen; + if (outputByteArray.length < newOutputLength) { + int newSize = Math.max(outputByteArray.length * 3 / 2 + BLOCK_SIZE, newOutputLength); + outputByteArray = Arrays.copyOf(outputByteArray, newSize); + } + + int outLen = processUpdate(input, inputOffset, inputLen, outputByteArray, offset); + return Arrays.copyOfRange(outputByteArray,offset-outLen,offset); + } + + @Override + protected int processUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset){ + int outLen = update(input, inputOffset, inputLen, output, outputOffset); + this.offset+=outLen; + return outLen; + } + + @Override + protected byte[] processBlock(byte[] input, int inputOffset, int inputLen) { + if(null!=input){ + processUpdate(input, inputOffset, inputLen); + } + int outLen = doFinal(outputByteArray, this.offset); + outLen = outLen + this.offset; + this.offset = 0; + outputByteArray = Arrays.copyOfRange(outputByteArray,0,outLen); + return outputByteArray; + } + + @Override + protected int processBlock(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { + int outLen = 0; + if(null!=input){ + outLen=this.processUpdate(input, inputOffset, inputLen, output, outputOffset); + } + outLen += doFinal(output, this.offset); + this.offset = 0; + return outLen; + } + + private void ctx() { + if ((this.sm4_cbc_ctx = GmSSLJNI.sm4_cbc_ctx_new()) == 0) { + throw new GmSSLException(""); + } + this.inited = false; + } + + private void init(byte[] key, byte[] iv, boolean do_encrypt) { + if (key == null + || key.length != this.KEY_SIZE + || iv == null + || iv.length != this.IV_SIZE) { + throw new GmSSLException(""); + } + + if (do_encrypt) { + if (GmSSLJNI.sm4_cbc_encrypt_init(this.sm4_cbc_ctx, key, iv) != 1) { + throw new GmSSLException(""); + } + } else { + if (GmSSLJNI.sm4_cbc_decrypt_init(this.sm4_cbc_ctx, key, iv) != 1) { + throw new GmSSLException(""); + } + } + + this.do_encrypt = do_encrypt; + this.inited = true; + } + + private int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset) { + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (in == null + || in_offset < 0 + || inlen < 0 + || in_offset + inlen <= 0 + || in.length < in_offset + inlen) { + throw new GmSSLException(""); + } + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if (this.do_encrypt) { + if ((outlen = GmSSLJNI.sm4_cbc_encrypt_update(this.sm4_cbc_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } else { + if ((outlen = GmSSLJNI.sm4_cbc_decrypt_update(this.sm4_cbc_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } + + return outlen; + } + + private int doFinal(byte[] out, int out_offset) { + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if (this.do_encrypt) { + if ((outlen = GmSSLJNI.sm4_cbc_encrypt_finish(this.sm4_cbc_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } else { + if ((outlen = GmSSLJNI.sm4_cbc_decrypt_finish(this.sm4_cbc_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } + + this.inited = false; + return outlen; + } + +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4CTR.java b/src/main/java/org/gmssl/crypto/symmetric/SM4CTR.java new file mode 100644 index 0000000..01732f3 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4CTR.java @@ -0,0 +1,177 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.IvParameterSpec; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class SM4CTR extends SM4Engine { + + public final static int IV_SIZE = GmSSLJNI.SM4_BLOCK_SIZE; + + private byte[] iv; + + private long sm4_ctr_ctx = 0; + private boolean inited = false; + + private int offset; + + private byte[] outputByteArray; + + protected SM4CTR() { + super(); + ctx(); + } + + @Override + protected void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) { + if (!(params instanceof IvParameterSpec)) { + throw new GmSSLException("need the IvParameterSpec parameter"); + } + this.iv = ((IvParameterSpec) params).getIV(); + init(key.getEncoded(), iv); + + outputByteArray = new byte[BLOCK_SIZE]; + } + + @Override + protected byte[] engineGetIV() { + return iv; + } + + @Override + protected byte[] processUpdate(byte[] input, int inputOffset, int inputLen) { + int newOutputLength = BLOCK_SIZE + offset + inputLen; + if (outputByteArray.length < newOutputLength) { + int newSize = Math.max(outputByteArray.length * 3 / 2 + BLOCK_SIZE, newOutputLength); + outputByteArray = Arrays.copyOf(outputByteArray, newSize); + } + + int outLen = processUpdate(input, inputOffset, inputLen, outputByteArray, offset); + return Arrays.copyOfRange(outputByteArray,offset-outLen,offset); + } + + @Override + protected int processUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { + int outLen = update(input, inputOffset, inputLen, output, outputOffset); + this.offset += outLen; + return outLen; + } + + @Override + protected byte[] processBlock(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + if(null!=input){ + processUpdate(input, inputOffset, inputLen); + } + int outLen = doFinal(outputByteArray, this.offset); + outLen = outLen + this.offset; + this.offset = 0; + outputByteArray = Arrays.copyOfRange(outputByteArray,0,outLen); + return outputByteArray; + } + + @Override + protected int processBlock(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + int outLen = 0; + if(null!=input){ + outLen=this.processUpdate(input, inputOffset, inputLen, output, outputOffset); + } + outLen += doFinal(output, this.offset); + this.offset = 0; + return outLen; + } + + public void ctx(){ + if ((this.sm4_ctr_ctx = GmSSLJNI.sm4_ctr_ctx_new()) == 0) { + throw new GmSSLException(""); + } + this.inited = false; + } + + public void init(byte[] key, byte[] iv) { + if (key == null + || key.length != this.KEY_SIZE + || iv == null + || iv.length != this.IV_SIZE) { + throw new GmSSLException(""); + } + + if (GmSSLJNI.sm4_ctr_encrypt_init(this.sm4_ctr_ctx, key, iv) != 1) { + throw new GmSSLException(""); + } + + this.inited = true; + } + + public int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset) { + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (in == null + || in_offset < 0 + || inlen < 0 + || in_offset + inlen <= 0 + || in.length < in_offset + inlen) { + throw new GmSSLException(""); + } + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if ((outlen = GmSSLJNI.sm4_ctr_encrypt_update(this.sm4_ctr_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + return outlen; + } + + public int doFinal(byte[] out, int out_offset){ + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if ((outlen = GmSSLJNI.sm4_ctr_encrypt_finish(this.sm4_ctr_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + this.inited = false; + return outlen; + } +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4Cipher.java b/src/main/java/org/gmssl/crypto/symmetric/SM4Cipher.java new file mode 100644 index 0000000..2902c4c --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4Cipher.java @@ -0,0 +1,110 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLJNI; + +import javax.crypto.*; +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * CBC、CTR、ECB、GCM + */ +public class SM4Cipher extends CipherSpi { + + public static final int KEY_SIZE = GmSSLJNI.SM4_KEY_SIZE; + + public static final int BLOCK_SIZE = GmSSLJNI.SM4_BLOCK_SIZE; + + private SM4Engine sm4Engine; + + public SM4Cipher() { + super(); + } + + @Override + protected void engineSetMode(String mode) throws NoSuchAlgorithmException { + this.sm4Engine = SM4CipherFactory.createCipher(mode); + } + + @Override + protected void engineSetPadding(String padding) throws NoSuchPaddingException { + SM4CipherFactory.setPaddingScheme(sm4Engine, padding); + } + + @Override + protected int engineGetBlockSize() { + return SM4Engine.BLOCK_SIZE; + } + + @Override + protected int engineGetOutputSize(int inputLen) { + return 0; + } + + @Override + protected byte[] engineGetIV() { + return sm4Engine.engineGetIV(); + } + + @Override + protected AlgorithmParameters engineGetParameters() { + return null; + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + sm4Engine.init(opmode,key,random); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + sm4Engine.init(opmode, key, params, random); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + + } + + @Override + protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { + byte[] result = sm4Engine.processUpdate(input,inputOffset,inputLen); + return result; + } + + @Override + protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { + int outLen = sm4Engine.processUpdate(input, inputOffset, inputLen, output, outputOffset); + return outLen; + } + + @Override + protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + byte[] result = sm4Engine.processBlock(input, inputOffset, inputLen); + return result; + } + + @Override + protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + int outLen = sm4Engine.processBlock(input, inputOffset, inputLen, output, outputOffset); + return outLen; + } + + @Override + protected void engineUpdateAAD(byte[] src, int offset, int len) { + sm4Engine.processUpdateAAD(src, offset, len); + } + +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4CipherFactory.java b/src/main/java/org/gmssl/crypto/symmetric/SM4CipherFactory.java new file mode 100644 index 0000000..cde6769 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4CipherFactory.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.crypto.CipherPaddingEnum; +import org.gmssl.crypto.PKCS7PaddingScheme; + +import java.security.NoSuchAlgorithmException; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class SM4CipherFactory { + + /** + * Create an SM4 encryption and decryption engine that supports ECB, CBC, CTR, and GCM modes. + * @param mode + * @return + */ + public static SM4Engine createCipher(String mode){ + SM4Engine cipher; + try { + switch (mode.toUpperCase()) { + case "ECB": + cipher = new SM4ECB(); + break; + case "CBC": + cipher = new SM4CBC(); + break; + case "CTR": + cipher = new SM4CTR(); + break; + case "GCM": + cipher = new SM4GCM(); + break; + default: + throw new NoSuchAlgorithmException("Unsupported mode: " + mode); + } + }catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return cipher; + } + + /** + * Currently, only the PKCS7Padding padding mode for ECB algorithm mode is set. Other algorithms (SM4/CBC/PKCS5Padding, SM4/CTR/NoPadding, SM4/GCM/NoPadding) have their default padding implemented. + * @param engine + * @param padding + */ + public static void setPaddingScheme(SM4Engine engine, String padding) { + if(CipherPaddingEnum.PKCS7Padding.name().equals(padding)){ + engine.paddingScheme=new PKCS7PaddingScheme(); + } + } + +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4ECB.java b/src/main/java/org/gmssl/crypto/symmetric/SM4ECB.java new file mode 100644 index 0000000..27352c5 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4ECB.java @@ -0,0 +1,181 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; +import org.gmssl.Sm4; + +import javax.crypto.*; +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class SM4ECB extends SM4Engine { + + private Key key; + private long sm4_key; + + private boolean do_encrypt; + + private ByteBuffer buffer; + + @Override + protected void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + if (!(key instanceof SecretKey)) { + throw new GmSSLException("Invalid KeySpec"); + } + this.do_encrypt = (opmode == Cipher.ENCRYPT_MODE); + this.key = key; + // 初始化缓冲区 + this.buffer = ByteBuffer.allocate(2048); + init(); + } + + @Override + protected void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected byte[] engineGetIV() { + return null; + } + + /** + * Mainly used for caching data; it will not immediately generate encryption or decryption results + * @param input + * @param inputOffset + * @param inputLen + * @return null + * Return a non-actual value; actual encryption or decryption operations are performed in processBlock + */ + @Override + protected byte[] processUpdate(byte[] input, int inputOffset, int inputLen) { + putBytes(input, inputOffset, inputLen); + return null; + } + + @Override + protected byte[] processBlock(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + if(null!=input){ + putBytes(input, inputOffset, inputLen); + } + byte[] data = new byte[buffer.position()]; + buffer.flip(); + buffer.get(data); + + byte[] outPutByteArray = new byte[buffer.position()]; + if(do_encrypt){ + data = this.paddingScheme.pad(data,this.BLOCK_SIZE); + outPutByteArray = new byte[data.length]; + for (int i = 0; i < data.length; i += this.BLOCK_SIZE) { + encrypt(data,i,outPutByteArray,i); + } + }else{ + for (int i = 0; i < data.length; i += this.BLOCK_SIZE) { + encrypt(data,i,outPutByteArray,i); + } + outPutByteArray=this.paddingScheme.unpad(outPutByteArray); + } + + buffer.clear(); + return outPutByteArray; + } + + /** + * Mainly used for caching data; it will not immediately generate encryption or decryption results + * @param input + * @param inputOffset + * @param inputLen + * @param output + * @param outputOffset + * @return 0 + * Return a non-actual value; actual encryption or decryption operations are performed in processBlock + */ + @Override + protected int processUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { + putBytes(input, inputOffset, inputLen); + return 0; + } + + /** + * + * @param input + * @param inputOffset + * @param inputLen + * @param output + * @param outputOffset + * @return actual encryption or decryption bytes length,not the whole length of the output data + * + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + @Override + protected int processBlock(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalBlockSizeException, BadPaddingException { + byte[] outPutByteArray = processBlock(input, inputOffset, inputLen); + System.arraycopy(outPutByteArray, 0,output, outputOffset, outPutByteArray.length); + return outPutByteArray.length; + } + + private void putBytes(byte[] input, int inputOffset, int inputLen){ + if(buffer.remaining() in.length) { + throw new GmSSLException(""); + } + if (out == null + || out_offset < 0 + || out_offset + this.BLOCK_SIZE <= 0 + || out_offset + this.BLOCK_SIZE > in.length) { + throw new GmSSLException(""); + } + + if (GmSSLJNI.sm4_encrypt(sm4_key, in, in_offset, out, out_offset) != 1) { + throw new GmSSLException(""); + } + } +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4Engine.java b/src/main/java/org/gmssl/crypto/symmetric/SM4Engine.java new file mode 100644 index 0000000..52bfe1c --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4Engine.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLJNI; +import org.gmssl.crypto.PaddingScheme; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.ShortBufferException; +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public abstract class SM4Engine { + + public static final int KEY_SIZE = SM4Cipher.KEY_SIZE; + + public static final int BLOCK_SIZE = SM4Cipher.BLOCK_SIZE; + + protected PaddingScheme paddingScheme; + + protected abstract void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException; + + protected abstract void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random); + + protected abstract byte[] engineGetIV(); + + protected abstract byte[] processUpdate(byte[] input, int inputOffset, int inputLen); + + protected abstract int processUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException; + + protected abstract int processBlock(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException; + + protected abstract byte[] processBlock(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException; + protected void processUpdateAAD(byte[] src, int offset, int len){}; + +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/SM4GCM.java b/src/main/java/org/gmssl/crypto/symmetric/SM4GCM.java new file mode 100644 index 0000000..a10f8b4 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/SM4GCM.java @@ -0,0 +1,231 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.GCMParameterSpec; +import java.nio.ByteBuffer; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class SM4GCM extends SM4Engine { + + public final static int MIN_IV_SIZE = GmSSLJNI.SM4_GCM_MIN_IV_SIZE; + public final static int MAX_IV_SIZE = GmSSLJNI.SM4_GCM_MAX_IV_SIZE; + public final static int DEFAULT_IV_SIZE = GmSSLJNI.SM4_GCM_DEFAULT_IV_SIZE; + public final static int MIN_TAG_SIZE = 8; + public final static int MAX_TAG_SIZE = GmSSLJNI.SM4_GCM_MAX_TAG_SIZE; + + private long sm4_gcm_ctx = 0; + private boolean do_encrypt = true; + private boolean inited = false; + + private byte[] iv; + + private ByteBuffer aad; + + private Key key; + + private int tLen; + + private int offset; + + private byte[] outputByteArray; + + protected SM4GCM(){ + super(); + ctx(); + } + + @Override + protected void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) { + if (!(params instanceof GCMParameterSpec)) { + throw new GmSSLException("need the GCMParameterSpec parameter"); + } + this.key = key; + this.iv = ((GCMParameterSpec) params).getIV(); + this.tLen = ((GCMParameterSpec) params).getTLen(); + this.do_encrypt = (opmode == Cipher.ENCRYPT_MODE); + + outputByteArray = new byte[BLOCK_SIZE+tLen]; + aad=ByteBuffer.allocate(BLOCK_SIZE+tLen); + } + + @Override + protected byte[] engineGetIV() { + return iv; + } + + @Override + protected byte[] processUpdate(byte[] input, int inputOffset, int inputLen) { + int newOutputLength = BLOCK_SIZE + offset + tLen + inputLen; + if (outputByteArray.length < newOutputLength) { + int newSize = Math.max(outputByteArray.length * 3 / 2 + BLOCK_SIZE + tLen, newOutputLength); + outputByteArray = Arrays.copyOf(outputByteArray, newSize); + } + + int outLen = processUpdate(input, inputOffset, inputLen, outputByteArray, offset); + return Arrays.copyOfRange(outputByteArray,offset-outLen,offset); + } + + @Override + protected int processUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { + int outLen = update(input, inputOffset, inputLen, output, outputOffset); + this.offset+=outLen; + return outLen; + } + + @Override + protected byte[] processBlock(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + if(null!=input){ + processUpdate(input, inputOffset, inputLen); + } + int outLen = doFinal(outputByteArray, this.offset); + outLen = outLen + this.offset; + this.offset = 0; + outputByteArray = Arrays.copyOfRange(outputByteArray,0,outLen); + return outputByteArray; + } + + @Override + protected int processBlock(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + int outLen = 0; + if(null!=input){ + outLen=this.processUpdate(input, inputOffset, inputLen, output, outputOffset); + } + outLen += doFinal(output, this.offset); + this.offset = 0; + return outLen; + } + + @Override + protected void processUpdateAAD(byte[] src, int offset, int len) { + if(aad.remaining() this.MAX_IV_SIZE + || taglen < this.MIN_TAG_SIZE + || taglen > this.MAX_TAG_SIZE) { + throw new GmSSLException(""); + } + + if (do_encrypt == true) { + if (GmSSLJNI.sm4_gcm_encrypt_init(this.sm4_gcm_ctx, key, iv, aad, taglen) != 1) { + throw new GmSSLException(""); + } + } else { + if (GmSSLJNI.sm4_gcm_decrypt_init(this.sm4_gcm_ctx, key, iv, aad, taglen) != 1) { + throw new GmSSLException(""); + } + } + + this.do_encrypt = do_encrypt; + this.inited = true; + } + + private int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset){ + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (in == null + || in_offset < 0 + || inlen < 0 + || in_offset + inlen <= 0 + || in.length < in_offset + inlen) { + throw new GmSSLException(""); + } + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if (this.do_encrypt) { + if ((outlen = GmSSLJNI.sm4_gcm_encrypt_update(this.sm4_gcm_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } else { + if ((outlen = GmSSLJNI.sm4_gcm_decrypt_update(this.sm4_gcm_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } + + return outlen; + } + + private int doFinal(byte[] out, int out_offset) { + + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if (this.do_encrypt) { + if ((outlen = GmSSLJNI.sm4_gcm_encrypt_finish(this.sm4_gcm_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } else { + if ((outlen = GmSSLJNI.sm4_gcm_decrypt_finish(this.sm4_gcm_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + } + + this.inited = false; + return outlen; + } +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/ZucCipher.java b/src/main/java/org/gmssl/crypto/symmetric/ZucCipher.java new file mode 100644 index 0000000..5f43828 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/ZucCipher.java @@ -0,0 +1,221 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLException; +import org.gmssl.GmSSLJNI; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * The Zu Chongzhi Cipher Algorithm (ZU Cipher, ZUC) is a stream cipher with both the key and IV lengths set to 16 bytes. + * As a stream cipher, ZUC can encrypt input data of variable length, and the ciphertext output has the same length as the input data. + * This makes it suitable for applications that do not allow ciphertext expansion. + * In terms of security, it is not recommended to use the ZUC algorithm to encrypt large amounts of data (such as GB or TB levels) with a single key and IV, to avoid a decrease in security when the stream cipher produces extremely long outputs. + */ +public class ZucCipher extends CipherSpi { + + public final static int IV_SIZE = GmSSLJNI.ZUC_IV_SIZE; + public final static int BLOCK_SIZE = 4; + + private long zuc_ctx; + private boolean inited; + + private byte[] iv; + + private int offset; + + private byte[] outputByteArray; + + public ZucCipher(){ + ctx(); + } + + /** + * As a stream cipher, ZUC generates a pseudo-random sequence for each encryption or decryption operation, which is then XORed bit-by-bit with the plaintext to achieve encryption or decryption. + * Therefore, ZUC does not require the use of specific modes like block ciphers; instead, it directly generates the encryption key stream and performs the encryption operation bit-by-bit. + * @param mode the cipher mode + * + */ + @Override + protected void engineSetMode(String mode){ + } + + /** + * ZUC does not require a padding mode and can directly handle plaintext of any length. + * @param padding the padding mechanism + * + */ + @Override + protected void engineSetPadding(String padding){ + } + + @Override + protected int engineGetBlockSize() { + return BLOCK_SIZE; + } + + @Override + protected int engineGetOutputSize(int inputLen) { + return 0; + } + + @Override + protected byte[] engineGetIV() { + return iv; + } + + @Override + protected AlgorithmParameters engineGetParameters() { + return null; + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { + if (params instanceof IvParameterSpec) { + IvParameterSpec ivSpec = (IvParameterSpec) params; + this.iv = ivSpec.getIV(); + } else { + throw new InvalidAlgorithmParameterException("Unsupported parameters"); + } + init(key.getEncoded(), iv); + + outputByteArray = new byte[BLOCK_SIZE]; + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + throw new GmSSLException("Initialization method not supported!"); + } + + @Override + protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { + int newOutputLength = BLOCK_SIZE + offset + inputLen; + if (outputByteArray.length < newOutputLength) { + int newSize = Math.max(outputByteArray.length * 3 / 2 + BLOCK_SIZE, newOutputLength); + outputByteArray = Arrays.copyOf(outputByteArray, newSize); + } + + int outLen = engineUpdate(input, inputOffset, inputLen, outputByteArray, offset); + return Arrays.copyOfRange(outputByteArray,offset-outLen,offset); + } + + @Override + protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset){ + int outLen = update(input, inputOffset, inputLen, output, outputOffset); + this.offset+=outLen; + return outLen; + } + + @Override + protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { + if(null!=input){ + engineUpdate(input, inputOffset, inputLen); + } + int outLen = doFinal(outputByteArray, this.offset); + outLen = outLen + this.offset; + this.offset = 0; + outputByteArray = Arrays.copyOfRange(outputByteArray,0,outLen); + return outputByteArray; + } + + @Override + protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + int outLen = 0; + if(null!=input){ + outLen=this.engineUpdate(input, inputOffset, inputLen, output, outputOffset); + } + outLen += doFinal(output, this.offset); + this.offset = 0; + return outLen; + } + + private void ctx(){ + if ((this.zuc_ctx = GmSSLJNI.zuc_ctx_new()) == 0) { + throw new GmSSLException(""); + } + this.inited = false; + } + + private void init(byte[] key, byte[] iv){ + if (key == null + || key.length != ZucKey.KEY_SIZE + || iv == null + || iv.length != this.IV_SIZE) { + throw new GmSSLException(""); + } + + if (GmSSLJNI.zuc_encrypt_init(this.zuc_ctx, key, iv) != 1) { + throw new GmSSLException(""); + } + + this.inited = true; + } + + private int update(byte[] in, int in_offset, int inlen, byte[] out, int out_offset) { + + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (in == null + || in_offset < 0 + || inlen < 0 + || in_offset + inlen <= 0 + || in.length < in_offset + inlen) { + throw new GmSSLException(""); + } + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if ((outlen = GmSSLJNI.zuc_encrypt_update(this.zuc_ctx, in, in_offset, inlen, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + + return outlen; + } + + private int doFinal(byte[] out, int out_offset) { + + if (this.inited == false) { + throw new GmSSLException(""); + } + + if (out == null + || out_offset < 0 + || out.length < out_offset) { + throw new GmSSLException(""); + } + + int outlen; + if ((outlen = GmSSLJNI.zuc_encrypt_finish(this.zuc_ctx, out, out_offset)) < 0) { + throw new GmSSLException(""); + } + + this.inited = false; + return outlen; + } +} diff --git a/src/main/java/org/gmssl/crypto/symmetric/ZucKey.java b/src/main/java/org/gmssl/crypto/symmetric/ZucKey.java new file mode 100644 index 0000000..f305f91 --- /dev/null +++ b/src/main/java/org/gmssl/crypto/symmetric/ZucKey.java @@ -0,0 +1,46 @@ +/* + * Copyright 2014-2024 The GmSSL Project. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package org.gmssl.crypto.symmetric; + +import org.gmssl.GmSSLJNI; + +import javax.crypto.SecretKey; + +/** + * @author yongfeili + * @email 290836576@qq.com + * @date 2024/07/27 + * @description + * + */ +public class ZucKey implements SecretKey { + + public final static int KEY_SIZE = GmSSLJNI.ZUC_KEY_SIZE; + + private byte[] key; + + public ZucKey(byte[] key){ + this.key = key; + } + + @Override + public String getAlgorithm() { + return "ZUC"; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return key; + } +} diff --git a/src/main/resources/lib/libgmssljni.dll b/src/main/resources/lib/libgmssljni.dll new file mode 100644 index 0000000..0d4e190 Binary files /dev/null and b/src/main/resources/lib/libgmssljni.dll differ diff --git a/src/test/java/org/gmssl/JceTest.java b/src/test/java/org/gmssl/JceTest.java new file mode 100644 index 0000000..39f2f35 --- /dev/null +++ b/src/test/java/org/gmssl/JceTest.java @@ -0,0 +1,406 @@ +package org.gmssl; + +import org.gmssl.crypto.asymmetric.*; +import org.gmssl.crypto.digest.SM3Hmac; +import org.gmssl.crypto.digest.SM3Pbkdf2; +import org.gmssl.crypto.symmetric.*; +import org.junit.Before; +import org.junit.Test; + +import javax.crypto.*; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.math.BigInteger; +import java.security.*; +import java.util.Arrays; + +/** + * @author yongfeili + * @date 2024/8/2 + * @description you must need to use openjdk! + * https://jdk.java.net/archive/ + * https://stackoverflow.com/questions/1756801/how-to-sign-a-custom-jce-security-provider + */ +public class JceTest { + + @Before + public void beforeTest(){ + Security.addProvider(new org.gmssl.crypto.GmSSLProvider()); + } + + @Test + public void SM2_test() throws Exception{ + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("SM2", "GmSSL"); + keyPairGen.initialize(256); + KeyPair keyPair = keyPairGen.generateKeyPair(); + byte[] pub= keyPair.getPublic().getEncoded(); + System.out.println(byteToHex(pub)); + byte[] pri= keyPair.getPrivate().getEncoded(); + // export private key + SM2PrivateKey SM2PrivateKey= (SM2PrivateKey)keyPair.getPrivate(); + SM2PrivateKey.exportEncryptedPrivateKeyInfoPem("123456", "D:\\private.key.pem"); + System.out.println(byteToHex(pri)); + + //Test "Z-value" hash + SM2PublicKey sm2PublicKey = new SM2PublicKey(pub); + byte[] zHash = sm2PublicKey.computeZ("Hello, GmSSL"); + System.out.println("zHash:"+byteToHex(zHash)); + + Cipher cipher = Cipher.getInstance("SM2", "GmSSL"); + // Test encryption + cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + byte[] plaintext = "Hello, GmSSL".getBytes(); + byte[] ciphertext = cipher.doFinal(plaintext); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // Test decryption + cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + byte[] decrypted = cipher.doFinal(ciphertext); + System.out.println("Decrypted: " + new String(decrypted)); + + Signature signature = Signature.getInstance("SM2", "GmSSL"); + // Test signature + signature.initSign(keyPair.getPrivate()); + byte[] signatureText = "Hello, GmSSL".getBytes(); + signature.update(signatureText); + byte[] signatureByte = signature.sign(); + System.out.println("Signature:"+byteToHex(signatureByte)); + // Test signature verification + signature.initVerify(keyPair.getPublic()); + signature.update(signatureText); + boolean signatureResult = signature.verify(signatureByte); + System.out.println("SignatureResult:"+signatureResult); + + + Signature signatureImport = Signature.getInstance("SM2", "GmSSL"); + // import private key + String privateKeyInfoHex="308193020100301306072a8648ce3d020106082a811ccf5501822d0479307702010104207fef3e258348873c47117c15093266e9dad99e131f1778e53d362b2b70649f85a00a06082a811ccf5501822da14403420004f94c0abb6cd00c6f0918cb9c54162213501d5cc278f5d3fcf63886f4e1dc6322b1b110e33a25216f258c4cce5fd52ab320d3b086ee5390f7387218c92578c3ab"; + byte[] privateKeyInfo = hexToByte(privateKeyInfoHex); + signatureImport.initSign(new SM2PrivateKey(privateKeyInfo)); + signatureImport.update(signatureText); + byte[] signatureByteImport = signatureImport.sign(); + System.out.println("Signature:"+byteToHex(signatureByteImport)); + // export public key + String publicKeyInfoHex = "3059301306072a8648ce3d020106082a811ccf5501822d03420004f94c0abb6cd00c6f0918cb9c54162213501d5cc278f5d3fcf63886f4e1dc6322b1b110e33a25216f258c4cce5fd52ab320d3b086ee5390f7387218c92578c3ab"; + byte[] publicKeyInfo = hexToByte(publicKeyInfoHex); + signatureImport.initVerify(new SM2PublicKey(publicKeyInfo)); + signatureImport.update(signatureText); + boolean signatureResultImport = signatureImport.verify(signatureByteImport); + System.out.println("SignatureResult:"+signatureResultImport); + } + + @Test + public void sm2_certificate_test() throws Exception{ + SM2Certificate sm2Cert = new SM2Certificate(); + //sm2Cert.importPem("D:\\cert.pem"); + //System.out.println("NotAfter:"+sm2Cert.getNotAfter()); + } + + @Test + public void SM3_test() throws Exception{ + String text="Hello, GmSSL"; + // hash + MessageDigest sm3Digest = MessageDigest.getInstance("SM3","GmSSL"); + sm3Digest.update("abc".getBytes()); + sm3Digest.reset(); + sm3Digest.update(text.getBytes()); + byte[] digest = sm3Digest.digest(); + System.out.println("digest:"+byteToHex(digest)); + + //HMAC Message Authentication Code Algorithm Based on SM3 + Mac hmac = Mac.getInstance("SM3", "GmSSL"); + hmac.init(new SecretKeySpec(new Random().randBytes(SM3Hmac.MAC_SIZE), "SM3")); + hmac.update(text.getBytes()); + byte[] hmacFinal = hmac.doFinal(); + System.out.println("hmac:"+byteToHex(hmacFinal)); + + //Password-Based Key Derivation Function PBKDF2 + char[] password = "P@ssw0rd".toCharArray(); + byte[] salt = new Random().randBytes(SM3Pbkdf2.DEFAULT_SALT_SIZE); + int iterations = SM3Pbkdf2.MIN_ITER * 2; + int keyLength = SM3Pbkdf2.MAX_KEY_SIZE; + PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength); + SecretKeyFactory skf = SecretKeyFactory.getInstance("SM3Pbkdf2"); + SecretKey key = skf.generateSecret(spec); + byte[] keyBytes = key.getEncoded(); + System.out.println("DerivedKey: " + byteToHex(keyBytes)); + } + + @Test + public void SM4_ECB_test() throws Exception{ + String text="Hello, GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + // encryption + Cipher sm4Cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "GmSSL"); + SecretKeySpec sm4Key = new SecretKeySpec(secureRandom.generateSeed(SM4ECB.KEY_SIZE), "SM4"); + sm4Cipher.init(Cipher.ENCRYPT_MODE, sm4Key); + sm4Cipher.update(text.getBytes()); + sm4Cipher.update("cipher.".getBytes(),0, 6); + byte[] ciphertext = sm4Cipher.doFinal(); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // decryption + sm4Cipher.init(Cipher.DECRYPT_MODE, sm4Key); + byte[] plaintext = sm4Cipher.doFinal(ciphertext); + System.out.println("plaintext: " + new String(plaintext)); + } + + @Test + public void SM4_CBC_test1() throws Exception{ + String text="Hello,GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + byte[] randomBytes = new byte[32]; + secureRandom.nextBytes(randomBytes); + System.out.println("Generated Random Bytes: " + byteToHex(randomBytes)); + // encryption + Cipher sm4cbcCipher = Cipher.getInstance("SM4/CBC/PKCS5Padding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4CBC.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4CBC.IV_SIZE); + sm4cbcCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + sm4cbcCipher.update(text.getBytes()); + sm4cbcCipher.update(text.getBytes()); + sm4cbcCipher.update(text.getBytes()); + byte[] ciphertext = sm4cbcCipher.doFinal(); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // decryption + sm4cbcCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + sm4cbcCipher.update(ciphertext); + byte[] plaintext2 = sm4cbcCipher.doFinal(); + String plaintextStr=new String(plaintext2); + System.out.println("plaintext: " + plaintextStr); + } + + @Test + public void SM4_CBC_test2() throws Exception{ + String text="Hello,GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + byte[] randomBytes = new byte[32]; + secureRandom.nextBytes(randomBytes); + System.out.println("Generated Random Bytes: " + byteToHex(randomBytes)); + // encryption + Cipher sm4cbcCipher = Cipher.getInstance("SM4/CBC/PKCS5Padding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4CBC.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4CBC.IV_SIZE); + sm4cbcCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + byte[] ciphertext = new byte[100]; + int cipherlen = sm4cbcCipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, 0); + cipherlen += sm4cbcCipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += sm4cbcCipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += sm4cbcCipher.doFinal(text.getBytes(), 0, text.getBytes().length,ciphertext, cipherlen); + byte[] ciphertext1 = Arrays.copyOfRange(ciphertext,0,cipherlen); + System.out.println("Ciphertext: " + byteToHex(ciphertext1)); + // decryption + byte[] plaintext = new byte[ciphertext1.length + SM4CBC.BLOCK_SIZE]; + sm4cbcCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + int plainLen = sm4cbcCipher.doFinal(ciphertext1, 0,ciphertext1.length, plaintext,0); + byte[] plaintext1 =Arrays.copyOfRange(plaintext,0,plainLen); + String plaintextStr=new String(plaintext1); + System.out.println("plaintext: " + plaintextStr); + } + + @Test + public void SM4_CTR_test1() throws Exception{ + String text="Hello, GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + Cipher sm4Cipher = Cipher.getInstance("SM4/CTR/NoPadding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4CTR.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4CTR.IV_SIZE); + // encryption + sm4Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + byte[] ciphertext = new byte[100]; + int cipherlen = sm4Cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, 0); + cipherlen += sm4Cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += sm4Cipher.doFinal(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + byte[] ciphertext1 = Arrays.copyOfRange(ciphertext,0,cipherlen); + System.out.println("Ciphertext: " + byteToHex(ciphertext1)); + // decryption + byte[] plaintext = new byte[ciphertext1.length+SM4CTR.BLOCK_SIZE]; + sm4Cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + int plainLen = sm4Cipher.doFinal(ciphertext1, 0, ciphertext1.length, plaintext, 0); + byte[] plaintext1 = Arrays.copyOfRange(plaintext,0,plainLen); + System.out.println("plaintext: " + new String(plaintext1)); + } + + @Test + public void SM4_CTR_test2() throws Exception{ + String text="Hello, GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + Cipher sm4Cipher = Cipher.getInstance("SM4/CTR/NoPadding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4CTR.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4CTR.IV_SIZE); + // encryption + sm4Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + sm4Cipher.update(text.getBytes()); + sm4Cipher.update(text.getBytes()); + sm4Cipher.update(text.getBytes()); + byte[] ciphertext = sm4Cipher.doFinal(); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // decryption + sm4Cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new IvParameterSpec(iv)); + sm4Cipher.update(ciphertext); + byte[] plaintext1=sm4Cipher.doFinal(); + System.out.println("plaintext: " + new String(plaintext1)); + } + + @Test + public void SM4_GCM_test1() throws Exception { + String text="Hello, GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + Cipher sm4Cipher = Cipher.getInstance("SM4/GCM/NoPadding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4GCM.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4GCM.DEFAULT_IV_SIZE); + byte[] aad = "Hello: ".getBytes(); + // encryption + sm4Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new GCMParameterSpec(SM4GCM.MAX_TAG_SIZE,iv)); + sm4Cipher.updateAAD(aad); + byte[] ciphertext = new byte[100]; + int cipherlen = sm4Cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, 0); + cipherlen += sm4Cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += sm4Cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += sm4Cipher.doFinal(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + byte[] ciphertext1 = Arrays.copyOfRange(ciphertext,0,cipherlen); + System.out.println("Ciphertext: " + byteToHex(ciphertext1)); + // decryption + byte[] plaintext = new byte[ciphertext1.length+SM4GCM.MAX_TAG_SIZE]; + sm4Cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new GCMParameterSpec(SM4GCM.MAX_TAG_SIZE,iv)); + sm4Cipher.updateAAD(aad); + int plainlen =sm4Cipher.doFinal(ciphertext1, 0, ciphertext1.length, plaintext, 0); + byte[] plaintext1 = Arrays.copyOfRange(plaintext,0,plainlen); + System.out.println("plaintext: " + new String(plaintext1)); + } + + @Test + public void SM4_GCM_test2() throws Exception { + String text="Hello,GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + Cipher sm4Cipher = Cipher.getInstance("SM4/GCM/NoPadding", "GmSSL"); + byte[] key = secureRandom.generateSeed(SM4GCM.KEY_SIZE); + byte[] iv = secureRandom.generateSeed(SM4GCM.DEFAULT_IV_SIZE); + byte[] aad = "Hello: ".getBytes(); + // encryption + sm4Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "SM4"), new GCMParameterSpec(SM4GCM.MAX_TAG_SIZE,iv)); + sm4Cipher.updateAAD(aad); + sm4Cipher.updateAAD(aad); + sm4Cipher.update(text.getBytes()); + sm4Cipher.update(text.getBytes()); + sm4Cipher.update(text.getBytes()); + byte[] ciphertext = sm4Cipher.doFinal(); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // decryption + sm4Cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "SM4"), new GCMParameterSpec(SM4GCM.MAX_TAG_SIZE,iv)); + sm4Cipher.updateAAD(aad); + sm4Cipher.updateAAD(aad); + sm4Cipher.update(ciphertext); + byte[] plaintext1=sm4Cipher.doFinal(); + System.out.println("plaintext: " + new String(plaintext1)); + } + + @Test + public void SM9_cipher_test() throws Exception{ + String text="Hello, GmSSL"; + SM9EncMasterKeyGenParameterSpec sm9EncMasterKeyGenParameterSpec = new SM9EncMasterKeyGenParameterSpec("bob"); + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("SM9", "GmSSL"); + keyPairGen.initialize(sm9EncMasterKeyGenParameterSpec); + keyPairGen.generateKeyPair(); + // encryption + PublicKey publicKey = keyPairGen.genKeyPair().getPublic(); + // export public key + SM9PublicKey SM9PublicKey = (SM9PublicKey)publicKey; + SM9PublicKey.exportPublicKeyPem("SM9Public.enc.mpk"); + Cipher sm9Cipher = Cipher.getInstance("SM9", "GmSSL"); + sm9Cipher.init(Cipher.ENCRYPT_MODE, publicKey,sm9EncMasterKeyGenParameterSpec); + byte[] ciphertext = sm9Cipher.doFinal(text.getBytes()); + System.out.println("Ciphertext: " + byteToHex(ciphertext)); + // decryption + SM9PrivateKey privateKey= (SM9PrivateKey) keyPairGen.genKeyPair().getPrivate(); + // export private key + privateKey.exportEncryptedPrivateKeyInfoPem("123456", "SM9Private.enc.mpk"); + SM9MasterKey masterKey = (SM9MasterKey)privateKey.getSecretKey(); + SM9UserKey userKey= masterKey.extractKey(sm9EncMasterKeyGenParameterSpec.getId()); + sm9Cipher.init(Cipher.DECRYPT_MODE, userKey.getPrivateKey()); + byte[] plaintext = sm9Cipher.doFinal(ciphertext); + System.out.println("plaintext: " + new String(plaintext)); + } + + @Test + public void SM9_sign_test() throws Exception{ + String text="Hello, GmSSL"; + SM9SignMasterKeyGenParameterSpec sm9SignMasterKeyGenParameterSpec = new SM9SignMasterKeyGenParameterSpec("alice"); + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("SM9", "GmSSL"); + keyPairGen.initialize(sm9SignMasterKeyGenParameterSpec); + keyPairGen.generateKeyPair(); + + Signature signature = Signature.getInstance("SM9", "GmSSL"); + // Signature + SM9PrivateKey privateKey= (SM9PrivateKey) keyPairGen.genKeyPair().getPrivate(); + // export private key + privateKey.exportEncryptedPrivateKeyInfoPem("123456", "SM9Private.sign.mpk"); + SM9MasterKey masterKey = (SM9MasterKey)privateKey.getSecretKey(); + SM9UserKey userKey= masterKey.extractKey(sm9SignMasterKeyGenParameterSpec.getId()); + signature.initSign(userKey.getPrivateKey()); + byte[] signatureText = text.getBytes(); + signature.update(signatureText); + byte[] signatureByte = signature.sign(); + System.out.println("Signature:"+byteToHex(signatureByte)); + // Verify + signature.setParameter(sm9SignMasterKeyGenParameterSpec); + PublicKey publicKey= keyPairGen.genKeyPair().getPublic(); + // export public key + SM9PublicKey SM9PublicKey = (SM9PublicKey)publicKey; + SM9PublicKey.exportPublicKeyPem("SM9Public.sign.mpk"); + signature.initVerify(publicKey); + signature.update(signatureText); + boolean signatureResult = signature.verify(signatureByte); + System.out.println("SignatureResult:"+signatureResult); + } + + @Test + public void ZUC_test() throws Exception{ + String text="Hello,GmSSL!"; + SecureRandom secureRandom = SecureRandom.getInstance("Random", "GmSSL"); + Cipher cipher = Cipher.getInstance("ZUC","GmSSL"); + SecretKey key = new ZucKey(secureRandom.generateSeed(ZucKey.KEY_SIZE)); + IvParameterSpec ivParameterSpec = new IvParameterSpec(secureRandom.generateSeed(ZucCipher.IV_SIZE)); + // encryption + cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec); + byte[] ciphertext = new byte[100]; + int cipherlen = cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, 0); + cipherlen += cipher.update(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + cipherlen += cipher.doFinal(text.getBytes(), 0, text.getBytes().length, ciphertext, cipherlen); + byte[] ciphertext1 = Arrays.copyOfRange(ciphertext,0,cipherlen); + System.out.println("Ciphertext: " + byteToHex(ciphertext1)); + // decryption + cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec); + cipher.update(ciphertext1); + byte[] plaintext1 = cipher.doFinal(); + System.out.println("plaintext: " + new String(plaintext1)); + } + + /** + * convert byte array to hex string + * @param btArr + * @return String + */ + private String byteToHex(byte[] btArr) { + BigInteger bigInteger = new BigInteger(1, btArr); + return bigInteger.toString(16); + } + + /** + * convert hex string to byte array + * @param hexString + * @return byte[] + */ + private byte[] hexToByte(String hexString) { + byte[] byteArray = new BigInteger(hexString, 16) + .toByteArray(); + if (byteArray[0] == 0) { + byte[] output = new byte[byteArray.length - 1]; + System.arraycopy( + byteArray, 1, output, + 0, output.length); + return output; + } + return byteArray; + } +} diff --git a/src/test/java/org/gmssl/Sm4EcbTest.java b/src/test/java/org/gmssl/Sm4EcbTest.java index b218c09..3f5c324 100644 --- a/src/test/java/org/gmssl/Sm4EcbTest.java +++ b/src/test/java/org/gmssl/Sm4EcbTest.java @@ -32,7 +32,7 @@ public void beforeTest(){ @Test public void encryptTest(){ String test_plaintext="gmssl"; - byte[] paddingPlaintext=pkcs5padding(test_plaintext.getBytes(),Sm4.BLOCK_SIZE); + byte[] paddingPlaintext=pkcs7padding(test_plaintext.getBytes(),Sm4.BLOCK_SIZE); byte[] encrypted = encrypt(paddingPlaintext,key); //System.out.println("encrypted data:"+HexUtil.byteToHex(encrypted)); Assert.assertNotNull("data is empty exception!",encrypted); @@ -44,7 +44,7 @@ public void decryptTest(){ String test_plaintext="gmssl"; byte[] encrypted =HexUtil.hexToByte(test_hex_chipertext); byte[] plaintextArray = decrypt(encrypted,key); - byte[] unpaddingPlaintextArray = pkcs5Unpadding(plaintextArray); + byte[] unpaddingPlaintextArray = pkcs7UnPadding(plaintextArray); String plaintext=new String(unpaddingPlaintextArray); //System.out.println("chipertext:"+plaintext); Assert.assertEquals("original value is not equal to the expected value after decryption!",plaintext,test_plaintext); @@ -52,40 +52,40 @@ public void decryptTest(){ /** - * The purpose of PKCS5Padding is to pad the data to the block size required by the encryption algorithm, ensuring that the data length meets the requirements of the encryption algorithm. - * In special cases where the data length is already a multiple of the block size, according to the PKCS5 rule, padding is still added at the end. + * The purpose of PKCS7Padding is to pad the data to the block size required by the encryption algorithm, ensuring that the data length meets the requirements of the encryption algorithm. + * In special cases where the data length is already a multiple of the block size, according to the PKCS7 rule, padding is still added at the end. * This is done to ensure consistent handling of padding during encryption and decryption processes. - * @param ciphertextArray + * @param byteArray * @param blockSize - * @return byte[] ciphertext + * @return byte[] padding array */ - private static byte[] pkcs5padding(byte[] ciphertextArray, int blockSize) { - int paddingLength = blockSize - (ciphertextArray.length % blockSize); + private static byte[] pkcs7padding(byte[] byteArray, int blockSize) { + int paddingLength = blockSize - (byteArray.length % blockSize); byte[] padding = new byte[paddingLength]; Arrays.fill(padding, (byte) paddingLength); - byte[] result = new byte[ciphertextArray.length + padding.length]; - System.arraycopy(ciphertextArray, 0, result, 0, ciphertextArray.length); - System.arraycopy(padding, 0, result, ciphertextArray.length, padding.length); + byte[] result = new byte[byteArray.length + padding.length]; + System.arraycopy(byteArray, 0, result, 0, byteArray.length); + System.arraycopy(padding, 0, result, byteArray.length, padding.length); return result; } /** - * unpadding the plaintext - * @param plaintextArray - * @return byte[] plaintext + * unPadding the byteArray + * @param byteArray + * @return byte[] unPadding byteArray * @throws IllegalArgumentException */ - private static byte[] pkcs5Unpadding(byte[] plaintextArray) throws IllegalArgumentException { - int paddingSize = plaintextArray[plaintextArray.length - 1]; - if (paddingSize <= 0 || paddingSize > plaintextArray.length) { - throw new IllegalArgumentException("Invalid pkcs#5 padding!"); + private static byte[] pkcs7UnPadding(byte[] byteArray) throws IllegalArgumentException { + int paddingSize = byteArray[byteArray.length - 1]; + if (paddingSize <= 0 || paddingSize > byteArray.length) { + throw new IllegalArgumentException("Invalid pkcs#7 padding!"); } - for (int i = plaintextArray.length - paddingSize; i < plaintextArray.length; i++) { - if (plaintextArray[i] != paddingSize) { - throw new IllegalArgumentException("Invalid pkcs#5 padding!"); + for (int i = byteArray.length - paddingSize; i < byteArray.length; i++) { + if (byteArray[i] != paddingSize) { + throw new IllegalArgumentException("Invalid pkcs#7 padding!"); } } - return Arrays.copyOfRange(plaintextArray, 0, plaintextArray.length - paddingSize); + return Arrays.copyOfRange(byteArray, 0, byteArray.length - paddingSize); } @@ -113,7 +113,7 @@ private static byte[] encrypt(byte[] data, byte[] key) { private static byte[] decrypt(byte[] data, byte[] key) { byte[] plaintext=new byte[data.length]; Sm4 sm4 = new Sm4(key, false); - for (int i = 0; i < data.length; i += 16) { + for (int i = 0; i < data.length; i += Sm4.BLOCK_SIZE) { sm4.encrypt(data, i, plaintext, i); } return plaintext;