## Implementation of LSB steganography based on MATLAB and python

What's the reason for this 2021-04-07 18:07:52
implementation lsb steganography based matlab

Embedding a string into a picture allows you to select pixels in order , You can also randomly select pixels . Let's implement each algorithm in turn .

## 1. Sequential embedding

Sequential embedding is simple , Traverse every pixel , Then embed the binary into the last bit, that is, the eighth bit .

To write a report , I also drew a flow chart , It's easy to understand ：

### 1.1 python edition

First of all, I use python Implemented a , It's mainly about matlab Not familiar with , utilize python3 Of PIL The library is still very simple to write . Just look at the code

``````# coding:utf-8
# python 3.6.6
from PIL import Image
import time
# Convert a string to binary
def str_convert_bin(s):
result = ''
for c in s:
b = bin(ord(c)).replace('0b', '')
b = '0'*(7-len(b))+b
result = result+b
return result
# Convert binary to string
def bin_convert_str(b):
str=''
# Put the binary string every 7 Bit splitting , Make a list
b1 = [b[i:i+7] for i in range(0, len(b), 7)]
for i in range(len(b1)):
b2 = chr(int(b1[i],2))
str = str+b2
return str
# Embed a binary string into a picture pixel B passageway im:Image()、bin1: Binary string to embed
def insert(im,bin1):
size = im.size
length = len(bin1)
k=0
flag=0
for i in range(size[0]):
for j in range(size[1]):
# im.getpixel((i,j)) Read pixels (i,j) Pixel value
pixel_b=bin(im.getpixel((i,j))[2]).replace('0b', '')
if pixel_b[-1:]<bin1[k]:
# im.putpixel((i,j),(x,y,z)) Set the pixels (i,j) Of RGB The value is (x,y,z)
im.putpixel((i,j),(im.getpixel((i,j))[0],im.getpixel((i,j))[1],im.getpixel((i,j))[2]+1))
if pixel_b[-1:]>bin1[k]:
im.putpixel((i,j),(im.getpixel((i,j))[0],im.getpixel((i,j))[1],im.getpixel((i,j))[2]-1))
k=k+1
if k==length:
flag=1
break
if flag==1:
break
print(" String embedding complete \n\n")
# Extract string im:Image()、length: Binary string length
def extract(im,length):
size = im.size
k=0
result=''
flag=0
for i in range(size[0]):
for j in range(size[1]):
pixel_b=bin(im.getpixel((i,j))[2]).replace('0b', '')
result=result+pixel_b[-1:]
k=k+1
if k==length:
flag=1
break
if flag==1:
break
print(" Extraction complete , The binary string is ：\n%s"%result)
str = bin_convert_str(result)
print(" convert network , The result is ：\n%s"%str)
def main():
test_str=input(" Please enter the string :\n")
result = str_convert_bin(test_str)
print(" The string to be embedded is converted to binary :\n%s"%result)
print(" Start embedding ....")
im = Image.open("2.bmp")
insert(im, result)
time.sleep(5)
print(" Start extracting strings ：")
extract(im, len(result))
if __name__=='__main__':
main()
Copy code ``````

result ：

### 1.2 matlab edition

Later, more complex steganography still needs to be used matlab, So it turns around matlab Well .

matlab No introduction , I also learn first and use first , The code is rough , Barely stick the code ：

``````% By gengyanqing
% LSB hide （ Order hidden ）
% You can hide numbers 、 Letter 、 English characters ex: hello,world.111
% jpg The distortion ！ use png/bmp
clear all;clc;
str=input(' Please enter the string you want to sneak in :','s'); % Receive string
str_bin_mat=dec2bin(str); % String to binary matrix
% Binary matrix to string
l_str_bin_mat=size(str_bin_mat); % Binary matrix
str_bin='';
for i=1:l_str_bin_mat(1)
for j=1:l_str_bin_mat(2)
str_bin=[str_bin,str_bin_mat(i,j)];
end
end
disp(' The binary form of the string to be embedded is ');
disp(str_bin);
% Check if it can be fully embedded
[l,w,h]=size(data);
if length(str_bin)>=l*w*h
error(' The character length exceeds !!!');
end
% Embedded programs
data1=data;
disp(' Start embedding ');
flag1=1; % Enter the binary length of the character , Judge whether the embedding is over
flag2=1;
flag3=1;
for i=1:l
if flag3==0
break
end
for j=1:w
if flag2==0
flag3=0;
break
end
for k=1:h
if flag1>length(str_bin)
disp('over');
flag2=0;
break
end
a=dec2bin(data1(i,j,k),8);% The number is binary
data1(i,j,k)=bin2dec([a(1:7),str_bin(flag1)]);% Binary addition , Take the decimal system
flag1=flag1+1;
end
end
end
% Save the picture
imwrite(data1,'1-2.png')
disp(' Embedding complete , Save as 1-2.png');
% Here is the extraction procedure
disp(' Start extracting ...')
[l,w,h]=size(data2);
str_bin1='';% Extracted binary string
locationx=[];
locationy=[];
locationxy=[];
m=length(str_bin);
flag1=1;
flag2=1;
flag3=1;
for i=1:l
if flag3==0
break
end
for j=1:w
if flag2==0
flag3=0;
break
end
for k=1:h
if flag1>length(str_bin)
flag2=0;
break
end
a=dec2bin(data2(i,j,k),8);% Decimal to binary
str_bin1=[str_bin1,a(8)];% Take the last number
flag1=flag1+1;
end
end
end
disp(' Extraction complete !');
disp(' The extracted binary string is ：');
disp(str_bin1);
disp(' Start conversion ...')
% Binary to string
str2='';
for q=1:length(str_bin1)/l_str_bin_mat(2)
w=str_bin1((q-1)*l_str_bin_mat(2)+1:q*l_str_bin_mat(2));%w For every seven
a=bin2dec(w); % Convert to decimal
if a>9
str2=[str2,char(a)];
end
if a<9
str2=[str2,a];
end
end
disp(' convert network ');
disp(' The final result is ：');
disp(str2);
Copy code ``````

You can embed characters , Numbers , Letter , give the result as follows ：

## 2. Random LSB Steganography

In fact, this is similar to the order , It's just traversing pixels , take （i,j) Change to random dots , We can write a random function to generate a random list X and Y, When it comes to embedding (i,j) We turn it into (X(i+j), Y(i+j)), Why not （X(i), Y(j)) Readers can think about （ It's not random ）.

I also drew a flow chart for this , But there seems to be a problem , Time is urgent. Let's do it for the time being .

Next, let's look at the functions that generate random lists randomxy.m：

``````% Randomly generate two lists
% l For the long ,w To be wide ,len_str_bin For embedding binary length ,key For random seeds
function [x,y]=randxy(l,w,len_str_bin,key)
% Set random seeds , Generating a random number
rand('seed',key);
disp('hhhhhhhhh');
x=randperm(l,len_str_bin);
y=randperm(w,len_str_bin);
%x = unique(x); % To reprocess
%y = unique(y) ;% To reprocess
end
Copy code ``````

Then look at the main code ：

``````% By gengyanqing
% LSB hide （ Random hiding ）
% You can hide numbers 、 Letter 、 English characters ex: hello,world.111
% jpg The distortion ！ use png/bmp
clear all;clc;
str=input(' Please enter the string you want to sneak in :','s'); % Receive string
str_bin_mat=dec2bin(str); % String to binary matrix
% Binary matrix to string
l_str_bin_mat=size(str_bin_mat); % Binary matrix
str_bin='';
for i=1:l_str_bin_mat(1)
for j=1:l_str_bin_mat(2)
str_bin=[str_bin,str_bin_mat(i,j)];
end
end
disp(' The binary form of the string to be embedded is ');
disp(str_bin);
% Check if it can be fully embedded
[l,w,h]=size(data);
if length(str_bin)>=l*w*h
error(' The character length exceeds !!!');
end
% Embedded programs
data1=data;
disp(' Start embedding ');
flag1=1; % Enter the binary length of the character , Judge whether the embedding is over
flag2=1;
flag3=1;
% call randxy function
[x,y]=randxy(l,w,length(str_bin),88);
for i=1:l
if flag3==0
break
end
for j=1:w
if flag2==0
flag3=0;
break
end
for k=1:h
if flag1>length(str_bin)
disp('over');
flag2=0;
break
end
a=dec2bin(data1(x(i+j),y(i+j),k),8);% The number is binary
data1(x(i+j),y(i+j),k)=bin2dec([a(1:7),str_bin(flag1)]);% Binary addition , Take the decimal system
flag1=flag1+1;
end
end
end
% Save the picture
imwrite(data1,'1-2.png')
disp(' Embedding complete , Save as 1-2.png');
% Here is the extraction procedure
% Here is x and y, Extract information about the number of bits in a binary string
disp(' Start extracting ...')
[l,w,h]=size(data2);
str_bin1='';% Extracted binary string
locationx=[];
locationy=[];
locationxy=[];
m=length(str_bin);
flag1=1;
flag2=1;
flag3=1;
for i=1:l
if flag3==0
break
end
for j=1:w
if flag2==0
flag3=0;
break
end
for k=1:h
if flag1>length(str_bin)
flag2=0;
break
end
a=dec2bin(data2(x(i+j),y(i+j),k),8);% Decimal to binary
locationx=[locationx,x(i+j)];% Random point x coordinate
locationy=[locationy,y(i+j)];% Random point y coordinate
locationxy=[locationxy;x(i+j),y(i+j),k];
str_bin1=[str_bin1,a(8)];% Take the last number
flag1=flag1+1;
end
end
end
disp(' Extraction complete !');
disp(' The extracted binary string is ：');
disp(str_bin1);
disp(' Start conversion ...')
% Binary to string
str2='';
for q=1:length(str_bin1)/l_str_bin_mat(2)
w=str_bin1((q-1)*l_str_bin_mat(2)+1:q*l_str_bin_mat(2));%w For every seven
a=bin2dec(w); % Convert to decimal
if a>9
str2=[str2,char(a)];
end
if a<9
str2=[str2,a];
end
end
disp(' convert network ');
disp(' The final result is ：');
disp(str2);
disp(' The random positions are ');
disp(locationxy);
plot(locationx,locationy);
Copy code ``````

result ：

The figure below shows the hidden points （ You can see it's really random ）

https://pythonmana.com/2021/04/20210407164603884e.html