Skip to content

公钥加密

公钥加密说明

公钥加密的定义

hengshi 系统公钥加密,主要用于 hengshi 用户密码的加密。

结构说明

接口说明

获取公钥

获取公钥。

请求URL

http
POST /api/rsa HTTP/1.1
Content-Type: application/json
Cookie: csrf=183f1c4...; sid=26ee552d...; _USER_SESSION_ID=f2a01083...

请求参数

URL 参数

request body 参数

返回对象的格式说明

字段类型说明
uuidSTRINGuuid
publicKeySTRING公钥

接口示例1: 获取公钥

http
POST /api/rsa HTTP/1.1
Content-Type: application/json
Cookie: csrf=183f1c4...; sid=26ee552d...; _USER_SESSION_ID=f2a01083...
http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "version": "version@9a5e106#6730f0d",
    "code":0,
    "msg":"success",
    "data":{
        "uuid":"315b33bc-24f8-4e01-a92b-e57a250453db",
        "publicKey":"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMIZ/S3Gu4V02uE2mOgZyRzfe8njecXBn3YSwhyVFmKLpF6pJIBBthsGOI+I45DlZpMaEbympaNS6UHTIULnZUcCAwEAAQ=="
    }
}

接口示例2: 使用公钥加密

linux shell 示例
shell
encrypt_password_v2() {
    local pubkey="$1"
    local passwd="$2"
    echo -n "$passwd" | openssl rsautl -encrypt -inkey <(echo -e "-----BEGIN PUBLIC KEY-----\n$(echo $pubkey | split -b 64 --filter "cat; echo ''")\n-----END PUBLIC KEY-----") -pubin  | base64 | tr -d '\n'
}

encrypt_password_v2  {PUBLIC_KEY} {PASSWORD}
java 示例
java
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public static String encryptPassword(String publicKeyStr, String password) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    byte[] bytes = Base64.getDecoder().decode(publicKeyStr);
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes);
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    String encryptedPassword = Base64.getEncoder().encodeToString(cipher.doFinal(password.getBytes()));
    return encryptedPassword;
}
javascript 实例
javascript
import { JSEncrypt } from 'jsencrypt';

function encryptPassword(publicKey, password) {
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey);
  const ep = encrypt.encrypt(password);
  return ep
}

HENGSHI SENSE API 使用手册