Android examples for java.security:RSA
rsa Verify Hex String
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{ /* w w w . ja v a 2s. c om*/ public static final String HEX_DIGITS = "0123456789ABCDEF"; /** * UTF-8 */ public static final String UTF_8 = "UTF-8"; /** * rsaVerifyHex * @param content * @param sign * @param publicKey * @return * @throws Exception */ public static boolean rsaVerifyHex(String content, String sign, String publicKey) throws Exception { if (StringUtils.isBlank(content) || StringUtils.isBlank(sign) || StringUtils.isBlank(publicKey)) { throw new Exception("illegal params."); } return rsaVerify(content.getBytes(UTF_8), hexStringToBytes(sign), publicKey.getBytes(UTF_8)); } /** * rsaVerify * @param content * @param sign * @param publicKey * @return * @throws Exception */ public static boolean rsaVerify(byte[] content, byte[] sign, byte[] publicKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT); PublicKey publicKeyObj = keyFactory .generatePublic(new X509EncodedKeySpec(encodedKey)); java.security.Signature signature = java.security.Signature .getInstance("SHA1WithRSA"); signature.initVerify(publicKeyObj); signature.update(content); return signature.verify(sign); } public static byte[] hexStringToBytes(String hexString) { if (StringUtils.isBlank(hexString)) { return null; } char[] hexChars = hexString.toUpperCase(Locale.US).toCharArray(); int length = hexString.length() / 2; byte[] bytes = new byte[length]; for (int i = 0; i < length; ++i) { bytes[i] = (byte) (HEX_DIGITS.indexOf(hexChars[i * 2]) << 4 | HEX_DIGITS .indexOf(hexChars[i * 2 + 1])); } return bytes; } }