所有由雷老虎发布的文章

解决Java的PKIX path building failed

最近做web service客户端,内网用http没问题,外网只开放了https,调用时出现javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed的错误。

度娘到一个解决方案,把下面的代码保存,javac编译成class文件。

/* 
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 *   - Redistributions of source code must retain the above copyright 
 *     notice, this list of conditions and the following disclaimer. 
 * 
 *   - Redistributions in binary form must reproduce the above copyright 
 *     notice, this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution. 
 * 
 *   - Neither the name of Sun Microsystems nor the names of its 
 *     contributors may be used to endorse or promote products derived 
 *     from this software without specific prior written permission. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */  
   
import java.io.*;  
import java.net.URL;  
   
import java.security.*;  
import java.security.cert.*;  
   
import javax.net.ssl.*;  
   
public class InstallCert {  
   
    public static void main(String[] args) throws Exception {  
    String host;  
    int port;  
    char[] passphrase;  
    if ((args.length == 1) || (args.length == 2)) {  
        String[] c = args[0].split(":");  
        host = c[0];  
        port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);  
        String p = (args.length == 1) ? "changeit" : args[1];  
        passphrase = p.toCharArray();  
    } else {  
        System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");  
        return;  
    }  
   
    File file = new File("jssecacerts");  
    if (file.isFile() == false) {  
        char SEP = File.separatorChar;  
        File dir = new File(System.getProperty("java.home") + SEP  
            + "lib" + SEP + "security");  
        file = new File(dir, "jssecacerts");  
        if (file.isFile() == false) {  
        file = new File(dir, "cacerts");  
        }  
    }  
    System.out.println("Loading KeyStore " + file + "...");  
    InputStream in = new FileInputStream(file);  
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());  
    ks.load(in, passphrase);  
    in.close();  
   
    SSLContext context = SSLContext.getInstance("TLS");  
    TrustManagerFactory tmf =  
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
    tmf.init(ks);  
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];  
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);  
    context.init(null, new TrustManager[] {tm}, null);  
    SSLSocketFactory factory = context.getSocketFactory();  
   
    System.out.println("Opening connection to " + host + ":" + port + "...");  
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);  
    socket.setSoTimeout(10000);  
    try {  
        System.out.println("Starting SSL handshake...");  
        socket.startHandshake();  
        socket.close();  
        System.out.println();  
        System.out.println("No errors, certificate is already trusted");  
    } catch (SSLException e) {  
        System.out.println();  
        e.printStackTrace(System.out);  
    }  
   
    X509Certificate[] chain = tm.chain;  
    if (chain == null) {  
        System.out.println("Could not obtain server certificate chain");  
        return;  
    }  
   
    BufferedReader reader =  
        new BufferedReader(new InputStreamReader(System.in));  
   
    System.out.println();  
    System.out.println("Server sent " + chain.length + " certificate(s):");  
    System.out.println();  
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");  
    MessageDigest md5 = MessageDigest.getInstance("MD5");  
    for (int i = 0; i < chain.length; i++) {  
        X509Certificate cert = chain[i];  
        System.out.println  
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());  
        System.out.println("   Issuer  " + cert.getIssuerDN());  
        sha1.update(cert.getEncoded());  
        System.out.println("   sha1    " + toHexString(sha1.digest()));  
        md5.update(cert.getEncoded());  
        System.out.println("   md5     " + toHexString(md5.digest()));  
        System.out.println();  
    }  
   
    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");  
    String line = reader.readLine().trim();  
    int k;  
    try {  
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;  
    } catch (NumberFormatException e) {  
        System.out.println("KeyStore not changed");  
        return;  
    }  
   
    X509Certificate cert = chain[k];  
    String alias = host + "-" + (k + 1);  
    ks.setCertificateEntry(alias, cert);  
   
    OutputStream out = new FileOutputStream("jssecacerts");  
    ks.store(out, passphrase);  
    out.close();  
   
    System.out.println();  
    System.out.println(cert);  
    System.out.println();  
    System.out.println  
        ("Added certificate to keystore 'jssecacerts' using alias '"  
        + alias + "'");  
    }  
   
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();  
   
    private static String toHexString(byte[] bytes) {  
    StringBuilder sb = new StringBuilder(bytes.length * 3);  
    for (int b : bytes) {  
        b &= 0xff;  
        sb.append(HEXDIGITS[b >> 4]);  
        sb.append(HEXDIGITS[b & 15]);  
        sb.append(' ');  
    }  
    return sb.toString();  
    }  
   
    private static class SavingTrustManager implements X509TrustManager {  
   
    private final X509TrustManager tm;  
    private X509Certificate[] chain;  
   
    SavingTrustManager(X509TrustManager tm) {  
        this.tm = tm;  
    }  
   
    public X509Certificate[] getAcceptedIssuers() {  
        throw new UnsupportedOperationException();  
    }  
   
    public void checkClientTrusted(X509Certificate[] chain, String authType)  
        throws CertificateException {  
        throw new UnsupportedOperationException();  
    }  
   
    public void checkServerTrusted(X509Certificate[] chain, String authType)  
        throws CertificateException {  
        this.chain = chain;  
        tm.checkServerTrusted(chain, authType);  
    }  
    }  
   
}

然后java InstallCert [webservice的域名(不含https://)]就会生成一个jssecacerts,然后把这个文件放到$JAVA_HOME/jre/lib/security或者在代码中添加一行:

System.setProperty("javax.net.ssl.trustStore", "PATH_OF_THE_FILE/jssecacerts");

然后再调用就OK了。

iF.SVNAdmin 在 Php7.0下的运行

iF.SVNAdmin判断PHP版本的函数有缺陷,需要修改

<?php
function checkPHPVersion($minimumVersion)
{
  $phpVersion = phpversion();
  $phpVersionParts = explode(".", $phpVersion);
  $minVersionParts = explode(".", $minimumVersion);
  $minVersionPartsCount = count($minVersionParts);

  $check = true;
  if ($minVersionPartsCount >= 1)
    if ($phpVersionParts[0] < $minVersionParts[0])
      $check = false;

  if ($minVersionPartsCount >= 2)
    //if ($phpVersionParts[1] < $minVersionParts[1])
    if ($phpVersionParts[0] < $minVersionParts[0] || $phpVersionParts[0] == $minVersionParts[0] && $phpVersionParts[1] < $minVersionParts[1])
      $check = false;

  if ($minVersionPartsCount >= 3)
    if ($phpVersionParts[2] < $minVersionParts[2])
      $check = false;

  return $check;
}

 

因为我增加了维护用户的同时保存用户信息到数据库的功能,所以需要访问数据库,这个是新增文件。PHP7.0 不再支持mysql驱动,改为mysqli,所以需要修改以下操作数据库的方法:

<?php
function getConnection(){
  $hostname = "localhost:3306";
  $username = "username";
  $password = "password";  
  $conn = mysqli_connect($hostname,$username,$password) or die("Connection error:" . mysqli_connect_error());
  $dbName = "dbname";	
  $ret=mysqli_select_db($conn, $dbName);
  return $conn; 
}
function query($sql){
  $conn = getConnection();
  $res = mysqli_query($conn, $sql)  or die("Connection error:" . mysqli_error($conn));
  return $res;  
}
?>

如果是用mysql驱动,这段代码可以改为:

<?php
function getConnection(){
  $hostname = "localhost:3306";
  $username = "username";
  $password = "password";  
  $conn = mysql_pconnect($hostname,$username,$password) or die("Connection error:" . mysql_error());
  $dbName = "dbname";	
  $ret=mysql_select_db($dbName,$conn);
  return $conn; 
}
function query($sql){
  $conn = getConnection();
  $res = mysql_query($sql,$conn)  or die("Connection error:" . mysql_error());
  return $res;  
}
?>

而要保存用户信息到数据库需要修改./actions/create_user.php

// Create user object.
$u = new \svnadmin\core\entities\User;
$u->id = $username;
$u->name = $username;
$u->password = $password;

try {
  // Create the user now.
  $b = $appEngine->getUserEditProvider()->addUser($u);
  if($b)
  {
    $appEngine->getUserEditProvider()->save();
    $appEngine->addMessage(tr("The user %0 has been created successfully.", array($username)));
          $q = "insert IGNORE into user(name, password) values('" . $username . "', '{SHA}" . base64_encode(sha1($password, TRUE)) . "')";
    query($q);

  }

删除用户信息:

// Delete the user.
$done = $appEngine->getUserEditProvider()->deleteUser($u);
if ($done)
{
          $q = "delete from user where name = '" . $u->name . "'";
          query($q);

	$appEngine->addMessage(tr("Removed user %0 successfully.", array($u->name)));
}
else
{
	$appEngine->addException(tr("Can not remove user %0."));
}

 

更改密码

// Ok, change password now.
$b = $appEngine->getUserEditProvider()->changePassword($username, $password);
if ($b) {
  $appEngine->getUserEditProvider()->save();
  $q = "update user set password = '{SHA}" . base64_encode(sha1($password, TRUE)) . "' where name = '" . $username . "'";
  query($q);
  $appEngine->addMessage(tr("The password has been changed."));
}

在./include/config.inc.php这个文件的头部增加对db.inc.php的引用

error_reporting(E_ALL);
include_once("./classes/util/global.func.php");
include_once("./db.inc.php");
set_exception_handler('exception_handler');

 

 

SSH 使用小结

-f    要求 ssh在执行命令前退至后台.它用于当ssh准备询问口令或密语,但是用户希望它在后台进行.该选项隐含了-n选项.在远端机器上启动

-N    不执行远程命令.用于转发端口.

-C    要求进行数据压缩 (包括stdin, stdout, stderr以及转发X11和TCP/IP连接 的数据).压缩算法和gzip(1)的一样,协议第一版中,压缩级别 “level” 用CompressionLevel选项控制.压缩技术在modem线路或其他慢速连接上很有用,但是在高速网络上反而 可能降低速度.可以在配置文件中对每个主机单独设定这个参数.

-g    允许远端主机连接本地转发的端口

-q    安静模式.消除所有的警告和诊断信息

-T    禁止分配伪终端

-n    把 stdin重定向到/dev/null (实际上防止从stdin读取数据).  ssh在后台运行时一定会用到这个选项.它的常用技巧是远程运行X11程序.

ssh -CfNg -L port1:127.0.0.1:port2 user@host    #本地转发
ssh -CfNg -R port2:127.0.0.1:port1 user@host    #远程转发
要监听到0.0.0.0,需要参数 -o GatewayPorts=yes 或者修改 /etc/ssh/sshd_config
SSH -qTfnN -D port remotehost   #socks代理,如果非默认端口,加 -p 参数

CentOS 7安装EasyMock

Easy Mock是一个高效数据模拟解决方案,本地部署需要安装Mongodb, Redis, Node.js等组件的最新版本,下面是具体的方法:

mongodb:

# 编辑文件
vim /etc/yum.repos.d/mongodb-org-3.6.repo

# 添加以下内容
[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

yum install -y mongodb-org

# 启动
systemctl start mongod.service

# 停止
systemctl stop mongod.service

# 重启
systemctl restart mongod.service

 

Redis:

yum install -y http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

yum –enablerepo=remi install redis

service redis start
或者
systemctl start redis

node.js:

curl -sL https://rpm.nodesource.com/setup_9.x | bash –

sudo方式执行如果最后一步有错误,找到下面这一行, sudo方式执行一次
+ rpm -i –nosignature –force ‘/tmp/……..’

然后:
yum install -y nodejs

安装EasyMock

$ git clone https://github.com/easy-mock/easy-mock.git
$ cd easy-mock && npm install

配置文件路径是:config/default.json,可根据需要修改内容

$ npm run build
$ npm install pm2 -g — 安装pm2作为守护进程
$ NODE_ENV=production pm2 start app.js –启动守护进程

 

如果用Apache/Nginx作为web服务器,可以做一个代理,下面是一个Apache的例子:
<VirtualHost *:80>
ServerName mock.mydomain.com
ServerSignature Off

ProxyPreserveHost On

AllowEncodedSlashes NoDecode

<Location />
Order deny,allow
Allow from all
Require all granted

 

ProxyPassReverse http://127.0.0.1:7300
ProxyPassReverse http://mock.mydomain.com/
</Location>

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule .* http://127.0.0.1:7300%{REQUEST_URI} [P,QSA,NE]

DocumentRoot /data/dummy

</VirtualHost>