zoukankan      html  css  js  c++  java
  • java util

    测试代码

    复制代码
    package cn.java.security;
    

    import java.security.Key;
    import java.util.Base64;
    import org.junit.Assert;
    import cn.java.codec.hex.HexUtil;
    import cn.java.security.SecurityUtil.RsaUtil.RsaKeyPair;

    public class Test {

    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> main(String[] args)  <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{
        System.out.println(</span>"-----------&lt;&lt;&lt; testDigest &gt;&gt;&gt;------------------"<span style="color: #000000">);
        testDigest();
        System.out.println();
        
        System.out.println(</span>"-----------&lt;&lt;&lt; testAes &gt;&gt;&gt;------------------"<span style="color: #000000">);
        testAes();
        System.out.println();
        
        System.out.println(</span>"-----------&lt;&lt;&lt; testRsa &gt;&gt;&gt;------------------"<span style="color: #000000">);
        testRsa();
        System.out.println();
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 对称加密算法
     * </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> testAes() <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
        String content </span>= "testAes"<span style="color: #000000">;
        String secretKeyStr </span>=<span style="color: #000000"> SecurityUtil.AesUtil.generaterKey();
        System.out.println(</span>"-----------secretKeyStr------------------"<span style="color: #000000">);
        System.out.println(secretKeyStr);
        String encryptStr </span>=<span style="color: #000000"> SecurityUtil.AesUtil.encrypt(content, secretKeyStr);
        String decryptStr </span>=<span style="color: #000000"> SecurityUtil.AesUtil.decrypt(encryptStr, secretKeyStr);
        System.out.println(</span>"-----------encryptStr------------------"<span style="color: #000000">);
        System.out.println(encryptStr);
        System.out.println(</span>"-----------decryptStr------------------"<span style="color: #000000">);
        System.out.println(decryptStr);
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 非对称加密算法
     * </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> testRsa() <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
    
        String content </span>= "testRsa"<span style="color: #000000">;
        </span><span style="color: #008000">//</span><span style="color: #008000"> 生成秘钥对</span>
        RsaKeyPair mRsaKeyPair =<span style="color: #000000"> SecurityUtil.RsaUtil.generaterKeyPair();
        String privateKeyStr </span>=<span style="color: #000000"> mRsaKeyPair.getPrivateKey();
        String publicKeyStr </span>=<span style="color: #000000"> mRsaKeyPair.getPublicKey();
        System.out.println(</span>"-----------privateKeyStr------------------"<span style="color: #000000">);
        System.out.println(privateKeyStr);
        System.out.println(</span>"-----------publicKeyStr------------------"<span style="color: #000000">);
        System.out.println(publicKeyStr);
        
        </span><span style="color: #008000">//</span><span style="color: #008000"> test sign</span>
    

    {
    String signStr
    = SecurityUtil.RsaUtil.sign(content, privateKeyStr,true);
    boolean isValid = SecurityUtil.RsaUtil.verify(content,signStr, publicKeyStr,true);
    System.out.println(
    "-----------signStr------------------");
    System.out.println(signStr);
    System.out.println(
    "-----------isValid------------------");
    System.out.println(isValid);
    }

        </span><span style="color: #008000">//</span><span style="color: #008000"> test codec</span>
    

    {
    Key privateKey
    = SecurityUtil.RsaUtil.getPrivateKey(privateKeyStr);
    Key publicKey
    = SecurityUtil.RsaUtil.getPublicKey(publicKeyStr);

            </span><span style="color: #008000">//</span><span style="color: #008000"> 私钥加密、公钥解密</span>
            String encryptStr =<span style="color: #000000"> SecurityUtil.RsaUtil.encrypt(content, privateKey);
            String decryptStr </span>=<span style="color: #000000"> SecurityUtil.RsaUtil.decrypt(encryptStr, publicKey);
    

    // Assert.assertEquals(content, decryptStr);
    System.out.println("-----------encryptStr------------------");
    System.out.println(encryptStr);
    System.out.println(
    "-----------decryptStr------------------");
    System.out.println(decryptStr);

            </span><span style="color: #008000">//</span><span style="color: #008000"> 公钥加密、私钥解密</span>
            encryptStr =<span style="color: #000000"> SecurityUtil.RsaUtil.encrypt(content, privateKey);
            decryptStr </span>=<span style="color: #000000"> SecurityUtil.RsaUtil.decrypt(encryptStr, publicKey);
            Assert.assertEquals(content, decryptStr);
        }
    
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 签名
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> testDigest() <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
        </span><span style="color: #0000ff">byte</span>[] bytes = SecurityUtil.MessageDigestUtil.digest("test", <span style="color: #0000ff">true</span><span style="color: #000000">);
        String hexEncode </span>=<span style="color: #000000"> HexUtil.encode(bytes);
        System.out.println(hexEncode);
    
        </span><span style="color: #0000ff">byte</span>[] hexDecode =<span style="color: #000000"> HexUtil.decode(hexEncode);
        System.out.println(Base64.getEncoder().encodeToString(bytes));
        System.out.println(Base64.getEncoder().encodeToString(hexDecode));
    }
    

    }

    复制代码

    数据内容

    复制代码
    -----------<<< testDigest >>>------------------
    098f6bcd4621d373cade4e832627b4f6
    CY9rzUYh03PK3k6DJie09g==
    CY9rzUYh03PK3k6DJie09g==
    

    -----------<<< testAes >>>------------------
    -----------secretKeyStr------------------
    BREMlyKxuMP2Qc7wIVa9Hg
    ==
    16
    16
    -----------encryptStr------------------
    W
    +47ylkmqZ3G2Wq95esUEg==
    -----------decryptStr------------------
    testAes

    -----------<<< testRsa >>>------------------
    -----------privateKeyStr------------------
    MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCQsWH5fsMj03Ja2W5pxvCz5JBrOUF43yZCenUuBB9gMcJH9oySOeQVWWiAQJ
    +sVqI4QqMLrYsZJuNnuHFWr+uIFyXV7doQDFysvPmbMeQ1UPR9Bv+60QC47YRpVzAR3x0bGRbB3cCJ2U+t55xDV0CuljqR7X4CyfVSDvqaRV08uRn+b/vIvC0e623Uidez1IwGbobWYXBL6WRS0ooOm8AcSy84+c+mahuOUQFjJak18fBwJYnPTHWQnpxtnPYQ028LY05Njnux6DY2tEqeavvFuGQ4jXEhLEqTQL0dT2/auM39wErLkgfwX6OPPgCM/AcUKaM/pdzbZG1In2sVjFUlAgMBAAECggEAP6u+6FJOvqoiTTYW7zca3p56qqRUWkMgC+rlO62WvPbIfnBQ5VvSMU7ZvG4zlVu+ILG6G75vUk8ZjJ/OSA47v/Qnsx7qcVtvQJgb4p4uxQNtwsLcr7Ge9sGWHeC/B2492ZnNuNvDCSX2eRlNWxi/HtR+y45NgB6s9EIhJtfVMo27/a4qEKoyxB9kUOQ+EWXEEGDt8ERYnJfuG6doZ/NI+T8caziKqnmR1pj30B7ASSsFUKoH1YbV71ftBPEvUsyqIOZgLokWfNq3QSWzFoskslJAOxATMcGD+HVt8QQfX92nfd4odpxZNqeS/Qc0MRj+zvltN0LsOBATYq6sRw0StQKBgQDJ3u3p1htpL0DZTgas39hp1qiA3BA9xmD4QZfHQydntDMzLSHDssM/yX1TJuaO6TLFVG9KNqf5UtgKt3QTImm6vU3rsITShAiYKcdbyyEIxpITC89JNqKFop8w77xlYxZc02iS4I4he1rcZFx+14dIJwTCBXUyrkzHxWehmPbDZwKBgQC3fZMrUcJQ7LV8Z4t+gS7ViJh0oE/kvjc8qN5VnW4/YwrAiqsIeM1/J65wQZpl0OcgtRVXhfo2yX+xa8CCh1W22QCGGpuGfSjuM3FSB/QJaBnyW7CZQey0VOICAXAiMf7I8bGO6vaxaK6ECQgcN4bxuFVfV/9U7D6F8tXLsMk3kwKBgFyujlqio3kaadKbITNznj+Rf1GSN561GsZADzg8G7ZgJHWlje/0ffImRvTLUmVgqZ+xkVroVxyALZJWAePbE+HZkhHYvFKOrgd2fwIk86i8ykoWTPgXLmzeaeok10FRSe4aXdO5Z2f145R2O4U83O6Cg4u0x8caAURi3J5zxS+XAoGBAKxbx/dkKGyNvXirZwwg2tZ4JgU/ZWzQBOD1G0w+woXGSh5M45Xkq9uqcaA+74J+de1yTCbX0g7OviTxu3ahG7HTKzvNGJR/UwhVyDevAtwnLmBLIpsDow5NwbLymNt2LQeiiRBfw/UoCO478aNXwWmjpoYWCeFCvQRj89IPMSQDAoGBAIYlxX5FcfColAT3Ams4cjXqVMiwH2O+Ka7bkeQMfWuLTpGAcgM/f6vMoQ1NHUgu+M70pyyrV48pBHxIqAP0PYn6piMMfk7S6yORDF9riFh8D30up3O0Bfe8PbTyModCdhaGNWvhSqMs/ijDVclAXWeuKtA6A8GFuWvxgKdONey9
    -----------publicKeyStr------------------
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkLFh
    +X7DI9NyWtluacbws+SQazlBeN8mQnp1LgQfYDHCR/aMkjnkFVlogECfrFaiOEKjC62LGSbjZ7hxVq/riBcl1e3aEAxcrLz5mzHkNVD0fQb/utEAuO2EaVcwEd8dGxkWwd3AidlPreecQ1dArpY6ke1+Asn1Ug76mkVdPLkZ/m/7yLwtHutt1InXs9SMBm6G1mFwS+lkUtKKDpvAHEsvOPnPpmobjlEBYyWpNfHwcCWJz0x1kJ6cbZz2ENNvC2NOTY57seg2NrRKnmr7xbhkOI1xISxKk0C9HU9v2rjN/cBKy5IH8F+jjz4AjPwHFCmjP6Xc22RtSJ9rFYxVJQIDAQAB
    -----------signStr------------------
    ZZuYMdl58w2TCBaUMfU0p
    +XUL6Irix9/nD0gPm83P/xqlY18GROztZmat5XLKA5Wu373/2l2WhIKdp7DYoQm0Cnmr/0PDGz9PHw2Hhd9I52OVkcDqSPqgmo0U9uE02Urlt3C2moVS08b3VhLHOOzSq8lcsicqis17p0KY33k2he2XMbHEJEbxRMkPCDubDWqwnS/fKiXbNn3u+jni7zdX/Phaq41V2lMMMjdIP8Pm7OxlxdNP3aoTAu6eHaCvakganQE2cz6Y1HwfgXgA8EzaTCcE+weGBbfy9umcMfK0/Pnsqp+jTiz3c8O0p0C8QwogGwIOLBzbeu4d9svC8JA9Q==
    -----------isValid------------------
    true
    -----------encryptStr------------------
    dJGhdeCaK
    /gw52NkD+z1BPoooKYgHqMWUn+tvyPndrq1f5oqaqc8mn/ZclWCLg/hN4PE9zi7gCD9xgp/KEPWOc6XNzOXA/92LVBERpGGtYLQmZnOS8ZrrD4xxxMmra5qD2j03T9Cu4xrICCVZ/Qcp7l05/tZt6tFXJqSDG5uSN9I/en+Mbza9aGwBiTWm6rpv+E5F3sMVk9XDMMgVTMVu6DeT4jZ7HjQ+GATlYFHReVFWmyTv8ijKdnhgMhVvOrGToRAu/ExbNuF99l6FB5I5ZQQMU0wyQDlpXm4GYoRIMmT5wweWJy2f0yO4BnkTje8oNMz7pXnuhNdEulZ5S86sA==
    -----------decryptStr------------------
    testRsa

    复制代码

    工具类

    复制代码
    package cn.java.security;
    

    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class SecurityUtil {

    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 消息摘要
     * </span><span style="color: #808080">@author</span><span style="color: #008000"> zhouzhian
     *
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span><span style="color: #000000"> MessageDigestUtil {
    
        </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">byte</span>[] digest(String content, <span style="color: #0000ff">boolean</span> isMd5) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
            MessageDigest messageDigest </span>= <span style="color: #0000ff">null</span><span style="color: #000000">;
            String algorithm </span>= isMd5 ? "MD5" : "SHA"<span style="color: #000000">;
            messageDigest </span>=<span style="color: #000000"> MessageDigest.getInstance(algorithm);
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> messageDigest.digest(content.getBytes());
        }
    
        </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">byte</span>[] digest1(String content, <span style="color: #0000ff">boolean</span> isMd5) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
            MessageDigest messageDigest </span>= <span style="color: #0000ff">null</span><span style="color: #000000">;
            String algorithm </span>= isMd5 ? "MD5" : "SHA"<span style="color: #000000">;
            messageDigest </span>=<span style="color: #000000"> MessageDigest.getInstance(algorithm);
            messageDigest.update(content.getBytes());
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> messageDigest.digest();
        }
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 对称加密算法
     * </span><span style="color: #808080">@author</span><span style="color: #008000"> zhouzhian
     *
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span><span style="color: #000000"> AesUtil {
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String ALGORITHM = "AES"<span style="color: #000000">;
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String DEFAULT_CHARSET = "UTF-8"<span style="color: #000000">;
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 生成秘钥
         * </span><span style="color: #808080">@return</span><span style="color: #008000">
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> NoSuchAlgorithmException
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String generaterKey() <span style="color: #0000ff">throws</span><span style="color: #000000"> NoSuchAlgorithmException {  
            KeyGenerator keygen </span>=<span style="color: #000000"> KeyGenerator.getInstance(ALGORITHM);
            keygen.init(</span>128, <span style="color: #0000ff">new</span> SecureRandom()); <span style="color: #008000">//</span><span style="color: #008000"> 16 字节 == 128 bit
            </span><span style="color: #008000">//</span><span style="color: #008000">            keygen.init(128, new SecureRandom(seedStr.getBytes())); </span><span style="color: #008000">//</span><span style="color: #008000"> 随机因子一样,生成出来的秘钥会一样</span>
            SecretKey secretKey =<span style="color: #000000"> keygen.generateKey();
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> Base64.getEncoder().encodeToString(secretKey.getEncoded());
        }
    
        </span><span style="color: #008000">/**</span>
         <span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span><span style="color: #000000"> SecretKeySpec getSecretKeySpec(String secretKeyStr){
            </span><span style="color: #0000ff">byte</span>[] secretKey =<span style="color: #000000"> Base64.getDecoder().decode(secretKeyStr);
            System.out.println(secretKey.length);
            </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span><span style="color: #000000"> SecretKeySpec(secretKey, ALGORITHM);
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 加密
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String encrypt(String content,String secretKey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{
            Key key </span>=<span style="color: #000000"> getSecretKeySpec(secretKey);
            Cipher cipher </span>= Cipher.getInstance(ALGORITHM);<span style="color: #008000">//</span><span style="color: #008000"> 创建密码器  </span>
            cipher.init(Cipher.ENCRYPT_MODE, key);<span style="color: #008000">//</span><span style="color: #008000"> 初始化</span>
            <span style="color: #0000ff">byte</span>[] result =<span style="color: #000000"> cipher.doFinal(content.getBytes(DEFAULT_CHARSET));
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> Base64.getEncoder().encodeToString(result);
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 解密
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String decrypt(String content, String secretKey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{  
            Key key </span>=<span style="color: #000000"> getSecretKeySpec(secretKey);
            Cipher cipher </span>=<span style="color: #000000"> Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            </span><span style="color: #0000ff">byte</span>[] result =<span style="color: #000000"> cipher.doFinal(Base64.getDecoder().decode(content));  
            </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span><span style="color: #000000"> String(result);
        }  
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 非对称加密算法
     * </span><span style="color: #808080">@author</span><span style="color: #008000"> zhouzhian
     *
     </span><span style="color: #008000">*/</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span><span style="color: #000000"> RsaUtil {
    
        </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span><span style="color: #000000"> RsaKeyPair {
            </span><span style="color: #0000ff">private</span> String publicKey =""<span style="color: #000000">;
            </span><span style="color: #0000ff">private</span> String privateKey =""<span style="color: #000000">;
    
            </span><span style="color: #0000ff">public</span><span style="color: #000000"> RsaKeyPair(String publicKey, String privateKey) {
                </span><span style="color: #0000ff">super</span><span style="color: #000000">();
                </span><span style="color: #0000ff">this</span>.publicKey =<span style="color: #000000"> publicKey;
                </span><span style="color: #0000ff">this</span>.privateKey =<span style="color: #000000"> privateKey;
            }
    
            </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getPublicKey() {
                </span><span style="color: #0000ff">return</span><span style="color: #000000"> publicKey;
            }
            </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getPrivateKey() {
                </span><span style="color: #0000ff">return</span><span style="color: #000000"> privateKey;
            }
        }
    
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String ALGORITHM = "RSA"<span style="color: #000000">;
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String ALGORITHMS_SHA1WithRSA = "SHA1WithRSA"<span style="color: #000000">;
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String ALGORITHMS_SHA256WithRSA = "SHA256WithRSA"<span style="color: #000000">;
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String DEFAULT_CHARSET = "UTF-8"<span style="color: #000000">;
        </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String getAlgorithms(<span style="color: #0000ff">boolean</span><span style="color: #000000"> isRsa2) {
            </span><span style="color: #0000ff">return</span> isRsa2 ?<span style="color: #000000"> ALGORITHMS_SHA256WithRSA : ALGORITHMS_SHA1WithRSA;
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 生成秘钥对
         * </span><span style="color: #808080">@return</span><span style="color: #008000">
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> NoSuchAlgorithmException
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> RsaKeyPair generaterKeyPair() <span style="color: #0000ff">throws</span><span style="color: #000000"> NoSuchAlgorithmException{  
            KeyPairGenerator keygen </span>=<span style="color: #000000"> KeyPairGenerator.getInstance(ALGORITHM);  
            SecureRandom random </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> SecureRandom();  
            </span><span style="color: #008000">//</span><span style="color: #008000">            SecureRandom random = new SecureRandom(seedStr.getBytes()); </span><span style="color: #008000">//</span><span style="color: #008000"> 随机因子一样,生成出来的秘钥会一样
            </span><span style="color: #008000">//</span><span style="color: #008000"> 512位已被破解,用1024位,最好用2048位 </span>
            keygen.initialize(2048<span style="color: #000000">, random);
            </span><span style="color: #008000">//</span><span style="color: #008000"> 生成密钥对  </span>
            KeyPair keyPair =<span style="color: #000000"> keygen.generateKeyPair();  
            RSAPrivateKey privateKey </span>=<span style="color: #000000"> (RSAPrivateKey)keyPair.getPrivate();  
            RSAPublicKey publicKey </span>=<span style="color: #000000"> (RSAPublicKey)keyPair.getPublic();   
            String privateKeyStr </span>=<span style="color: #000000"> Base64.getEncoder().encodeToString(privateKey.getEncoded());
            String publicKeyStr </span>=<span style="color: #000000"> Base64.getEncoder().encodeToString(publicKey.getEncoded());  
            </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span><span style="color: #000000"> RsaKeyPair(publicKeyStr,privateKeyStr);
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 获取公钥
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> publicKey
         * </span><span style="color: #808080">@return</span><span style="color: #008000">
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> RSAPublicKey getPublicKey(String publicKey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{  
            </span><span style="color: #0000ff">byte</span>[] keyBytes =<span style="color: #000000"> Base64.getDecoder().decode(publicKey);  
            X509EncodedKeySpec spec </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> X509EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory </span>=<span style="color: #000000"> KeyFactory.getInstance(ALGORITHM);  
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> (RSAPublicKey) keyFactory.generatePublic(spec);  
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 获取私钥
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> privateKey
         * </span><span style="color: #808080">@return</span><span style="color: #008000">
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> NoSuchAlgorithmException 
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> InvalidKeySpecException 
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> RSAPrivateKey getPrivateKey(String privateKey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{  
            </span><span style="color: #0000ff">byte</span>[] keyBytes =<span style="color: #000000"> Base64.getDecoder().decode(privateKey);  
            PKCS8EncodedKeySpec spec </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> PKCS8EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory </span>=<span style="color: #000000"> KeyFactory.getInstance(ALGORITHM);  
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> (RSAPrivateKey) keyFactory.generatePrivate(spec);  
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 要私钥签名
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> InvalidKeySpecException 
         * </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception 
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String sign(String content, String privateKey, <span style="color: #0000ff">boolean</span> isRsa2) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
            PrivateKey priKey </span>=<span style="color: #000000"> getPrivateKey(privateKey);
            java.security.Signature signature </span>=<span style="color: #000000"> java.security.Signature.getInstance(getAlgorithms(isRsa2));
            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            </span><span style="color: #0000ff">byte</span>[] signed =<span style="color: #000000"> signature.sign();
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> Base64.getEncoder().encodeToString(signed);
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 要公钥签名
         </span><span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">boolean</span> verify(String content,String sign,String publicKey,<span style="color: #0000ff">boolean</span> isRsa2) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
            PublicKey pubKey </span>=<span style="color: #000000"> getPublicKey(publicKey);
            java.security.Signature signature </span>=<span style="color: #000000"> java.security.Signature.getInstance(getAlgorithms(isRsa2));
            signature.initVerify(pubKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> signature.verify(Base64.getDecoder().decode(sign));
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 加密
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> input
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> pubOrPrikey
         * </span><span style="color: #808080">@return</span>
         <span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String encrypt(String content, Key pubOrPrikey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{
            Cipher cipher </span>= <span style="color: #0000ff">null</span><span style="color: #000000">;
            cipher </span>=<span style="color: #000000"> Cipher.getInstance(ALGORITHM); 
            cipher.init(Cipher.ENCRYPT_MODE, pubOrPrikey);
            </span><span style="color: #0000ff">byte</span>[] result =<span style="color: #000000"> cipher.doFinal(content.getBytes(DEFAULT_CHARSET));
            </span><span style="color: #0000ff">return</span><span style="color: #000000"> Base64.getEncoder().encodeToString(result);
        }
    
        </span><span style="color: #008000">/**</span><span style="color: #008000">
         * 解密
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> input
         * </span><span style="color: #808080">@param</span><span style="color: #008000"> pubOrPrikey
         * </span><span style="color: #808080">@return</span>
         <span style="color: #008000">*/</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String decrypt(String content, Key pubOrPrikey) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception {
            Cipher cipher </span>= <span style="color: #0000ff">null</span><span style="color: #000000">;
            cipher </span>=<span style="color: #000000"> Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, pubOrPrikey);  
            </span><span style="color: #0000ff">byte</span>[] result =<span style="color: #000000"> cipher.doFinal(Base64.getDecoder().decode(content));
            </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span><span style="color: #000000"> String(result);
        }
    }
    

    }

    复制代码
  • 相关阅读:
    前后端分离
    分库分表之终极设计方案
    题解-CF1491
    题解-ARC113
    题解-CF578D LCS Again
    团队冲刺第二阶段5
    团队冲刺第二阶段4
    团队冲刺第二阶段3
    团队冲刺第二阶段2
    团队冲刺第二阶段1
  • 原文地址:https://www.cnblogs.com/jpfss/p/8567191.html
Copyright © 2011-2022 走看看