Having fun with numbers & Python – Randomization & Shuffling – Stream Cipher

import sys,time
def hexs(s):
	o = ""
	for c in s:
		h = hex(ord(c))[2:]
		if (len(h) < 2):
			h = ("0" + h)
		if (o != ""):
			o += ":"
		o += h
	return o
def nice(s):
	o = ""
	for i in range(0, len(s)):
		if (i > 0):
			if ((i % 16) == 0):
				o += "\n  "
			else:
				o += ":"
		t = str(s[i])
		while (len(t) < 3):
			t = ("0" + t)
		o += t
	return o
def rnds():
	n = 2; s = ""
	while ((int(time.time()) % n) != 0):
		pass
	while (len(s) != 32):
		time.sleep(1)
		r = 0
		while ((int(time.time()) % n) != 0):
			r = (r + 1)
		#sys.stderr.write("r="+str(r)+"\n");break
		s = (s + chr((r >> 8) & 0xff) + chr(r & 0xff))
	return s
if (len(sys.argv) < 2):
	h = rnds()
	sys.stderr.write("k="+hexs(h)+"\n")
else:
	def keys(k):
		s = []
		for x in range(0, 256):
			s.append(x)
		for y in range(0, len(k)):
			l = ord(k[y])
			for x in range(0, 256):
				t = s[x] ; s[x] = s[l] ; s[l] = t
				l = ((l + x) % 256)
		return s
	s = keys(sys.argv[1])
	if (len(sys.argv) > 2):
		sys.stderr.write("s="+nice(s)+"\n\n")
	def ciph(m, s, z):
		j = 0; o = ""
		for y in range(0, len(m)):
			l = ord(m[y])
			c = (l ^ s[y % 256])
			o += chr(c)
			i = l
			if (z == "d"):
				i = c
			j = ((j ^ i) % 256)
			for x in range(0, 256):
				t = s[x] ; s[x] = s[j] ; s[j] = t
				j = ((j + x) % 256)
		return o
	if (len(sys.argv) < 3):
		m = sys.stdin.read()
		z = "d"
	else:
		m = sys.argv[2]
		z = "e"
	o = ciph(m, s, z)
	if (len(sys.argv) > 2):
		sys.stderr.write("m="+hexs(o)+"\n")
	sys.stdout.write(o)

$ clear ; echo ; python fun.py ; python fun.py ; echo ; python fun.py key msg | python fun.py key ; echo

k=74:ed:3c:1d:62:72:92:61:3c:27:f8:7c:c4:98:92:47:0d:18:c0:47:a6:44:b6:13:19:5c:90:30:4b:23:cf:12
k=fd:e7:4d:1d:c7:b0:a6:d9:45:0e:c9:68:95:35:46:e9:08:e9:8c:4f:53:42:9d:29:7b:30:65:f6:cd:00:ae:f6

s=054:166:020:190:252:207:029:030:042:098:156:055:041:108:058:032
  073:208:253:242:115:250:053:106:192:168:087:173:045:161:124:186
  163:049:162:067:040:096:086:039:057:023:100:216:203:123:217:175
  248:107:224:131:038:172:014:011:085:003:214:149:110:215:159:129
  046:125:144:043:077:126:150:167:200:169:097:153:188:201:071:254
  246:244:080:184:232:010:006:176:241:183:019:027:118:090:104:065
  000:033:210:220:236:234:063:205:048:155:095:133:218:050:022:158
  130:068:221:170:202:079:213:101:164:111:099:074:034:239:082:238
  031:181:092:230:088:017:007:251:083:193:051:245:237:209:064:070
  016:139:013:037:113:180:119:009:191:148:026:189:136:059:142:233
  056:160:243:135:076:165:012:035:222:212:231:084:249:061:152:093
  255:015:174:178:223:102:052:177:021:062:117:028:225:105:025:069
  121:002:227:122:143:047:134:137:146:219:194:060:005:089:044:140
  182:247:147:145:179:198:075:081:138:094:109:141:151:116:187:127
  103:128:001:132:036:154:066:112:078:196:229:004:226:211:206:199
  091:072:171:008:114:228:197:157:240:120:185:235:018:204:195:024

m=5b:c4:90
msg

Leave a comment