无法将 WebCrypto 密钥对转换为 Java RSA 密钥
Unable to convert a WebCrypto key pair to Java RSA keys
I have public key and private key as string which are generated from
Webcrypto API RSA-OAEP algorithm. I want to encrypt and decrypt some
plain text by using those and getting exception when trying to convert
string to byte array
Java代码:
package mailsend;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RsaOaep {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//Encryption
byte[] input = "{\"userid\":\"1242\",\"appid\":\"1234\",\"tenentid\":\"4567\",\"sessionid\":\"session1234567\"}".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
SecureRandom random = new SecureRandom();
String publicKey="{\n" +
" \"alg\": \"RSA-OAEP-256\",\n" +
" \"e\": \"AQAB\",\n" +
" \"ext\": true,\n" +
" \"key_ops\": [\n" +
" \"encrypt\"\n" +
" ],\n" +
" \"kty\": \"RSA\",\n" +
" \"n\": \"uChD48P6OBCynflLVsuP51hExmS7JIJmSPe6g_RYeb-O8rbaJA6mJE7QsMBeCrBUeyjhFYOFkGV9tpu3xIMkuRmTiyqy_mP2DKo8x9RB0gGVRvDuFjyOb3qpTAEA1SGyo_jGwN3RmVAVzVOTAAHqgQpRHtUsFEpQImUJgOUGVAfyFYpyyJKypcRv-RIU2JxOg3w7-i53erZPMHq_eWzEEXOgAU49UPjlTV18bXklBKSy3sbhKDpvHvOh_rEufhtD1Jl5RAQz3o8GGWPmcSf_3h5xa5ppqcgx6cfHDY9KKgxgCScwtjzTqU_QJO_zRnf3kYFU4dIFkfpXOJDDJc6RwQ\"\n" +
"}";
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
PublicKey publicKeyNew = KeyFactory.getInstance("RSA", "BC").generatePublic(new X509EncodedKeySpec(keyBytes));
cipher.init(Cipher.ENCRYPT_MODE, publicKeyNew, random);
byte[] cipherText = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherText));
//Decryption
String privateKey="{\n" +
" \"alg\": \"RSA-OAEP-256\",\n" +
" \"d\": \"FZO8Lp_r_a0xLHLE6cjElePg_QjY54Ry1RpXi3Xx9uPjrRsREJf5zffBGnCTpDd4Uozd4I4uNFa75c01eSwvfZOaVrw8SDOwpNe-cuBzDNbcJXl9v_O88aFi3DGi5hYCbxVrPjZPRGIeh9YCu4W98vwhOJZcCY2SeZEyjZxoAyjOmsvvylpUVN2ZVJ22lDOaBJMerPdwyXFv9wsUserFleZByk-M8WLz5JiT3MIg6NuMiMryx3-lhcHCBXgHJMeuxrdnPc_acer3WNkgWf5Q4LkTu9TT_Uz4kULtPvdbccv3-JyE0x4ZjCfiAmT65vUM5WvmCE6MZseR3WONIxmh0Q\",\n" +
" \"dp\": \"FdzMUisoeG6Kk4C7Ol7k3QqR6QKa18LsMVIQXruQ7Vxm4bJ0lo8WyHWhLy4n11JLs7OGFENyXu7NtXw0ezmolfKIJVlItxWofICm8wm3Rhljrxe9KJnp1V4L1ibCXLOXOLsqhUwesWOhjAkfTHWJf3-wslSxVtFbif3fjeaKHlk\",\n" +
" \"dq\": \"YTfHIEIOYiJ9AW_r3R8ou69ApwyzFNqczSeVooMKvKTYrpdj4ms6MeW5uL8Pq9HKFr8AFA2FWtOvrHrxShw_1V9IuvNChmPEF11RIO7CSc6xeK98zFtgqzbpJ81SKlcKh4icpaSjX3SQa7qbasgk9MBxK5gmpc5XZZNICDKfZ-E\",\n" +
" \"e\": \"AQAB\",\n" +
" \"ext\": true,\n" +
" \"key_ops\": [\n" +
" \"decrypt\"\n" +
" ],\n" +
" \"kty\": \"RSA\",\n" +
" \"n\": \"uChD48P6OBCynflLVsuP51hExmS7JIJmSPe6g_RYeb-O8rbaJA6mJE7QsMBeCrBUeyjhFYOFkGV9tpu3xIMkuRmTiyqy_mP2DKo8x9RB0gGVRvDuFjyOb3qpTAEA1SGyo_jGwN3RmVAVzVOTAAHqgQpRHtUsFEpQImUJgOUGVAfyFYpyyJKypcRv-RIU2JxOg3w7-i53erZPMHq_eWzEEXOgAU49UPjlTV18bXklBKSy3sbhKDpvHvOh_rEufhtD1Jl5RAQz3o8GGWPmcSf_3h5xa5ppqcgx6cfHDY9KKgxgCScwtjzTqU_QJO_zRnf3kYFU4dIFkfpXOJDDJc6RwQ\",\n" +
" \"p\": \"_8_ViZjqi4qU0jdt4dbrv81-FYFjJ0A3CpHhOwDxvIHRBMTS188_SEe-CZFwF91myv3AF9ZA64gYscr6t765F3-R7ydygryQWOedE-meRZhUHw3E3y-w_Khvtv0k3DW_NBO1-i3MDi8HV-xoSED9_ZYP6B0N05sBeoLhr76MuVk\",\n" +
" \"q\": \"uErwgmSi7_t90oqKEED4Da8csEZVBN6_7n9xbZEk366lPf5rPETPbr8DKG-rA4kXq3l10ZksC-oo0RKdMpnqoHiYjmFPex1uLXJOAR_sg8ENtYtH-U6tNBjpoLufnbtg39O4bT7jr0HXx3MQmNy4rumfO97XypqIdKkrAODtJqk\",\n" +
" \"qi\": \"brnAuBOvNKKdkwsI836lPNxmKqAMc-Jbtn7YmOu3ofq6PtiT5blJSGUJizMd1YDRHTLlQzWt1eqFZr_AjidGZ0QvYSj1jZT1hdpkIGn1M6oDDwh73mDC_Wqg5qtyFp6YudzWpSt5TG7m94pyPFx79wm1WedW53RVNQVdx3yOcBI\"\n" +
"}";
byte[] keyBytesNew = Base64.getDecoder().decode(privateKey);
PrivateKey privateKeyNew = KeyFactory.getInstance("RSA", "BC").generatePrivate(new X509EncodedKeySpec(keyBytesNew));
cipher.init(Cipher.DECRYPT_MODE, privateKeyNew);
byte[] plainText = cipher.doFinal(cipherText);
System.out.println("plain : " + new String(plainText));
}
}
异常:
Exception in thread "main" java.lang.IllegalArgumentException:
Illegal base64 character 7b at
java.util.Base64$Decoder.decode0(Base64.java:714) at
java.util.Base64$Decoder.decode(Base64.java:526) at
java.util.Base64$Decoder.decode(Base64.java:549) at
mailsend.RsaOaep.main(RsaOaep.java:30)
webcrypto 导出的密钥采用 JWK(JSON Web 密钥)格式。 Java不直接支持这种格式,所以必须先处理RSA密钥对的组成部分
正确生成密钥后,您可以检查加密代码
1.解码 JSON Web Key:解析 JSON 字符串并提取 public 和私钥
的组件
我建议使用像 Jackson 这样的 JSON 库。看到这个 sample
public class JWK{
String n;
String e;
//getters and setters
}
ObjectMapper mapper = new ObjectMapper();
JWK jwk = mapper.readValue(publicKeyJson, JWK.class);
2。将关键组件转换为 BigInteger:模数、public 指数、私有指数等被编码为 base64url 字符串。将这些字符串解码为 byte[] 并使用它们构建 BigInteger,因此它们可以由 Java Key builders
加载
byte[] publicExponentBytes = Base64.getUrlDecoder().decode(jwkPublic.e);
byte[] privateExponentBytes = Base64.getUrlDecoder().decode(jwkPrivate.d);
byte[] modulusBytes = Base64.getUrlDecoder().decode(jwkPublic.n);
BigInteger publicExponent = new BigInteger(1, publicExponentBytes );
BigInteger privateExponent = new BigInteger(1, privateExponentBytes);
BigInteger modulus = new BigInteger(1, modulusBytes);
3。使用模数 (n) 和 public 指数 (e)
构建 public 密钥
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent );
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(spec);
4.使用模数 (n) 和私有指数 (d)
构建私钥
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
I have public key and private key as string which are generated from Webcrypto API RSA-OAEP algorithm. I want to encrypt and decrypt some plain text by using those and getting exception when trying to convert string to byte array
Java代码:
package mailsend;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RsaOaep {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//Encryption
byte[] input = "{\"userid\":\"1242\",\"appid\":\"1234\",\"tenentid\":\"4567\",\"sessionid\":\"session1234567\"}".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
SecureRandom random = new SecureRandom();
String publicKey="{\n" +
" \"alg\": \"RSA-OAEP-256\",\n" +
" \"e\": \"AQAB\",\n" +
" \"ext\": true,\n" +
" \"key_ops\": [\n" +
" \"encrypt\"\n" +
" ],\n" +
" \"kty\": \"RSA\",\n" +
" \"n\": \"uChD48P6OBCynflLVsuP51hExmS7JIJmSPe6g_RYeb-O8rbaJA6mJE7QsMBeCrBUeyjhFYOFkGV9tpu3xIMkuRmTiyqy_mP2DKo8x9RB0gGVRvDuFjyOb3qpTAEA1SGyo_jGwN3RmVAVzVOTAAHqgQpRHtUsFEpQImUJgOUGVAfyFYpyyJKypcRv-RIU2JxOg3w7-i53erZPMHq_eWzEEXOgAU49UPjlTV18bXklBKSy3sbhKDpvHvOh_rEufhtD1Jl5RAQz3o8GGWPmcSf_3h5xa5ppqcgx6cfHDY9KKgxgCScwtjzTqU_QJO_zRnf3kYFU4dIFkfpXOJDDJc6RwQ\"\n" +
"}";
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
PublicKey publicKeyNew = KeyFactory.getInstance("RSA", "BC").generatePublic(new X509EncodedKeySpec(keyBytes));
cipher.init(Cipher.ENCRYPT_MODE, publicKeyNew, random);
byte[] cipherText = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherText));
//Decryption
String privateKey="{\n" +
" \"alg\": \"RSA-OAEP-256\",\n" +
" \"d\": \"FZO8Lp_r_a0xLHLE6cjElePg_QjY54Ry1RpXi3Xx9uPjrRsREJf5zffBGnCTpDd4Uozd4I4uNFa75c01eSwvfZOaVrw8SDOwpNe-cuBzDNbcJXl9v_O88aFi3DGi5hYCbxVrPjZPRGIeh9YCu4W98vwhOJZcCY2SeZEyj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188_SEe-CZFwF91myv3AF9ZA64gYscr6t765F3-R7ydygryQWOedE-meRZhUHw3E3y-w_Khvtv0k3DW_NBO1-i3MDi8HV-xoSED9_ZYP6B0N05sBeoLhr76MuVk\",\n" +
" \"q\": \"uErwgmSi7_t90oqKEED4Da8csEZVBN6_7n9xbZEk366lPf5rPETPbr8DKG-rA4kXq3l10ZksC-oo0RKdMpnqoHiYjmFPex1uLXJOAR_sg8ENtYtH-U6tNBjpoLufnbtg39O4bT7jr0HXx3MQmNy4rumfO97XypqIdKkrAODtJqk\",\n" +
" \"qi\": \"brnAuBOvNKKdkwsI836lPNxmKqAMc-Jbtn7YmOu3ofq6PtiT5blJSGUJizMd1YDRHTLlQzWt1eqFZr_AjidGZ0QvYSj1jZT1hdpkIGn1M6oDDwh73mDC_Wqg5qtyFp6YudzWpSt5TG7m94pyPFx79wm1WedW53RVNQVdx3yOcBI\"\n" +
"}";
byte[] keyBytesNew = Base64.getDecoder().decode(privateKey);
PrivateKey privateKeyNew = KeyFactory.getInstance("RSA", "BC").generatePrivate(new X509EncodedKeySpec(keyBytesNew));
cipher.init(Cipher.DECRYPT_MODE, privateKeyNew);
byte[] plainText = cipher.doFinal(cipherText);
System.out.println("plain : " + new String(plainText));
}
}
异常:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 7b at java.util.Base64$Decoder.decode0(Base64.java:714) at java.util.Base64$Decoder.decode(Base64.java:526) at java.util.Base64$Decoder.decode(Base64.java:549) at mailsend.RsaOaep.main(RsaOaep.java:30)
webcrypto 导出的密钥采用 JWK(JSON Web 密钥)格式。 Java不直接支持这种格式,所以必须先处理RSA密钥对的组成部分
正确生成密钥后,您可以检查加密代码
1.解码 JSON Web Key:解析 JSON 字符串并提取 public 和私钥
的组件我建议使用像 Jackson 这样的 JSON 库。看到这个 sample
public class JWK{
String n;
String e;
//getters and setters
}
ObjectMapper mapper = new ObjectMapper();
JWK jwk = mapper.readValue(publicKeyJson, JWK.class);
2。将关键组件转换为 BigInteger:模数、public 指数、私有指数等被编码为 base64url 字符串。将这些字符串解码为 byte[] 并使用它们构建 BigInteger,因此它们可以由 Java Key builders
加载byte[] publicExponentBytes = Base64.getUrlDecoder().decode(jwkPublic.e);
byte[] privateExponentBytes = Base64.getUrlDecoder().decode(jwkPrivate.d);
byte[] modulusBytes = Base64.getUrlDecoder().decode(jwkPublic.n);
BigInteger publicExponent = new BigInteger(1, publicExponentBytes );
BigInteger privateExponent = new BigInteger(1, privateExponentBytes);
BigInteger modulus = new BigInteger(1, modulusBytes);
3。使用模数 (n) 和 public 指数 (e)
构建 public 密钥RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent );
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(spec);
4.使用模数 (n) 和私有指数 (d)
构建私钥RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(privateKeySpec);