如何使用 android 获取摘要?

How can I get digest with android?

我需要签署 String 并发送两者。我有一个 .pem 文件作为私钥,我正在尝试将此文件转换为 PrivateKey.

这是我的代码:

try {
            File privateKeyFile = new File("path to .pem file");

            //TODO: HOW CAN I CONVERT THAT FILE INTO PRIVATE KEY?

            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(privateKey);
            signature.update(data.getBytes());

            byte[] sign = signature.sign();
        } catch (NoSuchAlgorithmException | SignatureException e) {
            e.printStackTrace();
        }

你有什么建议给我吗?

我是这样解决的: 相反使用 .pem 文件我直接保存了从 PrivateKey 获得的 String 然后当我需要签署数据时,我得到 String 并将其转换为 PrivateKey.

这是我的代码:

public String signData(final String data, final String privateKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(privateKeyString.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);


        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        byte[] sign = signature.sign();
        return new String(sign);
    }