无法将WebCrypto密钥对转换为Java RSA密钥

时间:2018-02-06 08:55:21

标签: java encryption base64 rsa webcryptoapi

  

我将公钥和私钥作为字符串生成   Webcrypto API RSA-OAEP算法。我想加密和解密一些   通过使用那些纯文本并在尝试转换时获得异常   字符串到字节数组

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));
  }
}

例外:

  

线程“main”中的异常java.lang.IllegalArgumentException:   非法base64字符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)

1 个答案:

答案 0 :(得分:2)

webcrypto导出的密钥采用JWK(JSON Web Key)格式。 Java不直接支持此格式,因此您必须首先处理RSA密钥对的组件

正确生成密钥后,您可以检查加密代码

<强> 1。解码de JSON Web Key :解析JSON字符串并提取公钥和私钥的组件

我建议使用像杰克逊这样的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 :模数,公共指数,私有指数等编码为base64url字符串。将这些字符串解码为byte []并使用它们构建BigInteger,因此它们可以由Java Key构建器加载

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)和公共指数(e)

构建公钥
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);