加密数据:(自己随便找)
加密前图像:
自己随便找一个
加密后图像:
自己跑代码生成
加密代码:
from PIL import Image
def get_key(strr):
tmp = strr
f = open(tmp,'rb')
str = ""
s = f.read()
for i in range(len(s)):
str = str + bin(s[i]).replace("0b","").zfill(8)
#str = str + " "
f.close()
#print(str)
return str
def func(str1,str2,str3):
im = Image.open(str1)
width = im.size[0]
height = im.size[1]
print("Width: " + str(width))
print("Height: " + str(height))
key = get_key(str2)
# 信息编码解码无误
print(key)
#for i in range(0,len(key),8):
# stra = int(key[i:i+8],2)
# print(chr(stra))
keylen = len(key)
# print(keylen)
count = 0
for h in range(0,height):
for w in range(0,width):
pixel = im.getpixel((w,h))
a = pixel[0]
b = pixel[1]
c = pixel[2]
if count == keylen:
break
a = a - a%2 + int(key[count])
count += 1
if count == keylen:
im.putpixel((w,h),(a,b,c))
break
b = b - b%2 + int(key[count])
count += 1
if count == keylen:
im.putpixel((w,h),(a,b,c))
break
c = c - c%2 + int(key[count])
count += 1
if count == keylen:
im.putpixel((w,h),(a,b,c))
break
im.putpixel((w,h),(a,b,c))
if count == keylen:
break
im.save(str3)
old = "D:\课程\电子商务安全\LSB\照片.jpg"
new = "D:\课程\电子商务安全\LSB\照片_LSB.png"
enc = "D:\课程\电子商务安全\LSB\information.txt"
func(old,enc,new)
加密检验(这个文件可以自己上网找一下,一个简单的java小程序,别人写的):
解密代码:
from PIL import Image
def func(le,str1,str2):
a = ""
b = ""
im = Image.open(str1)
length = le*8
width = im.size[0]
height = im.size[1]
count = 0
for h in range(0,height):
for w in range(0,width):
pixel = im.getpixel((w,h))
b = b + str(int(pixel[count%3]) % 2)
if count == length:
break
count += 1
b = b + str(int(pixel[count%3]) % 2)
if count == length:
break
count += 1
b = b + str(int(pixel[count%3]) % 2)
if count == length:
break
count += 1
if count == length:
break
# print(b)
message = ""
for i in range(0,len(b),8):
stra = int(b[i:i+8],2)
message += chr(stra)
print(message)
f = open(str2,'w')
f.write(message)
le = 8000
new = "D:\课程\电子商务安全\LSB\照片_LSB.png"
message = "D:\课程\电子商务安全\LSB\message.txt"
func(le,new,message)
解密结果:(跟加密一样)
反思与总结:
加密要使用LSB算法使用png、bmp等格式,使用而jpg格式的图片加密后,依旧使用jpg格式保存,图像会在处理过程中被压缩,造成信息丢失。
之前误以为是代码逻辑写错了,后来才发现是生成的图片格式不对。