JCodec用法

x33g5p2x  于2021-12-25 转载在 其他  
字(18.9k)|赞(0)|评价(0)|浏览(431)

第一部分 简介

JCodec包含了常用的编码、加解密的JAVA实现。

第二部分 开始使用

使用JCodec可以直接下载源代码编译或者下载已经编译的jar文件,如果您是使用maven来构建项目,也可以直接在pom.xml中添加JCodec的坐标:

<!-- http://mvnrepository.com/artifact/com.jianggujin/JCodec -->
<dependency>
    <groupId>com.jianggujin</groupId>
    <artifactId>JCodec</artifactId>
    <version>最新版本</version>
</dependency>

最新的版本可以从Maven仓库或者码云获取。

2.1 Base64

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JDecoder;
import com.jianggujin.codec.JBase64.JEncoder;

public class Base64Test {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws IOException {
      JEncoder encoder = JBase64.getEncoder();
      JDecoder decoder = JBase64.getDecoder();
      System.out.println("原串:" + str);
      String encode = encoder.encodeToString(str.getBytes(), "UTF-8");
      System.out.println("编码:" + encode);
      System.out.println("解码:" + new String(decoder.decode(encode, "UTF-8")));
      System.out.print("输出流编码:" + file.getAbsolutePath());
      OutputStream out = encoder.wrap(new FileOutputStream(file));
      out.write(str.getBytes());
      out.flush();
      out.close();
      System.out.println();
      System.out.print("输入流解码:");
      InputStream in = decoder.wrap(new FileInputStream(file));
      byte[] buffer = new byte[1024];
      int len = in.read(buffer);
      System.out.println(new String(buffer, 0, len));
   }
}

2.2 Caesar(凯撒加密)

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
import com.jianggujin.codec.JCaesar;

public class CaesarTest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");
   int k = 10;

   @Test
   public void test() throws IOException {
      System.out.println("原串:" + str + ", 偏移:" + k);
      String encrypt = JCaesar.encrypt(str, k);
      System.out.println("加密:" + encrypt);
      System.out.println("解密:" + JCaesar.decrypt(encrypt, k));
      System.out.print("输出流加密:" + file.getAbsolutePath());
      OutputStream out = JCaesar.wrap(new FileOutputStream(file), k);
      out.write(str.getBytes());
      out.flush();
      System.out.println();
      System.out.print("输入流解密:");
      InputStream in = JCaesar.wrap(new FileInputStream(file), k);
      byte[] buffer = new byte[1024];
      int len = in.read(buffer);
      System.out.println(new String(buffer, 0, len));
   }
}

2.3 CRC32(循环冗余校验)

package com.jianggujin.codec.test;

import java.io.IOException;
import org.junit.Test;
import com.jianggujin.codec.JCRC32;

public class CRC32Test {
   String str = "jianggujin";

   @Test
   public void test() throws IOException {
      System.out.println("原串:" + str);
      System.out.println("CRC32:" + JCRC32.encode(str.getBytes()));
   }
}

2.4 MessageDigest(信息摘要算法)

package com.jianggujin.codec.test;

import org.junit.Test;

import com.jianggujin.codec.JHex;
import com.jianggujin.codec.JMessageDigest;
import com.jianggujin.codec.JMessageDigest.JMessageDigestAlgorithm;

public class MessageDigestTest {
   String str = "jianggujin";

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      for (JMessageDigestAlgorithm algorithm : JMessageDigestAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("算法:" + algorithm.getName());
         byte[] result = JMessageDigest.encrypt(str.getBytes(), algorithm.getName());
         System.out.println("结果:" + JHex.encodeString(result));
      }
   }
}

2.5 Mac(消息认证码 Message Authentication Code)

package com.jianggujin.codec.test;

import org.junit.Test;

import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JHex;
import com.jianggujin.codec.JMac;
import com.jianggujin.codec.JMac.JMacAlgorithm;

public class MacTest {
   String str = "jianggujin";

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      for (JMacAlgorithm algorithm : JMacAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("算法:" + algorithm);
         byte[] key = JMac.initEncodedKey(algorithm);
         System.out.println("密钥:" + encoder.encodeToString(key, "UTF-8"));
         byte[] result = JMac.encrypt(str.getBytes(), key, algorithm);
         System.out.println("结果:" + JHex.encodeString(result));
      }
   }
}

2.6 Symmetrical(对称加密)

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JSymmetrical;
import com.jianggujin.codec.JSymmetrical.JSymmetricalAlgorithm;

public class SymmetricalTest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      for (JSymmetricalAlgorithm algorithm : JSymmetricalAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("算法:" + algorithm);
         byte[] key = JSymmetrical.initEncodedKey(algorithm);
         System.out.println("密钥:" + encoder.encodeToString(key, "UTF-8"));

         byte[] encrypt = JSymmetrical.encrypt(str.getBytes(), key, algorithm);
         System.out.println("加密:" + encoder.encodeToString(encrypt, "UTF-8"));
         System.out.println("解密:" + new String(JSymmetrical.decrypt(encrypt, key, algorithm)));

         System.out.print("输出流加密:" + file.getAbsolutePath());
         OutputStream out = JSymmetrical.wrap(new FileOutputStream(file), key, algorithm);
         out.write(str.getBytes());
         out.flush();
         out.close();
         System.out.println();
         System.out.print("输入流解密:");
         InputStream in = JSymmetrical.wrap(new FileInputStream(file), key, algorithm);
         byte[] buffer = new byte[1024];
         int len = in.read(buffer);
         System.out.println(new String(buffer, 0, len));
      }
   }
}

2.7 TripleDES(三重数据加密算法)

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JTripleDES;
import com.jianggujin.codec.JTripleDES.JTripleAlgorithm;
import com.jianggujin.codec.JTripleDES.JPadding;
import com.jianggujin.codec.JTripleDES.JWorkingMode;

public class TripleDESTest {
   String str = "jianggujin111111";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      for (JTripleAlgorithm algorithm : JTripleAlgorithm.values()) {
         System.out.println("算法:" + algorithm);
         byte[] key = JTripleDES.initEncodedKey(algorithm);
         System.out.println("密钥:" + encoder.encodeToString(key, "UTF-8"));
         for (JWorkingMode workingMode : JWorkingMode.values()) {
            for (JPadding padding : JPadding.values()) {
               System.out.println("-----------------------------------------");
               System.out.println(algorithm + "/" + workingMode + "/" + padding);
               byte[] encrypt = JTripleDES.encrypt(str.getBytes(), key, algorithm, workingMode, padding);
               System.out.println("加密:" + encoder.encodeToString(encrypt, "UTF-8"));
               System.out
                     .println("解密:" + new String(JTripleDES.decrypt(encrypt, key, algorithm, workingMode, padding)));

               System.out.print("输出流加密:" + file.getAbsolutePath());
               OutputStream out = JTripleDES.wrap(new FileOutputStream(file), key, algorithm, workingMode, padding);
               out.write(str.getBytes());
               out.flush();
               out.close();
               System.out.println();
               System.out.print("输入流解密:");
               InputStream in = JTripleDES.wrap(new FileInputStream(file), key, algorithm, workingMode, padding);
               byte[] buffer = new byte[1024];
               int len = in.read(buffer);
               System.out.println(new String(buffer, 0, len));
            }
         }
      }
   }
}

2.8 DH(Diffie-Hellman算法)

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JDH;
import com.jianggujin.codec.JDH.JDHSymmetricalAlgorithm;

public class DHTest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      KeyPair keyPairA = JDH.initPartyAKey();
      byte[] keyPairAPrivate = keyPairA.getPrivate().getEncoded();
      byte[] keyPairAPublic = keyPairA.getPublic().getEncoded();
      System.out.println("甲方私钥:" + encoder.encodeToString(keyPairAPrivate, "UTF-8"));
      System.out.println("甲方公钥:" + encoder.encodeToString(keyPairAPublic, "UTF-8"));
      KeyPair keyPairB = JDH.initPartyBKey(keyPairAPublic);
      byte[] keyPairBPrivate = keyPairB.getPrivate().getEncoded();
      byte[] keyPairBPublic = keyPairB.getPublic().getEncoded();
      System.out.println("乙方私钥:" + encoder.encodeToString(keyPairBPrivate, "UTF-8"));
      System.out.println("乙方公钥:" + encoder.encodeToString(keyPairBPublic, "UTF-8"));
      for (JDHSymmetricalAlgorithm algorithm : JDHSymmetricalAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("对称算法:" + algorithm);
         byte[] encrypt = JDH.encrypt(str.getBytes(), keyPairAPrivate, keyPairBPublic, algorithm);
         System.out.println("加密:" + encoder.encodeToString(encrypt, "UTF-8"));
         System.out.println("解密:" + new String(JDH.decrypt(encrypt, keyPairBPrivate, keyPairAPublic, algorithm)));

         System.out.print("输出流加密:" + file.getAbsolutePath());
         OutputStream out = JDH.wrap(new FileOutputStream(file), keyPairAPrivate, keyPairBPublic, algorithm);
         out.write(str.getBytes());
         out.flush();
         out.close();
         System.out.println();
         System.out.print("输入流解密:");
         InputStream in = JDH.wrap(new FileInputStream(file), keyPairBPrivate, keyPairAPublic, algorithm);
         byte[] buffer = new byte[1024];
         int len = in.read(buffer);
         System.out.println(new String(buffer, 0, len));
      }
   }
}

2.9 DSA(Digital Signature Algorithm)

package com.jianggujin.codec.test;

import java.io.File;
import java.security.KeyPair;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JDSA;
import com.jianggujin.codec.JDSA.JDSASignatureAlgorithm;
import com.jianggujin.codec.util.JCodecUtils;

public class DSATest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      KeyPair keyPair = JDSA.initKey();

      byte[] keyPairPrivate = keyPair.getPrivate().getEncoded();
      byte[] keyPairPublic = keyPair.getPublic().getEncoded();
      System.out.println("私钥:" + encoder.encodeToString(keyPairPrivate, "UTF-8"));
      System.out.println("公钥:" + encoder.encodeToString(keyPairPublic, "UTF-8"));
      for (JDSASignatureAlgorithm algorithm : JDSASignatureAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("签名算法:" + algorithm);
         byte[] signed = JDSA.sign(str.getBytes(), keyPairPrivate, algorithm);
         System.out.println("签名:" + encoder.encodeToString(signed, "UTF-8"));
         JCodecUtils.getPublicKey(keyPairPublic, "DSA");
         boolean verify = JDSA.verify(str.getBytes(), signed, keyPairPublic, algorithm);
         System.out.println("验签:" + verify);
      }
   }
}

2.10 PBE(基于密码加密 Password-based encryption)

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JPBE;
import com.jianggujin.codec.JPBE.JPBEAlgorithm;

public class PBETest {
   String str = "jianggujin";
   String password = "12345678";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      byte[] salt = JPBE.initSalt();
      System.out.println("盐:" + encoder.encodeToString(salt, "UTF-8"));
      System.out.println("密码:" + password);
      for (JPBEAlgorithm algorithm : JPBEAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("算法:" + algorithm);
         byte[] encrypt = JPBE.encrypt(str.getBytes(), password.toCharArray(), salt, algorithm);
         System.out.println("加密:" + encoder.encodeToString(encrypt, "UTF-8"));
         System.out.println("解密:" + new String(JPBE.decrypt(encrypt, password.toCharArray(), salt, algorithm)));

         System.out.print("输出流加密:" + file.getAbsolutePath());
         OutputStream out = JPBE.wrap(new FileOutputStream(file), password.toCharArray(), salt, algorithm);
         out.write(str.getBytes());
         out.flush();
         out.close();
         System.out.println();
         System.out.print("输入流解密:");
         InputStream in = JPBE.wrap(new FileInputStream(file), password.toCharArray(), salt, algorithm);
         byte[] buffer = new byte[1024];
         int len = in.read(buffer);
         System.out.println(new String(buffer, 0, len));
      }
   }
}

2.11 RSA

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import org.junit.Test;
import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JRSA;
import com.jianggujin.codec.JRSA.JRSASignatureAlgorithm;

public class RSATest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      KeyPair keyPair = JRSA.initKey();
      byte[] privateKey = keyPair.getPrivate().getEncoded();
      byte[] publicKey = keyPair.getPublic().getEncoded();
      System.out.println("私钥:" + encoder.encodeToString(privateKey, "UTF-8"));
      System.out.println("公钥:" + encoder.encodeToString(publicKey, "UTF-8"));
      for (JRSASignatureAlgorithm algorithm : JRSASignatureAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("签名算法:" + algorithm);
         byte[] signed = JRSA.sign(str.getBytes(), privateKey, algorithm);
         System.out.println("签名:" + encoder.encodeToString(signed, "UTF-8"));

         boolean verify = JRSA.verify(str.getBytes(), signed, publicKey, algorithm);
         System.out.println("验签:" + verify);
      }

      byte[] encrypt = JRSA.encryptByPrivateKey(str.getBytes(), privateKey);
      System.out.println("私钥加密:" + encoder.encodeToString(encrypt, "UTF-8"));
      System.out.println("公钥解密:" + new String(JRSA.decryptByPublicKey(encrypt, publicKey)));

      System.out.print("输出流私钥加密:" + file.getAbsolutePath());
      OutputStream out = JRSA.wrapByPrivateKey(new FileOutputStream(file), privateKey);
      out.write(str.getBytes());
      out.flush();
      out.close();
      System.out.println();
      System.out.print("输入流公钥解密:");
      InputStream in = JRSA.wrapByPublicKey(new FileInputStream(file), publicKey);
      byte[] buffer = new byte[1024];
      int len = in.read(buffer);
      System.out.println(new String(buffer, 0, len));

      encrypt = JRSA.encryptByPublicKey(str.getBytes(), publicKey);
      System.out.println("公钥加密:" + encoder.encodeToString(encrypt, "UTF-8"));
      System.out.println("私钥解密:" + new String(JRSA.decryptByPrivateKey(encrypt, privateKey)));

      System.out.print("输出流公钥加密:" + file.getAbsolutePath());
      out = JRSA.wrapByPublicKey(new FileOutputStream(file), publicKey);
      out.write(str.getBytes());
      out.flush();
      out.close();
      System.out.println();
      System.out.print("输入流私钥解密:");
      in = JRSA.wrapByPrivateKey(new FileInputStream(file), privateKey);
      len = in.read(buffer);
      System.out.println(new String(buffer, 0, len));
   }
}

2.12 Certificate(数字证书)

package com.jianggujin.codec.test;

import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;

import org.junit.Test;

import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JCertificate;
import com.jianggujin.codec.JCertificate.JKeyStore;

public class CertificateTest {
   @Test
   public void encode() throws Exception {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      char[] password = "123456".toCharArray();
      String alias = "www.jianggujin.com";
      String certificatePath = "test.cer";
      String keyStorePath = "test.pfx";
      byte[] data = "jianggujin".getBytes();

      KeyStore keyStore = JCertificate.getKeyStore(getClass().getResourceAsStream(keyStorePath), password,
            JKeyStore.JKS);
      X509Certificate certificate = (X509Certificate) JCertificate
            .getCertificate(getClass().getResourceAsStream(certificatePath));
      PrivateKey privateKey = JCertificate.getPrivateKey(keyStore, alias, password);
      PublicKey publicKey = JCertificate.getPublicKey(certificate);

      System.out.println("是否有效:" + JCertificate.verifyCertificate(certificate));
      System.out.println("使用者:" + certificate.getSubjectDN().getName());
      System.out.println("版本:" + certificate.getVersion());
      System.out.println("序列号:" + certificate.getSerialNumber().toString(16));
      System.out.println("签名算法:" + certificate.getSigAlgName());
      System.out.println("证书类型:" + certificate.getType());
      System.out.println("颁发者:" + certificate.getIssuerDN().getName());
      System.out.println(
            "有效期:" + format.format(certificate.getNotBefore()) + "到" + format.format(certificate.getNotAfter()));

      byte[] signResult = JCertificate.sign(data, keyStore, alias, password);
      System.out.println("签名:" + JBase64.getEncoder().encodeToString(signResult, "UTF-8"));
      System.out.println("证书验签:" + JCertificate.verify(data, signResult, certificate));
      System.out.println("密钥库验签:" + JCertificate.verify(data, signResult, keyStore));

      byte[] result = JCertificate.encrypt(data, privateKey);
      System.out.println("私钥加密:" + JBase64.getEncoder().encodeToString(result, "UTF-8"));
      System.out.println("公钥解密:" + new String(JCertificate.decrypt(result, publicKey)));

      result = JCertificate.encrypt(data, publicKey);
      System.out.println("公钥加密:" + JBase64.getEncoder().encodeToString(result, "UTF-8"));
      System.out.println("私钥解密:" + new String(JCertificate.decrypt(result, privateKey)));
   }

   public void convert() throws Exception {
      char[] password = "123456".toCharArray();
      String keyStorePath = "test.keystore";

      KeyStore keyStore = JCertificate.getKeyStore(getClass().getResourceAsStream(keyStorePath), password,
            JKeyStore.JKS);
      KeyStore target = JCertificate.convert(keyStore, JKeyStore.PKCS12, password);
      for (String alias : JCertificate.listAlias(target)) {
         System.out.println(alias);
      }
      target.store(new FileOutputStream("test.pfx"), password);
   }
}

相关文章