void main()
{
char key[]="abcd"
RC4_KEY stKey
BYTE d1[4]={0x11,0x22,0x33,0x44}
//加密
RC4Init(key,strlen(key),&stKey)
RC4Works(d1,4,&stKey)
//解密
RC4Init(key,strlen(key),&stKey)
RC4Works(d1,4,&stKey)
}
import javax.crypto.Cipherimport javax.crypto.spec.SecretKeySpec
import javax.xml.bind.DatatypeConverter
public class Test {
public static void main(String[] args) throws Exception{
Cipher cipher=Cipher.getInstance("RC4")
String pwd="123456"
String ptext="Hello World 你好"
SecretKeySpec key=new SecretKeySpec(pwd.getBytes("UTF-8"), "RC4")
cipher.init(Cipher.ENCRYPT_MODE, key)
byte[] cdata =cipher.update(ptext.getBytes("UTF-8"))
//解密
cipher.init(Cipher.DECRYPT_MODE, key)
byte[] ddata =cipher.update(cdata)
System.out.println("密码: "+pwd)
System.out.println("明文: "+ptext)
System.out.println("密文: "+DatatypeConverter.printHexBinary(cdata))
System.out.println("解密文: "+new String(ddata,"UTF-8"))
}
} 密码: 123456
明文: Hello World 你好
密文: 489D120B4B1342F30D5B46961D83E12B4875
解密文: Hello World 你好
RC4已经不太安全,只能用于一般加密,不能用于金融等紧要场合。
#include <stdio.h>#include <stdlib.h>
#include <string.h>
typedef unsigned long ULONG
void rc4_init(unsigned char *s, unsigned char *data,unsigned Len) { //初始化函数
int i,j
unsigned char k[256] = {0},tmp
for(i = 0i <256i++) {
s[i] = i
k[i] = data[i%Len]
}
for(i = 0i <256i++) {
j = (j + s[i] + k[i])%Len
tmp = s[i]
s[i] = s[j]//交换s[i]和s[j]
s[j] = tmp
}
}
void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len) { //加解密
int i = 0, j = 0, t = 0
unsigned long k = 0
unsigned char tmp
for(k = 0k <Lenk++) {
i = (i + 1)%256
j = (j + s[i])%256
tmp = s[i]
s[i] = s[j]//交换s[x]和s[y]
s[j] = tmp
t = (s[i] + s[j])%256
Data[k] ^= s[t]
}
}
int main() {
unsigned char s[256] = {0},st[256] = {0}//S-box
char key[256] = "just for test"
char pData[512] = "待加密数据Data"
ULONG len = strlen(pData)
printf("pData = %s\n",pData)
printf("key = %s, length = %d\n\n",key,strlen(key))
rc4_init(s,(unsigned char *)key,strlen(key))//初始化
printf("完成对S[i]的初始化,如下:\n\n")
for(int i = 0i <256i++) {
printf("%-3d ",s[i])
}
printf("\n\n")
for(i = 0i <256i++) { //用st[i]暂时保留经过初始化的s[i],很重要的!!!
st[i] = s[i]
}
printf("已经初始化,现在加密:\n\n")
rc4_crypt(s,(unsigned char *)pData,len)//加密
printf("pData = %s\n\n",pData)
printf("已经加密,现在解密:\n\n")
rc4_init(s,(unsigned char *)key,strlen(key)) //初始化密钥
rc4_crypt(st,(unsigned char *)pData,len)//解密
printf("pData = %s\n\n",pData)
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)