java&javascript自定义加密数据传输代码示例

2025-05-29 0 34

在开发应用过程中,客户端与服务端经常需要进行数据传输,涉及到重要隐私信息时,开发者自然会想到对其进行加密,即使传输过程中被“有心人”截取,也不会将信息泄露。对于加密算法,相信不少开发者也有所耳闻,比如MD5加密,Base64加密,DES加密,AES加密,RSA加密等等。。可利用亦或,并,且,等进行简单加密。

示例代码中使用的^运算key=0x01,可自定义自己的规则。定义自己的运算,保证可逆数据不丢失即可。key也可定义,动态key。

java代码

?

1

2

3

4

5

6

7

8

9

10

11

12
public static String myEncode(String str) throws UnsupportedEncodingException {

byte[] strBytes = str.getBytes("utf-8");

byte[] newStrByte = new byte[strBytes.length];

for (int i = 0; i < strBytes.length; i++) {

newStrByte[i] = (byte) (strBytes[i] ^ 0x01);

}

return new String(newStrByte);

}

String encodeStr = myEncode("IdmmnA\\"547''+) ')%\\"A ^*((!Vnsme");

System.out.println(encodeStr);

javascript代码

获取utf-8的byte

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
function toUTF8Array(str) {

var utf8 = [];

for (var i=0; i < str.length; i++) {

var charcode = str.charCodeAt(i);

if (charcode < 0x80) utf8.push(charcode);

else if (charcode < 0x800) {

utf8.push(0xc0 | (charcode >> 6),

0x80 | (charcode & 0x3f));

}

else if (charcode < 0xd800 || charcode >= 0xe000) {

utf8.push(0xe0 | (charcode >> 12),

0x80 | ((charcode>>6) & 0x3f),

0x80 | (charcode & 0x3f));

}

// surrogate pair

else {

i++;

// UTF-16 encodes 0x10000-0x10FFFF by

// subtracting 0x10000 and splitting the

// 20 bits of 0x0-0xFFFFF into two halves

charcode = 0x10000 + (((charcode & 0x3ff)<<10)

| (str.charCodeAt(i) & 0x3ff));

utf8.push(0xf0 | (charcode >>18),

0x80 | ((charcode>>12) & 0x3f),

0x80 | ((charcode>>6) & 0x3f),

0x80 | (charcode & 0x3f));

}

}

return utf8;

}

获取byte并进行^计算

?

1

2

3

4

5

6

7

8

9
bytes=stringToAsciiByteArray(str);

for (var i = 0; i < bytes.length; i++) {

var newByte = (bytes[i]^0x01);

// newByte = (newByte^0x01);

console.log(String.fromCharCode(newByte));

encodeStr += String.fromCharCode(newByte);

};

console.log(encodeStr);

总结

以上就是本文关于java&javascript自定义加密数据传输代码示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。

原文链接:http://blog.csdn.net/mendeliangyang/article/details/50108071

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java&javascript自定义加密数据传输代码示例 https://www.kuaiidc.com/113837.html

相关文章

发表评论
暂无评论