程序的加密解密

8.23

package com.zhongruan;

public class Test4 {

public static void main(String[] args) {
  /*  String hualili = Encrypt("hualili", 123);
    System.out.println(hualili);

    String encrypt = Decrypt(hualili, 123);
    System.out.println(encrypt);*/


    String username="hualili";
    String encrypt = Encrypt(username, 1);
    System.out.println(encrypt);
    String decrypt = Decrypt(encrypt, 1);
    System.out.println(decrypt);

}

private static int C1 = 52845;
private static int C2 = 22719;

// 加密函数

public static String Encrypt(String S, int Key) {

    StringBuffer Result = new StringBuffer();
    StringBuffer str;
    int i, j;


    for (i = 0; i < S.length(); i++) {
        // 依次对字符串中各字符进行操作
        Result.append((char) (S.charAt(i) ^ (Key >> 8))); // 将密钥移位后与字符异或
        Key = ((byte) Result.charAt(i) + Key) * C1 + C2; // 产生下一个密钥
    }
    S = Result.toString();
    System.out.println("密文中间值:" + S);
    Result = new StringBuffer();
    for (i = 0; i < S.length(); i++) // 对加密结果进行转换
    {
        j = (int) S.charAt(i); // 提取字符
        // 将字符转换为两个字母保存
        str = new StringBuffer(); // 设置str长度为2
        str.append((char) (65 + j / 26));//这里将65改大点的数例如256,密文就会变乱码,效果更好,相应的,解密处要改为相同的数
        str.append((char) (65 + j % 26));
        Result.append(str);
    }
    return Result.toString();
}

// 解密函数

public static String Decrypt(String S, int Key) {
    StringBuffer Result = new StringBuffer();
    StringBuffer str;
    int i, j;


    for (i = 0; i < S.length() / 2; i++) // 将字符串两个字母一组进行处理
    {
        j = ((int) S.charAt(2 * i) - 65) * 26;//相应的,解密处要改为相同的数

        j += (int) S.charAt(2 * i + 1) - 65;
        Result.append((char) j);
    }
    S = Result.toString(); // 保存中间结果
    System.out.println("原文中间值:" + S);
    Result = new StringBuffer();
    for (i = 0; i < S.length(); i++) // 依次对字符串中各字符进行操作
    {
        Result.append((char) (S.charAt(i) ^ (Key >> 8))); // 将密钥移位后与字符异或
        Key = ((byte) S.charAt(i) + Key) * C1 + C2; // 产生下一个密钥
    }
    return Result.toString();
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值