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;
}

}

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • WPF WrapPanel

    WPF WrapPanelWrapPanel布局面板将各个控件从左至右按照行或列的顺序罗列,当长度或高度不够是就会自动调整进行换行,后续排序按照从上至下或从右至左的顺序进行。Orientation——根据内容自动换行。当Horizontal选项看上去类似于Windows资源管理器的缩略图视图:元素是从左向右排列的,然后自上至下自动换行。Vertical选项看上去类似于Windows资源管理器的列表视图:元素是从上…

  • 搭建备份服务器

    搭建备份服务器一、rsync的特性rsync的特性:1、支持拷贝特殊文件,设备等2、可以有排除指定文件或者目录同步的功能,相当于tar的排除功能3、可以做到保持源文件或目录的权限、时间、软硬连接、属主

  • 大数据管理与应用专业总结笔记

    大数据管理与应用专业总结笔记大数据管理与应用专业:数据科学教育特点:不仅依赖于传统的信息管理于信息系统专业,更依赖于计算机、数学、统计等学科。大数据专业十一门涉及广泛的交叉性的学科。大数据时代的下的理念(维克托·迈尔·舍恩伯格):一是更相关性而不是因果性;二是更关注数据的纷繁复杂,而不是数据的精准;三是全部数据,而不是抽样数据。维克托·迈尔·舍恩伯格:维克托·迈尔-舍恩伯格是十余年潜心研究数据科学的技术权威,是最早洞见大数据时代发展趋势的数据科学家之一,也是最受人尊敬的权威发言人之一。**目前的形势:**目前国内新增院校还不多

  • java map是有序的吗_java中map遍历

    java map是有序的吗_java中map遍历|背景在调用接口A的时候,传给接口A的参数是通过调用接口B返回然后再重新封装的。接口A是需要验签,也就是说传给接口A的所有参数一定要是按照接口B返回的固有顺序。问题出现了!!!接口B返回的字段是数组类型ClassX[],传给接口A的字段是JSON字符串。我将数组ClassX[]遍历,然后把key,value重新传入了一个Map,而这个Map是newHashMap产生的。最后调……

  • APC 注入

    APC注入APC介绍APC(AsynchronousProcedureCalls,异步过程调用),APC是函数在特定的线程被异步执行。在Windows中APC是一种并发机制,用于异步的IO或

    2021年12月13日
  • SQL Server 中关于EXCEPT和INTERSECT的使用方法

    SQL Server 中关于EXCEPT和INTERSECT的使用方法

    2021年11月30日

发表回复

您的电子邮箱地址不会被公开。

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