rsa Sign Hex String - Android java.security

Android examples for java.security:RSA

Description

rsa Sign Hex String

Demo Code


import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main{
    /**/*  ww  w .  j a  v a 2 s.co  m*/
     * UTF-8
     */
    public static final String UTF_8 = "UTF-8";
    /**
     * rsaSignHex
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String rsaSignHex(String content, String privateKey)
            throws Exception {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(privateKey)) {
            throw new Exception("illegal params.");
        }
        return bytesToHexString(rsaSign(content.getBytes(UTF_8),
                privateKey.getBytes(UTF_8)));
    }
    
    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            int v = bytes[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    /**
     * rsaSign
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] rsaSign(byte[] content, byte[] privateKey)
            throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decode(privateKey, Base64.DEFAULT);
        PrivateKey privateKeyObj = keyFactory
                .generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        java.security.Signature signature = java.security.Signature
                .getInstance("SHA1WithRSA");
        signature.initSign(privateKeyObj);
        signature.update(content);
        return signature.sign();
    }
}

Related Tutorials