OPENSSL AES Encrypt ECB method example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
php example
<?php
 
 
 
$iv = "6543210987654321"; /* 必须16位哦 */
$password="1234567812345678";
$data="12345678901234567890012345678909999999999";
 
#$enc=aes_encode($data,$password)."\n";
 
$enc="S3Aqx0GUd3vcz5r6CkCkonPzwfaL3z3BgMtP8aEbzKUNeE+8APZVP02sviaSZXyS";
 
echo "decode:[".aes_decode($enc,$password)."]\n";
 
/* 采用128位加密,密钥也必须是16位 */
function aes_encode($sourcestr, $key)
{
    global $iv;
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $sourcestr, MCRYPT_MODE_CBC, $iv));
}
 
function aes_decode($crypttext, $key)
{
    global $iv;
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($crypttext), MCRYPT_MODE_CBC, $iv), "\0");
}
 
 
?>

C++ example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
string COpenSSL::aes_encode(const char *sourcestr, char *key = "")
{
    if (strcmp(key, "") == 0)
    {
        return "";
    }
 
    int len = strlen(sourcestr);
    unsigned char iv[AES_BLOCK_SIZE+1] = "6543210987654321"// 注意,iv绝对不能是const的,否则会段错误
 
    unsigned char * out = (unsigned char *)malloc(1024*1024);
    if (out == NULL) {
        fprintf(stderr, "No Memory!\n");
    }
    AES_KEY aes;
    if(AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0)
    {
        return NULL;
    }
    /* 计算补0后的长度 */
    int out_len = ((len - 1) / 16 + 1)* 16;
    char * sstr = (char *)malloc(sizeof(char) * out_len + 1);
    /* 补0 */
    memset(sstr, 0, out_len+1);
    strcpy(sstr, sourcestr);
    AES_cbc_encrypt((unsigned char*)sstr, out, out_len, &aes, (unsigned char*)iv, AES_ENCRYPT);
    /* 这里的长度一定要注意,不能用strlen来获取,加密后的字符串中可能会包含\0 */
    string out2 = base64_encode((char *)out, out_len);
    free(out);
    free(sstr);
 
    ofstream myfile;
            myfile.open("aes.txt", ios::out);
            myfile.write((char *) out2.c_str(), out2.size());
            myfile.close();
 
 
    return out2;
}
 
string COpenSSL::aes_decode(const char *crypttext, char *key = "")
{
    if (strcmp(key, "") == 0)
    {
        return "";
    }
    int out_len = 0;
    unsigned char iv[AES_BLOCK_SIZE+1] = "6543210987654321";
 
    string in = base64_decode(crypttext);
    out_len=in.size();
    char *out = (char *) malloc(sizeof(char) * out_len + 1);
    memset(out, 0, out_len + 1);
    AES_KEY aes;
    if(AES_set_decrypt_key((unsigned char*)key, 128, &aes) < 0)
    {
        return "";
    }
 
    AES_cbc_encrypt((unsigned char*)in.c_str(), (unsigned char*)out, out_len, &aes, (unsigned char*)iv, AES_DECRYPT);
    //free(in);
    string sRet=out;
    free(out);
    return sRet;
}
 
 
bool COpenSSL::testAES(std::string p_sKey, std::string p_sData2Encrypt,
        bool p_bEnc, std::string & p_sEncStr) {
 
    /*
     * aes BLOCK HAVE TO BE 16 BIT BLOCK
     * AES key has to be 16 CHAR
     */
    std::string sBuffer, sOutBuffer;
    //std::string sKey="1234567812345678";
    unsigned char aes_key[16]; //128 bit
    memset(aes_key, 0, 16);
 
    int nKeyLen = p_sKey.size() <= 16 ? p_sKey.size() : 16;
    memcpy(aes_key, p_sKey.c_str(), nKeyLen);   //Get password inplace
    /* Buffers for Encryption and Decryption */
 
    unsigned char databuffer[16];
    memset(databuffer, 0, 16);
    unsigned char outbuffer[16];
    memset(outbuffer, 0, 16);
 
    /* AES-128 bit CBC Encryption */
    AES_KEY enc_key, dec_key;
    if (p_bEnc) {
 
        if (AES_set_encrypt_key(aes_key, sizeof(aes_key) * 8, &enc_key) < 0) {
            return false;
        }
    } else {
        if (AES_set_decrypt_key(aes_key, sizeof(aes_key) * 8, &dec_key) < 0) {
 
            return false;
        }
 
    }
 
    int32_t nDataLen = 0;
 
    if (p_bEnc) {
        nDataLen = p_sData2Encrypt.size();
        sBuffer.append((char *) &nDataLen, sizeof(int32_t));
        sBuffer.append(p_sData2Encrypt);
        int nMod = sBuffer.size() % 16;
        if (nMod != 0) {
            sBuffer.append((char *) databuffer, 16 - nMod);
 
        }
 
    } else {
        sBuffer = base64_decode(p_sData2Encrypt);
        nDataLen = sBuffer.size();
        if (nDataLen % 16 != 0) {
            TRACE("Wrong Buffer,  Len mod 16 has to be 0\n");
            return false;
        }
    }
 
    int nDataIndex = 0;
    int nCopySize = 16;
    nDataLen = sBuffer.size();
    //AES_set_decrypt_key(aes_key, sizeof(aes_key)*8, &dec_key); // Size of key is in bits
 
    while (nDataIndex < nDataLen) {
 
        memcpy(databuffer, sBuffer.c_str() + nDataIndex, nCopySize);
        if (p_bEnc) {
            AES_ecb_encrypt(databuffer, outbuffer, &enc_key, AES_ENCRYPT);
        } else {
            AES_ecb_encrypt(databuffer, outbuffer, &dec_key, AES_DECRYPT);
 
        }
        nDataIndex += 16;
        sOutBuffer.append((char *) outbuffer, 16);
    }
 
    if (p_bEnc) {
        p_sEncStr = base64_encode((unsigned char *) sOutBuffer.c_str(),
                sOutBuffer.size());
    } else {
        int32_t nTotalLen = 0;
        memcpy((char *) &nTotalLen, sOutBuffer.c_str(), sizeof(int32_t));
 
 
        p_sEncStr.append(sOutBuffer.c_str() + sizeof(int32_t), nTotalLen);
    }
 
    return true;
 
     
 
}

iptable nf_inet_hooks

Netfilter places

从上网络包发送接受流程图中看出,可以在不同的地方注册Nefilter的hook函数.由如下定义:

enum nf_inet_hooks {
NF_INET_PRE_ROUTING, //0
NF_INET_LOCAL_IN,
NF_INET_FORWARD,
NF_INET_LOCAL_OUT,
NF_INET_POST_ROUTING, //4
NF_INET_NUMHOOKS
};
NF_INET_PRE_ROUTING: incoming packets pass this hook in the ip_rcv() (linux/net/ipv4/ip_input.c) function before they are processed by the routing code.
NF_INET_LOCAL_IN: all incoming packets addressed to the local computer pass this hook in the function ip_local_deliver().
NF_INET_FORWARD: incoming packets are passed this hook in the function ip_forwared().
NF_INET_LOCAL_OUT: all outgoing packets created in the local computer pass this hook in the function ip_build_and_send_pkt().
NF_INET_POST_ROUTING: this hook in the ipfinishoutput() function before they leave the computer.

C++ std map

Declare

std::map first;

Add
first[‘a’]=10;
first[‘b’]=30;
first[‘c’]=50;
first[‘d’]=70;

Test key exist:
if ( first.find(“f”) == first.end() ) {
// not found
} else {
// found
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
it = mymap.begin();
while (it != mymap.end()) {
   if (something)
      mymap.erase(it++);
   else
      it++;
}
 
C++ 11
 
std::map<K, V>::iterator itr = myMap.begin();
while (itr != myMap.end()) {
    if (ShouldDelete(*itr)) {
       itr = myMap.erase(itr);
    } else {
       ++itr;
    }
}

Compare Two Java byte Arrays Example

/*
Compare Two Java byte Arrays Example
This java example shows how to compare two byte arrays for equality using
Arrays.equals method.
*/

import java.util.Arrays;

public class CompareByteArraysExample {

public static void main(String[] args) {
//create byte arrays
byte[] byteArray1 = new byte[]{7,25,12};
byte[] byteArray2 = new byte[]{7,25,12};

/*
To compare two byte arrays use,
static boolean equals(byte array1[], byte array2[]) method of Arrays class.

It returns true if both arrays are equal. Arrays are considered as equal
if they contain same elements in same order.
*/

boolean blnResult = Arrays.equals(byteArray1,byteArray2);
System.out.println(“Are two byte arrays equal ? : ” + blnResult);

/*
Please note that two byte array references pointing to null are
considered as equal.
*/

}
}

/*
Output of the program would be
Are two byte arrays equal ? : true
*/

C++ Get current hour, minutes of the day

#include <time.h>
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);

int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 – 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900; // Year is # years since 1900
int hour=aTime->tm_hour;
int min=aTime->tm_min;

c++ code std::map iterator map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
map<DWORD,MACADDR> arpmap=CAddressHelper::GetARPCache();
 
    map<DWORD,MACADDR>::iterator it;
 
        for (it = arpmap.begin(); it != arpmap.end(); ++it) {
            MACADDR &sMac = (*it).second;
            const DWORD &nIP=(*it).first;
  
            }
 
 
 
c++ 11
for (auto x: arpmap) {
  cout << x.first << endl;
}

C++ Code Convert Hex string back to Char buffer

int _helpper_Hex2Char(unsigned char & p_cChar,unsigned char p_Value,int & p_nOdd)
{
p_cChar&=0xf0;
p_Value&=0x0f;
p_cChar|=p_Value;
if(p_nOdd++%2) p_cChar<<=4; //first part return p_nOdd%2?1:0; //if it is odd, then index need to +1 , other wise, index +0; } string _helper_Hex2Buffer(string p_sHexStr) { string sReturn = ""; unsigned char *buf=new unsigned char[p_sHexStr.length()]; memset(buf,0,p_sHexStr.length()); int nIndex=0; int nOdd=1; for (int i = 0; i < p_sHexStr.length (); ++i) { switch (p_sHexStr [i]) { case '0': { nIndex+=_helpper_Hex2Char(buf[nIndex],0x00,nOdd); break; } case '1': { nIndex+=_helpper_Hex2Char(buf[nIndex],0x01,nOdd); break; } case '2': nIndex+=_helpper_Hex2Char(buf[nIndex],0x02,nOdd); break; case '3': nIndex+=_helpper_Hex2Char(buf[nIndex],0x03,nOdd); break; case '4': nIndex+=_helpper_Hex2Char(buf[nIndex],0x04,nOdd); break; case '5': nIndex+=_helpper_Hex2Char(buf[nIndex],0x05,nOdd); break; case '6': nIndex+=_helpper_Hex2Char(buf[nIndex],0x06,nOdd); break; case '7': nIndex+=_helpper_Hex2Char(buf[nIndex],0x07,nOdd); break; case '8': nIndex+=_helpper_Hex2Char(buf[nIndex],0x08,nOdd); break; case '9': nIndex+=_helpper_Hex2Char(buf[nIndex],0x09,nOdd); break; case 'a': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0a,nOdd); break; case 'b': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0b,nOdd); break; case 'c': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0c,nOdd); break; case 'd': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0d,nOdd); break; case 'e': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0e,nOdd); break; case 'f': nIndex+=_helpper_Hex2Char(buf[nIndex],0x0f,nOdd); break; default: continue; } } sReturn.append((char *)buf,nIndex); delete buf; return sReturn; }