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


相关推荐

  • 学习大数据要掌握哪些语言?哪些必备知识和技能呢?

    学习大数据要掌握哪些语言?哪些必备知识和技能呢?大数据是近五年兴起的行业,发展迅速,很多技术经过这些年的迭代也变得比较成熟了,同时新的东西也不断涌现,想要保持自己竞争力的唯一办法就是不断学习。但是,大数据需要学习什么?01思维导图下面的是我之前整理的一张思维导图,内容分成几大块,包括了分布式计算与查询,分布式调度与管理,持久化存储,大数据常用的编程语言等等内容,每个大类下有很多的开源工具。  02大数据需要的语言Ja…

    2022年5月6日
    45
  • latex换行不缩进

    latex换行不缩进缩进哪段就直接放在段首\noindent

    2022年5月14日
    45
  • ▲ Android 自定义搜索附近的动画

    ▲ Android 自定义搜索附近的动画

    2021年3月12日
    156
  • ES6数组去重的三个简单办法

    ES6数组去重的三个简单办法ES6数组去重的三个简单办法简单说一下利用ES6实现数组去重的三个办法。第一种:利用Map对象和数组的filter方法贴上相关代码打印后的结果通过打印我们发现,确实实现了我们想要的效果。那么下面简单来解释一下。1.Map对象是ES6提供的一个新的数据结构,其中has的办法是返回一个布尔值,表示某个值是否存在当前的Mp对象之中,set的办法是给Map对象设置key/value。2…

    2022年6月13日
    62
  • es6数组处理方法整理

    es6数组处理方法整理数组常用.push().pop().unshift().shift().splice(i,n)删除,原数组被从i删除n个元素,返回被删掉的元素.slice(start,end)获取子数组,原数组不变,返回切出来的元素.concat().split()字符串变数组.sort()排序.reverse()翻转遍历处理.map(callback)遍历处…

    2022年5月24日
    39
  • MySQL 全局锁、表锁和行锁「建议收藏」

    MySQL 全局锁、表锁和行锁

    2022年2月17日
    49

发表回复

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

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