Java PrivateKey与Android不同

时间:2014-10-15 12:49:15

标签: java android private-key

我实际上在Android中遇到加密问题。为了测试,我创建了一个使用RSA和SHA生成签名的程序。

public static byte[] generateKey(String privKeyModulus,  String privKeyD, String encryptCredentials)    throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,  UnsupportedEncodingException, SignatureException {

    byte[] modulusBytes = Base64.getDecoder().decode(privKeyModulus.getBytes());
    byte[] dBytes = Base64.getDecoder().decode(privKeyD.getBytes());


    BigInteger modulusInt = new BigInteger(1, modulusBytes);
    BigInteger dInt = new BigInteger(1, dBytes);

    RSAPrivateKeySpec rsaPrivKey = new RSAPrivateKeySpec(modulusInt, dInt);
    KeyFactory factory = KeyFactory.getInstance("RSA");

    PrivateKey privKey = factory.generatePrivate(rsaPrivKey);


    // Here is the problem: 
    System.out.println(Arrays.toString(privKey.getEncoded()));

    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(privKey);
    sig.update((encryptCredentials).getBytes("UTF-16LE"));          
    byte[] signature = sig.sign();

    return signature;
}

现在的问题是我在Java和Android中获得了与PrivateKey不同的值。这让我感到困惑,因为这两个程序中的方法完全相同,java.security应该可以在Java和Android中使用。 我还检查了所有其他值(比如byte []等),但它们都是一样的。

你有任何帮助吗?

1 个答案:

答案 0 :(得分:0)

将私钥编码为PKCS#8和Base64以将其发送并重建私钥:

@Test
public void testKeyConversion() throws GeneralSecurityException {

    /* Generate random key pair */
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    AlgorithmParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
    keyPairGenerator.initialize(spec, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    /* Encode private key as PKCS#8 base64 string */
    byte[] privKeyBytes = keyPair.getPrivate().getEncoded();
    String privKeyStr = DatatypeConverter.printBase64Binary(privKeyBytes);

    /* Decode private key as PKCS#8 base64 string */
    byte[] privKeyBytes2 = DatatypeConverter.parseBase64Binary(privKeyStr);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes2);
    PrivateKey privateKey = keyFactory.generatePrivate(privSpec);

    /* Ensure key is the same */
    byte[] privKeyBytes3 = privateKey.getEncoded();
    assertEquals(
            DatatypeConverter.printHexBinary(privKeyBytes),
            DatatypeConverter.printHexBinary(privKeyBytes3));
}

使用android.util.Base64代替java.xml.bind.DatatypeConverter,这在Android平台上不可用。