补充一种实用的跨语言加密的java版本

加密算法的介绍
此算法源码最初由 Borland Delphi 编写,原作者似乎是 Allen Bauer,代码如下。
const   cMulKey = 52845;
   cAddKey = 11719;function Decrypt(const S: String; Key: Word): String;
var
  I: byte;
begin
  SetLength(Result, Length(S));
  for I := 1 to Length(S) do
  begin
    Result[I] := char(byte(S[I]) xor (Key shr 8));
    Key := (byte(S[I]) + Key) * cMulKey + cAddKey;
  end;
end;
function Encrypt(const S: String; Key: Word): String;
Var
  I: byte;
begin
  SetLength(Result, Length(S));
  for I := 1 to Length(S) do
  begin
    Result[I] := char(byte(S[I]) xor (Key shr 8));
    Key := (byte(Result[I]) + Key) * cMulKey + cAddKey;
  end;
end;
一位博主已经将此加密方法用golang、C#、Lua语言重写了, 需要的请点击下方链接查看。
点击跳转
这里补充java版本
注: 因为java进行运算时会统一将数据转成int32, 然后在进行运算, 所以需要将数据重新转换成int16。
@Slf4jpublic class SimpleEncryptTool {
    private static final short mulKey = (short) 52845;
    private static final short addKey = 11719;
    private static final short encryptKey = 12345;
    public static String encrypt(String data) {
        short key = encryptKey;
        //先转字节数组, 防止中文2字节的问题
        byte[] dataByte = data.getBytes();
        byte[] temp = new byte[dataByte.length];
        for (int i = 0; i < dataByte.length; i++) {
            byte single = (byte) (dataByte[i] ^ (key >> 8));
            temp[i] = single;
            key += (single & 0xff);
            key *= mulKey;
            key += addKey;
        }
        return Base64.getEncoder().encodeToString(temp);
    }
    public static String decrypt(String data) {
        short key = encryptKey;
        //记得修改转换编码
        byte[] dataByte = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        byte[] temp = new byte[dataByte.length];
        for (int i = 0; i < dataByte.length; i++) {
            byte single = (byte) (dataByte[i] ^ (key >> 8));
            temp[i] = single;
            key += (dataByte[i] & 0xff);
            key *= mulKey;
            key += addKey;
        }
        return new String(temp, StandardCharsets.UTF_8);
    }
    public static void main(String[] args) {
        String data = "少年";
        log.info("转换: {}", data);
        String encryptData = encrypt(data);
        log.info("encryptData: {}", encryptData);
        String decryptData = decrypt(encryptData);
        log.info("decryptData: {}", decryptData);
    }
}
以上是 补充一种实用的跨语言加密的java版本 的全部内容, 来源链接: utcz.com/z/515576.html
