月度归档:2016年09月

关于array_diff比较两数组的一个BUG

网上判断两数组是否相同BUG代码:

 <?php
$ar1 = [1,2,3,4];
$ar2 = [1,2,3,4,5];
var_dump(array_diff($ar1,$ar2));
var_dump(array_diff($ar2,$ar1));
?>

修复:

 <?php
$ar1 = [1,2,3,4];
$ar2 = [1,2,3,4,5];
if(count(array_unique($ar1))!=count(array_unique($ar2))){
echo "not eq";
exit;
}
var_dump(array_diff($ar1,$ar2));
var_dump(array_diff($ar2,$ar1));
?>

泛微邮箱账户密码解密算法

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.Security;
import java.util.Scanner;

public class Encoder {

    private static final String key = "weavercwjweavercwjweaver";
    private static final String Algorithm = "DESede";
    private static final int    KEY_LENGTH= 24; 
    public static String getBASE64(byte[] s) {
           if (s == null) return null;
           return (new sun.misc.BASE64Encoder()).encode( s );
    }

    public static byte[] getFromBASE64(String s) {
           if (s == null) return null;
           sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
           try {
                 byte[] b = decoder.decodeBuffer(s);
                 return b;
           } catch (Exception e) {
                 return null;
           }
    }

    private static byte[] genKey(String key)  throws Exception {

            byte keyBytes[];
            switch (key.length())
            {
            case 24:
                keyBytes=key.getBytes("UTF-8");
                break;
            case 16:
                key=key+key.substring(0,8);
                keyBytes=key.getBytes("UTF-8");
                break;
            default:
                throw new Exception("99999");
            }

            return keyBytes;

    }

    private static byte[] genMsg(String msg)  throws Exception {

            byte[] src=msg.getBytes("UTF-8");
            byte[] msgBytes;

            if ((src.length % 8) != 0) {
                int remain=8-(src.length % 8);
                int total=src.length+remain;
                msgBytes=new byte[total];
            } else {
                msgBytes=new byte[src.length];
            }
            for (int count=0;count<src.length;count++) {
                    msgBytes[count]=src[count];
            }
            return msgBytes;

    }

    private static IvParameterSpec genIV() {

            byte[] myIV = new byte[8];
            IvParameterSpec ivspec = new IvParameterSpec(myIV);

            return ivspec;

    }

    public static byte[] encrypt(String msg,String key) throws Exception {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());


            byte[] keyBytes=genKey(key);
            byte[] msgBytes=genMsg(msg);


            SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);
            IvParameterSpec ivspec=genIV();

            Cipher c1 = Cipher.getInstance("DESede/CBC/NoPadding");
            //Cipher c1 = Cipher.getInstance("DES/CBC/NoPadding");
            c1.init(Cipher.ENCRYPT_MODE, deskey,ivspec);
            byte[] result=c1.doFinal(msgBytes);

            //System.out.println(String.valueOf(result.length));
            return (result);


    }



    public static String decrypt(byte[] msg,String key) throws Exception {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());

            byte[] keyBytes=genKey(key);
            SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);

            IvParameterSpec ivspec=genIV();

            byte[] src=msg;

            Cipher c1 = Cipher.getInstance("DESede/CBC/NoPadding");
            //Cipher c1 = Cipher.getInstance("DES/CBC/NoPadding");
            c1.init(Cipher.DECRYPT_MODE, deskey,ivspec);
            return (new String(c1.doFinal(src),"UTF-8"));
            //return(String.valueOf(src.length));

    }


public static void main(String args[])    {
//run javac Encoder.java   java Encoder 

String str = "";
		try{
			 str = decrypt(getFromBASE64("+H5vDFqhNrQ="),key); // Kdkx+H/zBZI=  +H5vDFqhNrQ=
		}catch(Exception e){
			str ="abc";
		}

System.out.println(str);

		String stra = "";
		try{
			byte b[] = encrypt("94111",key);
			stra = getBASE64(b); 
		}catch(Exception e){
			stra ="abc";
		}

System.out.println(stra);

}

}

泛微某接口数据库连接字符串解密算法

PHP:

 <?php
function decrypt($str, $key)
{
        $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
            $block = mcrypt_get_block_size('des', 'ecb');
            $pad = ord($str[($len = strlen($str)) - 1]);
                return substr($str, 0, strlen($str) - $pad);
}
$url = "xxx";
$xx = file_get_contents($url);
$xx = trim($xx);
$keystr= "1z2x3c4v5b6n";
 
$hex_str = "xxxxxxxxxxxxxxxxxx";
$strs=hex2bin($hex_str);
$de = decrypt($xx,$keystr);
var_dump($de); 

JAVA:

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.Security;
import java.util.Scanner;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.*;
import java.security.SecureRandom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;


public class Td {

public static byte[] encodess(String sb,String keyString) throws Exception {
    byte[]  str = sb.getBytes();
    byte[] keyByte = keyString.getBytes();
    DESKeySpec dks1 = new DESKeySpec(keyByte);
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks1);
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE, key);  
    byte[] cipherText = cipher.doFinal(str);
    return cipherText;
}

public static byte[] decodess(byte[] str,String keyString) throws Exception {
    byte[] keyByte = keyString.getBytes();
    DESKeySpec dks1 = new DESKeySpec(keyByte);
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks1);
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, key);  
    byte[] cipherText = cipher.doFinal(str);
    return cipherText;
}

public static String printHexString( byte[] b) {
String a = "";
  for (int i = 0; i < b.length; i++) { 
    String hex = Integer.toHexString(b[i] & 0xFF); 
    if (hex.length() == 1) { 
      hex = '0' + hex; 
    }
   
    a = a+hex;
  } 
  
       return a;
}


public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
    return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
    int pos = i * 2;
    d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
    
}
return d;
}

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

public static void printbyte(byte[] b)    
    {       
        for (int i = 0; i < b.length; i++)    
        {    
            String hex = Integer.toHexString(b[i] & 0xFF);    
            if (hex.length() == 1)    
            {    
                hex = '0' + hex;    
            }    
            System.out.print(hex.toUpperCase() + " ");    
        }    
        System.out.println("");    
    }  


    public static byte[] getFromBASE64(String s) {
           if (s == null) return null;
           sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
           try {
                 byte[] b = decoder.decodeBuffer(s);
                 return b;
           } catch (Exception e) {
                 return null;
           }
    }


public static String getHtml(String urlString) {
try {
StringBuffer html = new StringBuffer();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
while ((temp = br.readLine()) != null) {
html.append(temp);
}
br.close();
isr.close();
return html.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


    public final static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }






public static void main(String args[])  throws Exception {
String keyString = "1z2x3c4v5b6n";
String str1 = "this is a stringasdfasdfasdfas adsfadsf aaa adsadfjjjjja asdfas asdfa adsf adsf";
String urls ="http://xxxxx";

byte[] test_encode_byte = encodess(str1,keyString);
printbyte(test_encode_byte);

System.out.println(new String(test_encode_byte));
System.out.println(new String(test_encode_byte).length());
printbyte(new String(test_encode_byte,"ISO8859-1").getBytes("ISO8859-1"));
byte[] new_byte = new String(test_encode_byte,"ISO8859-1").getBytes("ISO8859-1");

String hexstring = printHexString(test_encode_byte);
System.out.println(hexstring);

byte[] hexstring_t_byte = hexStringToBytes(hexstring);
System.out.println(hexstring_t_byte);

String htmlstr = new String(test_encode_byte);
byte[] htmlstr_byte = htmlstr.getBytes();
byte[] test_decode_byte = decodess(new_byte,keyString);
System.out.println(new String(test_decode_byte));


String base64_str = "itLx1Jh+xxxx+EcPVVteA==";
byte[] base64_decode = getFromBASE64(base64_str);
System.out.println(MD5(new String(base64_decode,"ISO8859-1")));
printbyte(base64_decode);
System.out.println(new String(base64_decode));
byte[] test_decode_byte_t = decodess(base64_decode,keyString);
System.out.println(new String(test_decode_byte_t));


/*
String url_content = getHtml(urls);
System.out.println(MD5(url_content));
byte[] new_html_byte = url_content.getBytes("ISO8859-1");
byte[] test_decode_byte_ta = decodess(new_html_byte,keyString);
System.out.println(new String(test_decode_byte_ta));
*/

}

}

php mysql pdo insert multiple rows 批量插入

DEMO:

<?php
// 批量插入DEMO
$dbhost="127.0.0.1";
$dbuser="root";
$dbpwd="123456";
$dbname="testa";
$option[PDO::MYSQL_ATTR_INIT_COMMAND]='SET SESSION sql_mode =REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@@sql_mode,"STRICT_ALL_TABLES,", ""),",STRICT_ALL_TABLES", ""),"STRICT_ALL_TABLES", ""),"STRICT_TRANS_TABLES,", ""),",STRICT_TRANS_TABLES", ""),"STRICT_TRANS_TABLES", "")';
$option['PDO::ATTR_ERRMODE']=PDO::ERRMODE_EXCEPTION;
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpwd, $option);

$data = [
['strs'=>'abc','time'=>1],
['strs'=>'abc2','time'=>2],
['strs'=>'abc3','time'=>3],
['strs'=>'abc4','time'=>4],
['strs'=>'abc5','time'=>5],
['strs'=>'abc6','time'=>6],
['strs'=>'abc7','time'=>7],
['strs'=>'abc8','time'=>8],
['strs'=>'abc9','time'=>9],
['strs'=>'abc10','time'=>10],
['strs'=>'abc11','time'=>11],
['strs'=>'abc12','time'=>12],
['strs'=>'abc13','time'=>13],
['strs'=>'abc14','time'=>14],
['strs'=>'abc15','time'=>15],
['strs'=>'abc16','time'=>16],
['strs'=>'abc17','time'=>17],
['strs'=>'abc18','time'=>18],
['strs'=>'abc19','time'=>19],
['strs'=>'abc20','time'=>20],
['strs'=>'abc21','time'=>21],
['strs'=>'abc22','time'=>22],
['strs'=>'abc23','time'=>23],
['strs'=>'abc24','time'=>24],
['strs'=>'abc25','time'=>25],
['strs'=>'abc26','time'=>26],
['strs'=>'abc27','time'=>27],
];

//array_chunk  实现的分页
$data_paged = array_chunk($data, 10);
foreach ($data_paged as $a_page){
$datafields_tmp = array_keys($a_page[0]);
$datafields = '('.implode(',',$datafields_tmp).')';
$values_tmp = [];
foreach($a_page as $d){
	$values_tmp[]="('".implode("','",array_values($d))."')";
}
$values = implode(',',$values_tmp);
$tables = 'exceptions';
$sql = "insert into {$tables} {$datafields} values {$values}";
$pdo->query($sql);
}
echo "good";


// array_slice 实现的分页
$total = count( $data );
$limit = 10;
$totalPages = ceil( $total/ $limit );
for ($page = 1 ; $page <=$totalPages ; $page++){
$offset = ($page - 1) * $limit;
if( $offset < 0 )
{
$offset = 0;
}
$a_page = array_slice( $data, $offset, $limit );
$datafields_tmp = array_keys($a_page[0]);
$datafields = '('.implode(',',$datafields_tmp).')';
$values_tmp = [];
foreach($a_page as $d){
	$values_tmp[]="('".implode("','",array_values($d))."')";
}
$values = implode(',',$values_tmp);
$tables = 'exceptions';
$sql = "insert into {$tables} {$datafields} values {$values}";
$pdo->query($sql);
}

echo "good1";

mysql php pdo sql_mode mark

$option[PDO::MYSQL_ATTR_INIT_COMMAND]='SET SESSION sql_mode =REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@@sql_mode,"STRICT_ALL_TABLES,", ""),",STRICT_ALL_TABLES", ""),"STRICT_ALL_TABLES", ""),"STRICT_TRANS_TABLES,", ""),",STRICT_TRANS_TABLES", ""),"STRICT_TRANS_TABLES", "")';
$option['PDO::ATTR_ERRMODE']=PDO::ERRMODE_EXCEPTION;
$pdo=new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpwd, $option);
 然后就可以偷懒些了。

解决 sysv-rc-conf 执行失效

vim /usr/sbin/sysv-rc-conf 

sub update_link 函数下

原代码:

return 1 if $sk eq ”; 

修改为

unlink “/etc/systemd/system/multi-user.target.wants/$sn.service”;

return 1 if $sk eq ”; 

return 1 if $sk eq ‘K’;

ubuntu 16.04 测试通过 ,  目前 只做了 off 操作修改  on 操作有时间再修改

另附一个已经改好的

sysv-rc-con1.tar

blog 启用https Let’s Encrypt

wget https://dl.eff.org/certbot-auto –no-check-certificate
chmod +x ./certbot-auto

./certbot-auto -n  #安装依赖

或者直接 yum install certbot

/opt/certbot-auto certonly –email xxx@qq.com –agree-tos –webroot -w /data/www/www.so-cools.com/ -d www.so-cools.com

cd /etc/letsencrypt/live/www.so-cools.com/

openssl dhparam -out dh4096.pem 4096

nginx 配置文件 添加

                    listen 443 ssl;
                    server_name www.so-cools.com so-cools.com;
                    ssl_certificate /etc/letsencrypt/live/www.so-cools.com/fullchain.pem;
                    ssl_certificate_key /etc/letsencrypt/live/www.so-cools.com/privkey.pem;
                    ssl_trusted_certificate /etc/letsencrypt/live/www.so-cools.com/chain.pem;
                    ssl_protocols          TLSv1 TLSv1.1 TLSv1.2;
                    ssl_dhparam /etc/letsencrypt/live/www.so-cools.com/dh4096.pem;
                    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA;
                    

最后添加定时任务:

0 3 */5 * * /opt/certbot-auto renew  #每5天定时更新证书

openvas openvas-scapdata-sync 出现date: invalid date

经测试 在centos6下会出现此问题, 经测试为date bug

临时解决办法:

/usr/sbin/openvas-scapdata-sync

oval_timestamp=`xsltproc “$SCAP_RES_DIR/oval_timestamp.xsl” “$ovalfile”  | date “+%s” -f -`

修改为

oval_timestamp=`xsltproc “$SCAP_RES_DIR/oval_timestamp.xsl” “$ovalfile” | sed ‘s/T/ /’ | date “+%s” -f -`

#复制异地的scap-data文件,然后再执行

openvas-scapdata-sync --migrate #刷新数据

#cert sync 对应文件

/usr/bin/rsync -ltvrP --delete --exclude /cert.db --exclude private/ rsync://feed.openvas.org:/cert-data /var/lib/openvas/cert

rsync 命令:

/usr/bin/rsync -ltvrP --delete --exclude /scap.db --exclude private/ rsync://feed.openvas.org:/scap-data /var/lib/openvas/scap-data