1. 程式人生 > >LSB隱寫演算法

LSB隱寫演算法

LSB循序替換隱寫演算法
原理
首先將需要隱寫的檔案用二進位制流的方式讀取並儲存在字串S當中,然後順序提取BMP圖片的畫素點,每一個畫素點包含K(R、G、B)三種顏色,每一種顏色能夠嵌入1bit資訊,每一個畫素點就能夠嵌入3bit的資訊。
隱寫部分:

Kr = Kr – mod(Kr,2) + int(S[i])
Kg = Kg – mod(Kg,2) + int(S[i+1])
Kb = Kb – mod(Kb,2) + int(S[i+2])

提取部分:

    S = S + mod(Kr,2)
    S = S + mod(Kg,2)
    S = S + mod(Kb,2)

隱寫部分程式碼

# -*- coding: UTF-8 -*-
from PIL import Image

def plus(str):
    return str.zfill(8)

def get_key(strr):
    tmp = strr
    f = file(tmp,"rb")
    str = ""
    s = f.read()
    for i in range(len(s)):
        str = str+plus(bin(ord(s[i])).replace('0b',''))
    f.closed
    return str

def
mod(x,y):
return x%y; *str1為載體圖片路徑,str2為隱寫檔案,str3為加密圖片儲存的路徑* def func(str1,str2,str3): im = Image.open(str1) width = im.size[0] height = im.size[1] count = 0 key = get_key(str2) keylen = len(key) 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-mod(a,2)+int(key[count]) count+=1 if count == keylen: im.putpixel((w,h),(a,b,c)) break b =b-mod(b,2)+int(key[count]) count+=1 if count == keylen: im.putpixel((w,h),(a,b,c)) break c= c-mod(c,2)+int(key[count]) count+=1 if count == keylen: im.putpixel((w,h),(a,b,c)) break if count % 3 == 0: im.putpixel((w,h),(a,b,c)) im.save(str3)

提取部分程式碼

```
# -*- coding:UTF-8 -*-
from PIL import Image

def mod(x,y):
    return x%y;

def toasc(strr):
    return int(strr, 2)
*le為檔案的長度,str1為加密載體圖片的路徑,str2為提取檔案的儲存路徑*
def func(le,str1,str2):
    a=""
    b=""
    im = Image.open(str1)
    lenth = le*8
    width = im.size[0]
    height = im.size[1]

    for h in range(0, height):
        for w in range(0, width):
            pixel = im.getpixel((w, h))
            if count%3==0:
                count+=1
                b=b+str((mod(int(pixel[0]),2)))
                if count ==lenth:
                    break
            if count%3==1:
                count+=1
                b=b+str((mod(int(pixel[1]),2)))
                if count ==lenth:
                    break
            if count%3==2:
                count+=1
                b=b+str((mod(int(pixel[2]),2)))
                if count ==lenth:
                    break
        if count == lenth:
            break
    with open(str2,"wb") as f:
        for i in range(0,len(b),8):
            stra = toasc(b[i:i+8])
            f.write(chr(stra))
            stra =""
    f.closed

“`