我需要将其从Java复制到JavaScript(NodeJs)

csbfibhn  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(92)

我试图让java类的相同功能复制到NodeJ中,但是我做不到。我不理解所有的JavaCode,特别是当示例sing()(返回什么)时。因为它不能复制到NodeJ中
Java代码

public String generateSignature(String key, String stringToSign) throws Exception {
    Signature signatureInstance = Signature.getInstance("SHA256WithRSA");

    ServiceKeyRep keyRep = new ServiceKeyRep(KeyRep.Type.PRIVATE, "RSA", "PKCS#8",      Base64.getDecoder().decode(key));

    PrivateKey resolvedPrivateKey = (PrivateKey) keyRep.readResolve();

    signatureInstance.initSign(resolvedPrivateKey);           
    
    byte[] bytesToSign = stringToSign.getBytes("UTF-8");

    
    signatureInstance.update(bytesToSign);
    
    String signatureString = Base64.getEncoder().encodeToString(signatureBytes);

    return signatureString;
}

我在 NodeJS 上试了一下

const privateKey = fs.readFileSync('myKey.pem', 'utf-8');
const stringToSign = new Int8Array([ myData ]);
const data = Buffer.from(stringToSign);  
const sign = crypto.sign("RSA-SHA256", data , privateKey);  
const signature = sign.toString('base64');  

//Printing the signature 
console.log(`Signature:\n\n ${signature}`);

但是当我打印出来的时候,输出是不一样的

xdyibdwo

xdyibdwo1#

使用crypto库我们可以在JS.Adapt中做一些类似的事情,这只是一个参考。

const fs = require('fs');
const crypto = require('crypto');

function generateSignature(key, stringToSign) {
  const privateKey = fs.readFileSync(key, 'utf-8');

  const sign = crypto.createSign('RSA-SHA256');
  sign.update(stringToSign);

  const signature = sign.sign(privateKey, 'base64');

  return signature;
}

const key = 'myKey.pem';
const stringToSign = 'myData';

const signature = generateSignature(key, stringToSign);

console.log(`Signature:\n\n${signature}`);

相关问题