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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ghost备份还原详细步骤_ghost一键备份还原

    ghost备份还原详细步骤_ghost一键备份还原注意点1:整个过程中不可动鼠标,使用键盘和触摸板操作。开始备份或还原后中不要动键盘备份从大白菜系统盘等方法进入GHOST依次进入Local→Partition(分区)→ToImage(到镜像文件)选择备份分区所在磁盘选择分区选择储存分区,写文件名字注意点2:移动备份后的文件极易造成文件的损坏,所以这里的位置一定要选好,之后不要移动位置选择压缩率(一般…

    2025年9月19日
    4
  • navicat 15.0.25激活码【2022最新】

    (navicat 15.0.25激活码)好多小伙伴总是说激活码老是失效,太麻烦,关注/收藏全栈君太难教程,2021永久激活的方法等着你。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html40ZKSWCX8G-eyJsaWNlbnNlSW…

    2022年4月2日
    200
  • rabbitmq集群搭建「建议收藏」

    rabbitmq集群搭建「建议收藏」一、基础安装前提:三个节点都主机映射,关防火墙网络,配好yum(后边出错,主机名和映射要对应)1.安装(三个节点)2.mq1启动rabbitmq服务查看状态3.配置界面访问4.使用界面查看(端口15672,默认帐户和密码guest)二、配置rabbitmq集群服务1.先构建erlang集群①复制cookie认证②配置节点加入集群(顺序很重要,解决报错看)123的顺序停止321的顺序启动rabbitmq服务

    2025年10月25日
    3
  • Win10 桌面美化

    Win10 桌面美化Win10桌面美化最近发现了几款Win10界面美化的软件,看了看别人家的Win10操作界面,瞬间觉得自己的low了,关键是赏心悦目啊!废话不多说,先看看我原来桌面和美化后的桌面对比图原始桌面美化桌面1.安装RocketDockRocketDock可以提供类似macos的操作系统图标特效,打开安装包进行安装,完毕后启动得到效果如下:可以发现切换效果与mac类似,他默认的主题是C…

    2022年4月25日
    36
  • armv7和arm64区别(armv7s)

    目前ios的指令集有以下几种:armv6iPhoneiPhone2iPhone3G第一代和第二代iPodToucharmv7iPhone4iPhone4Sarmv7siPhone5iPhone5Carm64iPhone5SiPhone6iPhone6+================================================…

    2022年4月11日
    91
  • 基于 Laravel-Admin 在十分钟内搭建起功能齐全的后台模板

    基于 Laravel-Admin 在十分钟内搭建起功能齐全的后台模板

    2021年10月21日
    36

发表回复

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

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