我正在Java中生成密钥对,并在WebCrypto API通过使用公共密钥。我得到的加密数据是以uint8array格式,试图用我的爪哇的私钥解密独自一人。
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);
});
签署了所有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;
}