Android RSA&SHA加密

前言

RSA允许你选择公钥的大小。512位的密钥被视为不安全的;768位的密钥不用担心受到除了国家安全管理(NSA)外的其他事物的危害;1024位的密钥几乎是安全的。RSA在一些主要产品内部都有嵌入,像 Windows、网景 Navigator、 Quicken和 Lotus Notes。

RSA公开密钥密码体制的原理是:根据数论,寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

RSA算法的具体描述如下:

(1)任意选取两个不同的大素数p和q计算乘积

(2)任意选取一个大整数e,满足

整数e用做加密钥(注意:e的选取是很容易的,例如,所有大于p和q的素数都可用);

(3)确定的解密钥d,满足

扫描二维码关注公众号,回复: 12510645 查看本文章

是一个任意的整数;所以,若知道e和

,则很容易计算出d;

(4)公开整数n和e,秘密保存d;

(5)将明文m(m<n是一个整数)加密成密文c,加密算法为

(6)将密文c解密为明文m,解密算法为

然而只根据n和e(注意:不是p和q)要计算出d是不可能的。因此,任何人都可对明文进行加密,但只有授权用户(知道d)才可对密文解密 。

1.在线加密解密

https://www.bejson.com/enc/rsa/

https://www.bejson.com/enc/sha/

2.RSA加密

RSA加密需要密钥,具体密钥字符串需要自己定义

public static String getRSAPublidKeyBybase64(String KEY, String text) {
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android上使用
        byte[] publicBytes = Base64.decode(KEY.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException |
            InvalidKeyException | BadPaddingException | IllegalBlockSizeException |
            InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return "";
}

3.SHA加密

SHA加密类型

输入加密类型时:SHA-512

/**
 * SHA加密
 * @param strText 待加密的字符串
 * @param strType 加密类型
 * @return 加密后的字符串
 */
public static String SHA(final String strText, final String strType) {
    // 返回值
    String strResult = null;
    // 是否是有效字符串
    if (strText != null && strText.length() > 0) {
        try {
            // SHA 加密开始
            // 创建加密对象 并傳入加密類型
            MessageDigest messageDigest = MessageDigest.getInstance(strType);
            // 传入要加密的字符串
            messageDigest.update(strText.getBytes());
            // 得到 byte 類型结果
            byte[] byteBuffer = messageDigest.digest();
            // 將 byte 轉換爲 string
            StringBuilder strHexString = new StringBuilder();
            // 遍歷 byte buffer
            for (byte b : byteBuffer) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            // 得到返回結果
            strResult = strHexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    return strResult;
}

猜你喜欢

转载自blog.csdn.net/mozushixin_1/article/details/113178753