Android中常用的加密方式[通俗易懂]

Android中常用的加密方式[通俗易懂]Android中常用的加密方式HmacSHA1publicstaticStringgetSignUtil(Stringkey,Stringbase){Log.i(TAG,”getSignUtil:GETSIGN”);Stringtype=”HmacSHA1″;SecretKeySpecsecret=newSecretKeySpec(key.getBytes(),type);Macmac=null;try{

大家好,又见面了,我是你们的朋友全栈君。

Android中常用的加密方式

HmacSHA1

public static String getSignUtil(String key ,String base) {
    Log.i(TAG, "getSignUtil: GET SIGN");
    String type = "HmacSHA1";
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
    Mac mac = null;
    try {
        mac = Mac.getInstance(type);
        mac.init(secret);
        byte[] digest = mac.doFinal(base.getBytes());
        Log.i(TAG, "authorization:  " + Base64.encodeToString(digest, Base64.DEFAULT));
        return Base64.encodeToString(digest, Base64.DEFAULT);
    } catch (Exception e) {
        Log.e(TAG, "getSignUtil: " + e.toString());
    }
    return type;
}

MD5 and RSA

public class DigestUtils {

public static String TAG = “DigestUtils”;
private static final char[] hexCode = “0123456789ABCDEF”.toCharArray();

public static String md5(String input) {
    byte[] bytes = new byte[0];
    try {
        bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "md5: " + e.toString());
    }
    return printHexBinary(bytes);
}

public static String printHexBinary(byte[] data) {
    StringBuilder r = new StringBuilder(data.length * 2);
    for (byte b : data) {
        r.append(hexCode[(b >> 4) & 0xF]);
        r.append(hexCode[(b & 0xF)]);
    }
    return r.toString();
}


/**
 * RSA私钥解密
 *
 * @param message    加密字符串
 * @param privateKey 私钥
 * @return铭文
 */

public static String decrypt(String message, String privateKey) {
    try {
        if (message.contains(" ")) {
            message = message.replaceAll(" " , "+");
        }
        //base64编码的私钥
        final byte[] decoded = Base64.decode(privateKey, Base64.DEFAULT);

        //final byte[] inputByte = Base64.decodeBase64(message.getBytes(StandardCharsets.UTF_8))

        //decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        //64位解码加密后的字符串
        final byte[] inputByte = Base64.decode(message.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);

        //  decodeBase64(message.getBytes(StandardCharsets.UTF_8));
        //密文
        final int len = inputByte.length;
        //偏移量
        int offset = 0;
        //段数
        int i = 0;
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (len - offset > 0) {
            byte[] cache;
            if
            (len - offset > 128) {
                cache = cipher.doFinal(inputByte, offset, 128);
            } else {
                cache = cipher.doFinal(inputByte, offset, len - offset);
            }
            bos.write(cache);
            i++;
            offset = 128 * i;
        }
        bos.close();
        return new String(bos.toByteArray(), StandardCharsets.UTF_8);
    } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException | NoSuchPaddingException
            | IllegalBlockSizeException | BadPaddingException | IOException e) {
        Log.e(TAG, String.format("decrypt: 数据解密异常 , 原始数据: %s,密钥: %s,e: %s " , message, privateKey, e));
    }
    return null;
}




/**
 * RSA私钥解密
 *
 * @param message    加密字符串
 * @param privateKey 私钥
 * @return 铭文
 */

public static String decrypt2(String message, String privateKey) {
    try {
        if (message.contains(" ")) {
            message = message.replaceAll(" ", "+");
        }
        //base64编码的私钥
        final byte[] decoded = Base64.decode(privateKey.getBytes(StandardCharsets.UTF_8),0);


      //  final byte[] decoded = Base64Utils.decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        //64位解码加密后的字符串
        final byte[] inputByte = Base64.decode(message.getBytes(StandardCharsets.UTF_8),0);
        //密文
        final int len = inputByte.length;
        //偏移量
        int offset = 0;
        //段数
        int i = 0;
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (len - offset > 0) {
            byte[] cache;
            if (len - offset > 128) {
                cache = cipher.doFinal(inputByte, offset, 128);
            } else {
                cache = cipher.doFinal(inputByte, offset, len - offset);
            }
            bos.write(cache);
            i++;
            offset = 128 * i;
        }
        bos.close();

        return new String(bos.toByteArray(),StandardCharsets.UTF_8);
    } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException
            | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | IOException e) {
        Log.e(TAG, String.format("decrypt: 数据解密异常 , 原始数据: %s,密钥: %s,e: %s " , message, privateKey, e));
    }
    return null;
}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145921.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 交换机zone 的概念 和交换机指令「建议收藏」

    交换机zone 的概念 和交换机指令「建议收藏」配置Zone需要涉及到三个对象的配置Alias,Zone,Configuration。Alias可以把设备的WWN或Domain,Port声明为Alias,用于更好更直观的标示设备。使用Alias的主要目的是方便用户的使用,想象一下记住一个人的身份证号和名字的区别就可以明白其中的道理,使用Alias就想给设备启名字一样。声明Alias的另外一个益处是便于Zone中成员的更换。当Zone

    2022年5月21日
    38
  • Longest Common Prefix_LeetCode

    Longest Common Prefix_LeetCode1.思路:求strs数组的长度,当len==0,len==1分开考虑;i从1-min_len,以strs[0][i]作为对照,一旦出现strs[j][i]!=strs[0][i],结束循环,则输出之前判断好了的字符串。 classSolution:deflongestCommonPrefix(self,strs):""":typestrs…

    2022年5月6日
    44
  • LSD_SLAM「建议收藏」

    LSD_SLAM「建议收藏」LSDSLAM1.Overview三大模块2.Posetracking2.1直接法2.2LSD的直接法3.Depthmapping3.1Keyframeselection3.2DepthMapCreation(DepthMapPropagation)3.3DepthMapRefinement3.3.1参考图像帧选取3.3.2立体匹配策略3.3.3不确定性估…

    2022年6月6日
    23
  • html中div滚动条设置,DIV滚动条属性及样式设置方式「建议收藏」

    html中div滚动条设置,DIV滚动条属性及样式设置方式「建议收藏」这里向大家描述一下DIV滚动条属性及样式设置,所谓DIV滚动条,就是利用DIV标签,在里面嵌入CSS样式表,加入overflow的属性值,这样,当div所规范的区域内的内容达到一定程序时,滚动条就派上用场。DIV滚动条属性及样式设置所谓DIV滚动条,就是利用DIV标签,在里面嵌入CSS样式表,加入overflow的属性值,这样,当div所规范的区域内的内容达到一定程序时,滚动条就派上用场。其功能大…

    2022年7月12日
    49
  • Java集合篇:ConcurrentHashMap详解(JDK1.8)

    Java集合篇:ConcurrentHashMap详解(JDK1.8)

    2021年10月4日
    38
  • 详细解读Spatial Transformer Networks(STN)-一篇文章让你完全理解STN了

    详细解读Spatial Transformer Networks(STN)-一篇文章让你完全理解STN了目录STN的作用1.1灵感来源1.2什么是STN?STN的基本架构Localisationnet是如何实现参数的选取的?3.1实现平移3.2实现缩放3.3实现旋转3.4实现剪切3.5小结Gridgenerator实现像素点坐标的对应关系4.1为什么会有坐标的问题?4.2仿射变换关系Sampler实现坐标求解的可微性5.1小数

    2022年10月19日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号