1

我在 java 中生成密钥对,并使用公钥在 webcrypto API 中加密了一些纯文本。我得到的加密数据是 Uint8Array 格式,并试图用我的私钥在 java 中单独解密。

Java 代码:

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;

public class RSAOAEP {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = "{\"userid\":\"raj1242\",\"appid\":\"1234\",\"tenentid\":\"4567\",\"sessionid\":\"session1234567\"}".getBytes();
    Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
    SecureRandom random = new SecureRandom();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");

    generator.initialize(4096, random);

    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();

    Key privKey = pair.getPrivate();

    System.out.println("privateKey: "+privKey);
    System.out.println("publicKey: "+pubKey);

    //Need to assign value from webcrpto api encrypted data
    byte[] cipherText= {};
    cipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainText = cipher.doFinal(cipherText);
    System.out.println("plain : " + new String(plainText));
  }
}

用于加密数据的 Webcrypto API 代码:

window.crypto.subtle.encrypt(
    {
        name: "RSA-OAEP",
        //label: Uint8Array([...]) //optional
    },
    publicKey, //from java generateKey 
    data //ArrayBuffer of data you want to encrypt
)
.then(function(encrypted){
    //returns an ArrayBuffer containing the encrypted data
    console.log(new Uint8Array(encrypted));
})
.catch(function(err){
    console.error(err);
});
4

1 回答 1

0

所有 Java 原语都经过签名。要将 Uint8 转换为字节,您可以执行以下操作。尽管这些值可能看起来不相等,但更精确的算法适用于位表示。
从 0 到 127 的值在有符号和无符号版本上是相等的

            Signed byte value   Unsigned byte value
0000 0001  =  1                 1
...
0111 1111  =  127               127

128个值像这样变化后

              Signed byte value  Unsigned byte value
1000 0000   = -128                128
1000 0001   = -127                129
1000 0011   = -125                131
.....
1111 1111   = -1                  255

所以我们可以编写代码来将无符号值位表示转换为有符号字节。

    // You should read uint8 value to short and then do the conversion
    public byte covertToSignedByte (short unit8Value){
        byte byteValue ;
        if(unit8Value <= 127){
           byteValue = (byte) unit8Value; // it is same up to 127
        }
        else {
           byteValue = (byte)(unit8Value- 256); // after 128 we can substract 256 to get the signed bit representation
        }
        return byteValue;
    }
于 2018-02-09T19:30:45.230 回答