信息隐藏课程之简单的LSB最低位隐写

# -*- coding: utf-8 -*-
_author_ = 'xiao_lu'
#取出RGB 值得 lsb  替换
import Image
import matplotlib.pyplot as plt

#得到加密文字的二进制形式
def plus(str):
   return str.zfill(8)
def get_key():
   f = file("D:\\zip1.txt", "r")
   str = ""
   s = f.read()
   print s
   for i in range(len(s)):
      str=str+ plus(bin(ord(s[i])).replace('0b', ''))
   print str
   f.closed
   return str
def mod(x,y):
    return x%y;

if __name__ == '__main__':
  im = Image.open("d:/lena.jpg")
  plt.subplot(1, 2, 1), plt.title('origin')
  plt.imshow(im), plt.axis('off')
  width = im.size[0]
  height = im.size[1]
  count = 0
  key = get_key()  #得到 文本信息
  #如果嵌入的文字过多导致载体不够大
  if width*height*3<len(key):
      print "please change the image"
      exit()
  #基于最低位lsb嵌入
  for h in range(0, height):
     for w in range(0, width):
        pixel = im.getpixel((w, h))
        a = pixel[0]#R
        b = pixel[1]#G
        c = pixel[2]#B
        if count == len(key):
            break
        #LSB 嵌入过程  替换最后一位
        if count%3==0:
            a= a-mod(a,2)+int(key[count])
        elif count%3==1:
            b = b- mod(b, 2) + int(key[count])
        else:
            c= c-mod(c,2)+int(key[count])
        im.putpixel((w,h),(a,b,c))
        count=count+1
     if count == len(key):#全部潜入完毕
         break
  plt.subplot(1, 2, 2), plt.title('now')#前后两个图片对比
  plt.imshow(im), plt.axis('off')
  plt.show()
  im.save(r"d:/lena_rgb.bmp")
  print "success\n"


解密过程


# -*- coding: utf-8 -*-
_author_ = 'xiao_lu'

import Image
def mod(x,y):
    return x%y;
#将得到的二进制串化成ASCII码
def toasc(str):
    return int(str, 2)
if __name__ == '__main__':
  a=""
  im = Image.open("d:/lena_rgb.bmp")
  f1 = file("D:\\zip1.txt", "r")
  s = f1.read()
  lenth = len(s)
  width = im.size[0]
  height = im.size[1]
  count = 0
  #直接提取最后一位 基于rgb三个图像
  for h in range(0, height):
       for w in range(0, width):
           pixel = im.getpixel((w, h))
           if count ==lenth*8:
               break
           if count%3==0:
               a = a+str((mod(int(pixel[0]),2)))
           elif count%3==1:
               a=a+str((mod(int(pixel[1]), 2)))
           else:
               a=a+str((mod(int(pixel[2]), 2)))
           count+=1
       if count == lenth*8:
           break
  print a#输出二进制
  print len(a)
  #将得到的明文写到文本
  with open("d:/zip2.txt","w") as f:
       for i in range(0,len(a),8):
           str = toasc(a[i:i+8])#化成ASCII码
           print chr(str)#输出明文
           f.write(chr(str))
           str =""
  f.closed


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值