import java.util.Base64;

// 加密方法 - deviceId 和二维码密码
public static String encrypt(long id, String inputString) {
    String idString = String.valueOf(id);
    StringBuilder encryptedString = new StringBuilder();

    // 遍历字符串的每个字符
    for (int i = 0; i < inputString.length(); i++) {
        char c = inputString.charAt(i);

        // 生成一个随机因子
        int randomFactor = (int) (Math.random() * 100);

        // 将字符与id字符串的对应字符和随机因子进行异或运算
        char encryptedChar = (char) (c ^ idString.charAt(i % idString.length()) ^ randomFactor);

        // 将异或运算后的字符加入到加密字符串中
        encryptedString.append(encryptedChar);
    }

    // 将id、随机因子和加密字符串进行拼接
    String combinedString = id + ":" + System.currentTimeMillis() + ":" + encryptedString.toString();

    // 使用Base64编码加密字符串,得到最终加密结果
    return Base64.getEncoder().encodeToString(combinedString.getBytes());
}

// 解密方法 - deviceId 和二维码密码
public static DeviceEntity decrypt(String encryptedString) {
    // 使用Base64解码加密字符串
    byte[] decodedBytes = Base64.getDecoder().decode(encryptedString);
    String combinedString = new String(decodedBytes);

    // 分割id、时间戳和加密字符串
    String[] parts = combinedString.split(":");
    long id = Long.parseLong(parts[0]);
    long timestamp = Long.parseLong(parts[1]);
    String encryptedContent = parts[2];

    StringBuilder decryptedString = new StringBuilder();

    // 遍历加密字符串的每个字符
    for (int i = 0; i < encryptedContent.length(); i++) {
        char c = encryptedContent.charAt(i);

        // 获取随机因子的值
        int randomFactor = (int) (timestamp % 100);

        // 将字符与id字符串的对应字符和随机因子进行异或运算,得到解密后的字符
        char decryptedChar = (char) (c ^ String.valueOf(id).charAt(i % String.valueOf(id).length()) ^ randomFactor);

        // 将解密后的字符加入到解密字符串中
        decryptedString.append(decryptedChar);
    }

    // 返回解密结果
    DeviceEntity deviceEntity = new DeviceEntity();
    deviceEntity.setDeviceId(id);
    deviceEntity.setQrCode(decryptedString.toString());
    return deviceEntity;
}

该方法首先将 deviceId 和二维码密码进行异或运算加密,然后使用 Base64 编码将加密后的字符串进行编码。解密时,使用 Base64 解码获取原始字符串,再进行异或运算解密。

该方法的优点是简单易懂,实现起来比较容易。缺点是安全性较低,容易被破解。

建议使用更安全的加密算法,例如 AES 或 RSA,来提高安全性。

Java deviceId 和二维码密码加密解密方法

原文地址: http://www.cveoy.top/t/topic/ZRF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录