Sample code

The following examples assume that you use the Java language.

Signature generation

private String doSign(String content, String privateKey, String charset)

                                                                            throws SignatureException {

        try {

            PrivateKey priKey = KeyReader.getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(

                privateKey.getBytes()));

            java.security.Signature signature = java.security.Signature

                .getInstance("SHA256withRSA");

            signature.initSign(priKey);

            signature.update(getContentBytes(content, charset));

            byte[] signed = signature.sign();

            return new String(Base64.encodeBase64(signed));

        } catch (Exception e) {

            throw new SignatureException("Failed to create RSA signature! [content = " + content + "; charset = " + charset

                                         + "]", e);

        }

    }

Signature Verification

private boolean doCheck(String content, String sign, String publicKey, String charset)

                                                                                          throws SignatureException {

        try {

            PublicKey pubKey = KeyReader.getPublicKeyFromX509("RSA", new ByteArrayInputStream(

                publicKey.getBytes()));

            java.security.Signature signature = java.security.Signature

                .getInstance("SHA256withRSA");

            signature.initVerify(pubKey);

            signature.update(getContentBytes(content, charset));

            return signature.verify(Base64.decodeBase64(sign.getBytes()));

        } catch (Exception e) {

            throw new SignatureException("Failed to verify RSA signature! [content = " + content + "; charset = " + charset

                                         + "; signature = " + sign + "]", e);

        }

    }