加密解密算法之RC4

本文介绍了如何使用Python实现一种基于秘钥流的对称加密算法,包括KSA(Key Scheduling Algorithm)和PRGA(Pseudo-Random Generation Algorithm),并展示了如何生成密钥流、加密和解密过程。
摘要由CSDN通过智能技术生成

基于秘钥流加密的对称算法
python算法实现

import codecs
MOD = 256
def KSA(key):
	key_length=len(key)
	S=list(range(MOD)) #[0,1,2,...,255]
	j=0
	for i in range(MOD):
		j=(j+S[i]+key[i%key_length])%MOD
		S[i],S[j]=S[j],S[i] #swap values
	return S
def PRGA(S):
	i=0
	j=0
	while True:
		i=(i+1)%MOD
		j=(j+S[i])%MOD
		S[i],S[j]=S[j],S[i] #swap values
		K=S[(S[i]+S[j])%MOD]
		yield K
def get_keystream(key):
	S=KSA(key)
	return PRGA(S)
def encrypt_logic(key,text):
	key=[ord(c) for c in key]
	#If key is in hex
	#key=codecs.decode(key,'hex_codec')
	#key=[c for c in key]
	keystream=get_keystream(key)

	res=[]
	for c in text:
		val=("%02X" % (c^next(keystream))) #XOR and taking hex
		res.append(val)
	return ''.join(res)
def encrypt(key,plaintext):
	plaintext=[ord(c) for c in plaintext]
	return encrypt_logic(key,plaintext)
def decrypt(key,ciphertext):
	ciphertext=codecs.decode(ciphertext,'hex_codec')
	res=encrypt_logic(key,ciphertext)
	return codecs.decode(res,'hex_codec').decode('utf-8')

def main():
	key='not-so-random-key'
	plaintext='Good work! Your implementation is correct' #plaintext
	ciphertext=encrypt(key,plaintext)
	print('plaintext:',plaintext)
	print('ciphertext:',ciphertext)
	ciphertext='2D7FEE79FFCE80B7DDB7BDA5A7F878CE298615476F86F3B890FD4746BE2D8F741395F884B4A35CE979'
	decrypted=decrypt(key,ciphertext)
	print('decrypted:',decrypted)
	if plaintext==decrypted:
		print('Congrats ! You made it.')
	else:
		print('Shit! You pooped your pants ! .-.')
if __name__=='__main__':
	main()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值