Java读取RSA pem公钥 使用公钥验证签名

之所以要记录是因为网上找了好久,试了好多方法,基本上都不好使.
签名sign做了base64

        BASE64Decoder base64decoder = new BASE64Decoder();
    try {
        //读取pem证书
        BufferedReader br = new BufferedReader(new FileReader("xxx.pem"));
        String s = br.readLine();
        StringBuffer publickey = new StringBuffer();
        s = br.readLine();
        while (s.charAt(0) != '-') {
            publickey.append(s + "\r");
            s = br.readLine();
        }
        byte[] keybyte = base64decoder.decodeBuffer(publickey.toString());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keybyte);
        PublicKey publicKey = kf.generatePublic(keySpec);
        BASE64Encoder bse=new BASE64Encoder();
        System.out.println("pk:"+bse.encode(publicKey.getEncoded()));

        //被签的原文
        String toSign="sxxxsasdsss";
        //生成的签名
        String sign="xxxxx";

        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(publicKey);
        signature.update(toSign.getBytes());
        boolean verify = signature.verify(base64decoder
            .decodeBuffer(
                sign));
        System.out.println(verify);
    } catch (Exception e) {
        e.printStackTrace();
    }

© 2017, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记