mirror of
https://gitee.com/willfree/min-vpn-non-core.git
synced 2026-10-05 01:15:48 +08:00
1. 解决了go中的转json会自动将byte[]转为base64的问题;2. 去min-lib-dev化,将用到的东西全部迁过来。
This commit is contained in:
1 parent
3e96c8dc0a
commit
e01e38b817
19 files changed
+1217
-17
No files matched your search
Binary file not shown.
Binary file not shown.
@@ -87,5 +87,43 @@
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- bc库, 国密算法-->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.65</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcpkix-jdk15on</artifactId>
|
||||
<version>1.65</version>
|
||||
</dependency>
|
||||
|
||||
<!-- json -->
|
||||
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>2.2.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.2.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.2.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.json/json -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.76</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -1,10 +1,10 @@
|
||||
package Security;
|
||||
|
||||
import Security.SM2.SM2KeyPair;
|
||||
import Security.SM2.SM2PrivateKey;
|
||||
import Security.SM2.SM2PublicKey;
|
||||
import Security.SM4.BC_SM4;
|
||||
import Utils.Base64Helper;
|
||||
import minsecurity.crypto.SM4;
|
||||
import minsecurity.crypto.sm2.SM2KeyPair;
|
||||
import minsecurity.crypto.sm2.SM2PrivateKey;
|
||||
import minsecurity.crypto.sm2.SM2PublicKey;
|
||||
import org.bouncycastle.crypto.CryptoException;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/*
|
||||
* @Author: Wang Feng
|
||||
@@ -138,7 +139,7 @@ public class BC_KeyManager {
|
||||
* @throws NoSuchProviderException
|
||||
*/
|
||||
public static byte[] SM4Encrypt(String secretkey,byte[] origData) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, NoSuchProviderException {
|
||||
return SM4.encrypt_ECB_Padding(secretkey.getBytes(StandardCharsets.UTF_8),origData);
|
||||
return BC_SM4.encrypt_ECB_Padding(secretkey.getBytes(StandardCharsets.UTF_8),origData);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -154,6 +155,8 @@ public class BC_KeyManager {
|
||||
* @throws NoSuchProviderException
|
||||
*/
|
||||
public static byte[] SM4Decrypt(String secretkey,byte[] crypted) throws IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException {
|
||||
return SM4.decrypt_ECB_Padding(secretkey.getBytes(StandardCharsets.UTF_8),crypted);
|
||||
System.out.println("sec: "+secretkey);
|
||||
System.out.println("cry: "+ Arrays.toString(crypted));
|
||||
return BC_SM4.decrypt_ECB_Padding(secretkey.getBytes(StandardCharsets.UTF_8),crypted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package Security.SM2;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description:
|
||||
* @Version: 1.0.0
|
||||
* @Date: 10:51 2021/03/12
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class AsymKeyException extends Exception{
|
||||
public AsymKeyException(String msg){
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package Security.SM2;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: 归纳所用常用变量
|
||||
* @Version: 1.0.0
|
||||
* @Date: 16:40 2021/03/04
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class Common {
|
||||
public static final String BC_NAME = "BC";
|
||||
public static final String X509 = "X.509";
|
||||
public static final String ALGO_NAME_EC = "EC";
|
||||
|
||||
/* Storage */
|
||||
public static final int SQLITE = 0;
|
||||
/* PublicKeyAlgorithm */
|
||||
public static final int SM2 = 0;
|
||||
/* SignatureAlgorithm */
|
||||
public static final int SM3withSM2 = 0;
|
||||
/* SymmetricAlgorithm */
|
||||
public static final int SM4ECB = 0;
|
||||
public static final int SM4CBC = 1;
|
||||
/* KeyUsage */
|
||||
public static final int ContentCommitment = 0;
|
||||
public static final int DataEncipherment = 1;
|
||||
public static final int CertSign = 2;
|
||||
/* tpyeOfCert */
|
||||
public static final int InnerCertificate = 0;
|
||||
public static final int Certificate = 1;
|
||||
public static final int TbsCertificate = 2;
|
||||
// public enum Storage {
|
||||
// SQLITE;
|
||||
// }
|
||||
// public enum PublicKeyAlgorithm {
|
||||
// SM2;
|
||||
// }
|
||||
// public enum SignatureAlgorithm {
|
||||
// SM3withSM2
|
||||
// }
|
||||
// public enum SymmetricAlgorithm {
|
||||
// SM4ECB,
|
||||
// SM4CBC;
|
||||
// }
|
||||
// public enum KeyUsage {
|
||||
// ContentCommitment,
|
||||
// DataEncipherment,
|
||||
// CertSign;
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package Security.SM2;
|
||||
|
||||
import org.bouncycastle.crypto.CryptoException;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: 所有对称加密方法必须实现的基本方法
|
||||
* @Version: 1.0.0
|
||||
* @Date: 17:28 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public interface PrivateKeyInterface {
|
||||
public byte[] getBytes();
|
||||
public boolean setBytes(byte[] bytes);
|
||||
public byte[] decrypt(byte[] cipher) throws InvalidCipherTextException;
|
||||
public byte[] sign(byte[] content) throws CryptoException;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package Security.SM2;
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: 所有对称加密方法必须实现的基本方法
|
||||
* @Version: 1.0.0
|
||||
* @Date: 17:06 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
|
||||
public interface PublicKeyInterface {
|
||||
public byte[] getBytes();
|
||||
public boolean setBytes(byte[] bytes);
|
||||
public byte[] encrypt(byte[] content) throws InvalidCipherTextException;
|
||||
public boolean verify(byte[] content, byte[] digest);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package Security.SM2;
|
||||
|
||||
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
|
||||
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
|
||||
import org.bouncycastle.crypto.params.ECDomainParameters;
|
||||
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
|
||||
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
|
||||
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
|
||||
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
|
||||
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
|
||||
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.jce.spec.ECParameterSpec;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
import org.bouncycastle.math.ec.custom.gm.SM2P256V1Curve;
|
||||
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.*;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
import static Security.SM2.Common.ALGO_NAME_EC;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: SM2推荐曲线参数
|
||||
* @Version: 1.0.0
|
||||
* @Date: 18:48 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class SM2Base {
|
||||
|
||||
static {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
|
||||
// private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SM2Base.class);
|
||||
|
||||
/*
|
||||
* 以下为SM2推荐曲线参数
|
||||
*/
|
||||
public static final SM2P256V1Curve CURVE = new SM2P256V1Curve();
|
||||
public final static BigInteger SM2_ECC_P = CURVE.getQ();
|
||||
public final static BigInteger SM2_ECC_A = CURVE.getA().toBigInteger();
|
||||
public final static BigInteger SM2_ECC_B = CURVE.getB().toBigInteger();
|
||||
public final static BigInteger SM2_ECC_N = CURVE.getOrder();
|
||||
public final static BigInteger SM2_ECC_H = CURVE.getCofactor();
|
||||
public final static BigInteger SM2_ECC_GX = new BigInteger(
|
||||
"32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
|
||||
public final static BigInteger SM2_ECC_GY = new BigInteger(
|
||||
"BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);
|
||||
public static final ECPoint G_POINT = CURVE.createPoint(SM2_ECC_GX, SM2_ECC_GY);
|
||||
public static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters(CURVE, G_POINT,
|
||||
SM2_ECC_N, SM2_ECC_H);
|
||||
|
||||
private static final String PEM_STRING_PUBLIC = "PUBLIC KEY";
|
||||
private static final String PEM_STRING_ECPRIVATEKEY = "EC PRIVATE KEY";
|
||||
|
||||
|
||||
/**
|
||||
* 生成BC自定义的SM2公私钥
|
||||
* @param
|
||||
* @return org.bouncycastle.crypto.AsymmetricCipherKeyPair
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static AsymmetricCipherKeyPair generateKeyPairParameter(){
|
||||
SecureRandom random = new SecureRandom();
|
||||
ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS,
|
||||
random);
|
||||
ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
|
||||
keyGen.init(keyGenerationParams);
|
||||
AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair();
|
||||
return keyPair;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成java.security.KeyPair类型的SM2公私钥
|
||||
* @param
|
||||
* @return java.security.KeyPair
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static KeyPair generateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException,
|
||||
InvalidAlgorithmParameterException {
|
||||
SecureRandom random = new SecureRandom();
|
||||
return generateKeyPair(DOMAIN_PARAMS, random);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成java.security.KeyPair类型的SM2公私钥, 需自定义曲线参数
|
||||
* @param domainParameters
|
||||
* @param random
|
||||
* @return
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
|
||||
throws NoSuchProviderException, NoSuchAlgorithmException,
|
||||
InvalidAlgorithmParameterException {
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
|
||||
ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
|
||||
domainParameters.getN(), domainParameters.getH());
|
||||
kpg.initialize(parameterSpec, random);
|
||||
return kpg.generateKeyPair();
|
||||
}
|
||||
|
||||
/**
|
||||
* BC公私钥转换为java.security.KeyPair公私钥
|
||||
* @param bcKeyPair
|
||||
* @return
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static KeyPair convertBcToJceKeyPair(AsymmetricCipherKeyPair bcKeyPair) throws Exception {
|
||||
byte[] pkcs8Encoded = PrivateKeyInfoFactory.createPrivateKeyInfo(bcKeyPair.getPrivate()).getEncoded();
|
||||
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pkcs8Encoded);
|
||||
byte[] spkiEncoded = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(bcKeyPair.getPublic()).getEncoded();
|
||||
X509EncodedKeySpec spkiKeySpec = new X509EncodedKeySpec(spkiEncoded);
|
||||
KeyFactory keyFac = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
|
||||
return new KeyPair(keyFac.generatePublic(spkiKeySpec), keyFac.generatePrivate(pkcs8KeySpec));
|
||||
}
|
||||
|
||||
/**
|
||||
* java.security.KeyPair转换为BC类型的公私钥对
|
||||
* @param keyPair
|
||||
* @return
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static AsymmetricCipherKeyPair convertKeyPair2Bc(KeyPair keyPair) {
|
||||
ECPrivateKeyParameters priKey = convertPrivateKeyToParameters((BCECPrivateKey) keyPair.getPrivate());
|
||||
ECPublicKeyParameters pubKey = convertPublicKeyToParameters((BCECPublicKey) keyPair.getPublic());
|
||||
return new AsymmetricCipherKeyPair(priKey,pubKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* BCECPrivateKey类型私钥转化为ECPrivateKeyParameters类型的私钥,
|
||||
* 调用者若想将java.security.PrivateKey转化为ECPrivateKeyParameters, 调用时将其强制转换为BCECPrivateKey类型
|
||||
* @param ecPriKey
|
||||
* @return ECPrivateKeyParameters
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static ECPrivateKeyParameters convertPrivateKeyToParameters(BCECPrivateKey ecPriKey) {
|
||||
ECParameterSpec parameterSpec = ecPriKey.getParameters();
|
||||
ECDomainParameters domainParameters = new ECDomainParameters(parameterSpec.getCurve(), parameterSpec.getG(),
|
||||
parameterSpec.getN(), parameterSpec.getH());
|
||||
return new ECPrivateKeyParameters(ecPriKey.getD(), domainParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* BCECPublicKey类型私钥转化为ECPublicKeyParameters类型的私钥,
|
||||
* 调用者若想将java.security.PublicKey转化为ECPublicKeyParameters, 调用时将其强制转换为BCECPublicKey类型
|
||||
* @param ecPubKey
|
||||
* @return ECPrivateKeyParameters
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public static ECPublicKeyParameters convertPublicKeyToParameters(BCECPublicKey ecPubKey) {
|
||||
ECParameterSpec parameterSpec = ecPubKey.getParameters();
|
||||
ECDomainParameters domainParameters = new ECDomainParameters(parameterSpec.getCurve(), parameterSpec.getG(),
|
||||
parameterSpec.getN(), parameterSpec.getH());
|
||||
return new ECPublicKeyParameters(ecPubKey.getQ(), domainParameters);
|
||||
}
|
||||
/**
|
||||
* 生成一对sm2公私钥
|
||||
* @param
|
||||
* @return minsecurity.crypto.sm2.SM2KeyPair
|
||||
* @throws
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/15
|
||||
**/
|
||||
public static SM2KeyPair generateSM2KeyPair(){
|
||||
return SM2KeyPair.generateKeyPair();
|
||||
}
|
||||
|
||||
/**
|
||||
* SM2字节数组->16进制字节数组 辅助函数
|
||||
* @param bytes byte[]
|
||||
* @return byte[]
|
||||
* @throws
|
||||
* @author zhengqi wu
|
||||
* @date 2021/4/12
|
||||
**/
|
||||
public static byte[] byteArraytoHexByteArray(byte[] bytes){
|
||||
// 16进制表示法
|
||||
// StringBuilder sb = new StringBuilder();
|
||||
// for(int i=0;i < bytes.length;i++) {
|
||||
// sb.append(String.format("%02x", bytes[i]));
|
||||
// }
|
||||
String hexStr = ByteUtils.toHexString(bytes);
|
||||
return hexStr.getBytes();
|
||||
}
|
||||
|
||||
/**
|
||||
* 16进制字节数组->SM2字节数组 辅助函数
|
||||
* @param bytes byte[]
|
||||
* @return byte[]
|
||||
* @throws
|
||||
* @author zhengqi wu
|
||||
* @date 2021/4/12
|
||||
**/
|
||||
public static byte[] hexByteArrayToByteArray(byte[] bytes){
|
||||
String hex = new String(bytes);
|
||||
if (hex.length() < 1) {
|
||||
return null;
|
||||
} else {
|
||||
byte[] result = new byte[hex.length() / 2];
|
||||
int j = 0;
|
||||
for(int i = 0; i < hex.length(); i+=2) {
|
||||
result[j++] = (byte)Integer.parseInt(hex.substring(i,i+2), 16);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package Security.SM2;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: sm2的自定义异常
|
||||
* @Version: 1.0.0
|
||||
* @Date: 19:00 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class SM2Exception extends AsymKeyException {
|
||||
public SM2Exception(String msg){
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package Security.SM2;
|
||||
|
||||
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
|
||||
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description:
|
||||
* @Version: 1.0.0
|
||||
* @Date: 09:57 2021/03/11
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class SM2KeyPair {
|
||||
private final SM2PublicKey sm2PublicKey;
|
||||
private final SM2PrivateKey sm2PrivateKey;
|
||||
|
||||
public SM2KeyPair(SM2PublicKey sm2PublicKey, SM2PrivateKey sm2PrivateKey) {
|
||||
this.sm2PublicKey = sm2PublicKey;
|
||||
this.sm2PrivateKey = sm2PrivateKey;
|
||||
}
|
||||
|
||||
public static SM2KeyPair generateKeyPair(){
|
||||
AsymmetricCipherKeyPair keyPair = SM2Base.generateKeyPairParameter();
|
||||
ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
|
||||
ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();
|
||||
byte[] d = priKey.getD().toByteArray();
|
||||
byte[] x = pubKey.getQ().getAffineXCoord().getEncoded();
|
||||
byte[] y = pubKey.getQ().getAffineYCoord().getEncoded();
|
||||
return new SM2KeyPair(new SM2PublicKey(x,y), new SM2PrivateKey(d));
|
||||
}
|
||||
|
||||
|
||||
public SM2PublicKey getSm2PublicKey() {
|
||||
return sm2PublicKey;
|
||||
}
|
||||
|
||||
public SM2PrivateKey getSm2PrivateKey() {
|
||||
return sm2PrivateKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package Security.SM2;
|
||||
|
||||
import org.bouncycastle.crypto.CipherParameters;
|
||||
import org.bouncycastle.crypto.CryptoException;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
import org.bouncycastle.crypto.engines.SM2Engine;
|
||||
import org.bouncycastle.crypto.params.ECDomainParameters;
|
||||
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.params.ParametersWithRandom;
|
||||
import org.bouncycastle.crypto.signers.SM2Signer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: 国密sm2 非对称加密私钥
|
||||
* @Version: 1.0.0
|
||||
* @Date: 19:40 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class SM2PrivateKey implements PrivateKeyInterface {
|
||||
|
||||
public SM2PrivateKey(){}
|
||||
|
||||
/*
|
||||
* @param d
|
||||
* @return
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
|
||||
/*
|
||||
* @param d 大数
|
||||
* @return
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public SM2PrivateKey(byte[] d) {
|
||||
privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
|
||||
}
|
||||
public SM2PrivateKey(byte[] d, ECDomainParameters parameters){
|
||||
if(d.length == 32 || d.length == 33)
|
||||
privateKey = new ECPrivateKeyParameters(new BigInteger(d), parameters);
|
||||
else {
|
||||
try {
|
||||
throw new SM2Exception("SM2私钥中,参数d长度应为32/33");
|
||||
} catch (SM2Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() {
|
||||
byte[] bytes = privateKey.getD().toByteArray();
|
||||
return SM2Base.byteArraytoHexByteArray(bytes);
|
||||
}
|
||||
|
||||
@Override
|
||||
// public boolean setBytes(byte[] d) {
|
||||
// // TODO 待与go版本进行兼容 目前版本无法使用
|
||||
// if(d.length != 32 && d.length != 33)
|
||||
// return false;
|
||||
// privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
|
||||
// return true;
|
||||
// }
|
||||
|
||||
/**
|
||||
* @description 与external_amd64同步
|
||||
* @params d {byte[]}
|
||||
* @return boolean
|
||||
*/
|
||||
// TODO 实现不同
|
||||
public boolean setBytes(byte[] d){
|
||||
if (d.length != 64 && d.length != 66 && d.length != 32 && d.length != 33)
|
||||
return false;
|
||||
switch (d.length){
|
||||
case 32:
|
||||
case 33:
|
||||
privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
|
||||
break;
|
||||
case 64:
|
||||
case 66:
|
||||
d = SM2Base.hexByteArrayToByteArray(d);
|
||||
privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] decrypt(byte[] cipher) throws InvalidCipherTextException {
|
||||
SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
|
||||
engine.init(false, privateKey);
|
||||
return engine.processBlock(cipher, 0, cipher.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(byte[] content) throws CryptoException {
|
||||
SM2Signer signer = new SM2Signer();
|
||||
CipherParameters param = null;
|
||||
ParametersWithRandom pwr = new ParametersWithRandom(privateKey, new SecureRandom());
|
||||
param = pwr;
|
||||
signer.init(true, param);
|
||||
signer.update(content, 0, content.length);
|
||||
return signer.generateSignature();
|
||||
}
|
||||
|
||||
private ECPrivateKeyParameters privateKey;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package Security.SM2;
|
||||
|
||||
import org.bouncycastle.crypto.CipherParameters;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
import org.bouncycastle.crypto.engines.SM2Engine;
|
||||
import org.bouncycastle.crypto.params.ECDomainParameters;
|
||||
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
|
||||
import org.bouncycastle.crypto.params.ParametersWithRandom;
|
||||
import org.bouncycastle.crypto.signers.SM2Signer;
|
||||
import org.bouncycastle.math.ec.ECCurve;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: 国密sm2 非对称加密公钥, 实现PublicKeyInterface中的方法
|
||||
* @Version: 1.0.0
|
||||
* @Date: 17:32 2021/03/03
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class SM2PublicKey implements PublicKeyInterface {
|
||||
|
||||
public SM2PublicKey(){}
|
||||
|
||||
public SM2PublicKey(byte[] xBytes, byte[] yBytes, ECCurve curve, ECDomainParameters domainParameters){
|
||||
publicKey = createPublicKey(xBytes,yBytes,curve,domainParameters);
|
||||
}
|
||||
/**
|
||||
* 使用SM2推荐曲线参数
|
||||
* @param xBytes 曲线x参数
|
||||
* @param yBytes 曲线y参数
|
||||
* @return
|
||||
* @author ghy
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
public SM2PublicKey(byte[] xBytes, byte[] yBytes){
|
||||
this(xBytes,yBytes, SM2Base.CURVE, SM2Base.DOMAIN_PARAMS);
|
||||
}
|
||||
|
||||
public SM2PublicKey(byte[] bytes){
|
||||
setBytes(bytes);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() {
|
||||
if(publicKey != null){
|
||||
byte[] bytes = publicKey.getQ().getEncoded(false); //不压缩
|
||||
byte[] basic = SM2Base.byteArraytoHexByteArray(bytes);
|
||||
return basic;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setBytes(byte[] bytes) {
|
||||
switch (bytes.length){
|
||||
case 65:
|
||||
createPub(bytes);
|
||||
break;
|
||||
case 130:
|
||||
bytes = SM2Base.hexByteArrayToByteArray(bytes); // 16进制表示法转为十进制表示法
|
||||
createPub(bytes);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void createPub(byte[] bytes){
|
||||
ByteBuffer encoded = ByteBuffer.wrap(bytes);
|
||||
byte[] x = new byte[32];
|
||||
byte[] y = new byte[32];
|
||||
encoded.position(1);
|
||||
encoded.get(x,0,32);
|
||||
encoded.get(y,0,32);
|
||||
publicKey = createPublicKey(x,y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param content
|
||||
* @return byte[] 密文
|
||||
* @author ghy
|
||||
* @date 2021/3/7
|
||||
**/
|
||||
@Override
|
||||
public byte[] encrypt(byte[] content) throws InvalidCipherTextException {
|
||||
SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
|
||||
ParametersWithRandom pwr = new ParametersWithRandom(publicKey, new SecureRandom());
|
||||
engine.init(true, pwr);
|
||||
return engine.processBlock(content, 0, content.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(byte[] content, byte[] digest) {
|
||||
SM2Signer signer = new SM2Signer();
|
||||
CipherParameters param = publicKey;
|
||||
signer.init(false, param);
|
||||
signer.update(content, 0, content.length);
|
||||
return signer.verifySignature(digest);
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////// private start //////////////////////////////////////////////
|
||||
private static ECPublicKeyParameters createPublicKey(
|
||||
byte[] xBytes, byte[] yBytes, ECCurve curve, ECDomainParameters domainParameters){
|
||||
final byte uncompressedFlag = 0x04;
|
||||
int curveLength = getCurveLength(domainParameters);
|
||||
xBytes = fixToCurveLengthBytes(curveLength, xBytes);
|
||||
yBytes = fixToCurveLengthBytes(curveLength, yBytes);
|
||||
byte[] encodedPubKey = new byte[1 + xBytes.length + yBytes.length];
|
||||
encodedPubKey[0] = uncompressedFlag;
|
||||
System.arraycopy(xBytes, 0, encodedPubKey, 1, xBytes.length);
|
||||
System.arraycopy(yBytes, 0, encodedPubKey, 1 + xBytes.length, yBytes.length);
|
||||
return new ECPublicKeyParameters(curve.decodePoint(encodedPubKey), domainParameters);
|
||||
}
|
||||
|
||||
private static ECPublicKeyParameters createPublicKey(byte[] xBytes, byte[] yBytes){
|
||||
return createPublicKey(xBytes,yBytes, SM2Base.CURVE, SM2Base.DOMAIN_PARAMS);
|
||||
}
|
||||
|
||||
private static int getCurveLength(ECDomainParameters domainParams) {
|
||||
return (domainParams.getCurve().getFieldSize() + 7) / 8;
|
||||
}
|
||||
|
||||
private static byte[] fixToCurveLengthBytes(int curveLength, byte[] src) {
|
||||
if (src.length == curveLength) {
|
||||
return src;
|
||||
}
|
||||
|
||||
byte[] result = new byte[curveLength];
|
||||
if (src.length > curveLength) {
|
||||
System.arraycopy(src, src.length - result.length, result, 0, result.length);
|
||||
} else {
|
||||
System.arraycopy(src, 0, result, result.length - src.length, src.length);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private ECPublicKeyParameters publicKey;
|
||||
////////////////////////////////////////////// private end //////////////////////////////////////////////
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package Security.SM4;
|
||||
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
import javax.crypto.*;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.*;
|
||||
|
||||
/*
|
||||
* @Author: hongyu guo
|
||||
* @Description: sm4算法
|
||||
* @Version: 1.0.0
|
||||
* @Date: 16:26 2021/03/04
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class BC_SM4 {
|
||||
static {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
public static final String ALGORITHM_NAME = "SM4";
|
||||
public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
|
||||
public static final String ALGORITHM_NAME_ECB_NOPADDING = "SM4/ECB/NoPadding";
|
||||
public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";
|
||||
public static final String ALGORITHM_NAME_CBC_NOPADDING = "SM4/CBC/NoPadding";
|
||||
|
||||
/**
|
||||
* SM4算法目前只支持128位(即密钥16字节)
|
||||
*/
|
||||
public static final int DEFAULT_KEY_SIZE = 128;
|
||||
|
||||
/**
|
||||
* 生成16字节的sm4 key
|
||||
* @param
|
||||
* @return byte[]
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @author hongyu guo
|
||||
* @date 2021/3/15
|
||||
**/
|
||||
public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {
|
||||
return generateKey(DEFAULT_KEY_SIZE);
|
||||
}
|
||||
|
||||
public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
|
||||
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
|
||||
kg.init(keySize, new SecureRandom());
|
||||
return kg.generateKey().getEncoded();
|
||||
}
|
||||
|
||||
public static byte[] encrypt_ECB_Padding(byte[] key, byte[] data)
|
||||
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
|
||||
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
|
||||
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
public static byte[] decrypt_ECB_Padding(byte[] key, byte[] cipherText)
|
||||
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
|
||||
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
|
||||
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
|
||||
return cipher.doFinal(cipherText);
|
||||
}
|
||||
|
||||
public static byte[] encrypt_ECB_NoPadding(byte[] key, byte[] data)
|
||||
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
|
||||
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
|
||||
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_NOPADDING, Cipher.ENCRYPT_MODE, key);
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
public static byte[] decrypt_ECB_NoPadding(byte[] key, byte[] cipherText)
|
||||
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
|
||||
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
|
||||
Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_NOPADDING, Cipher.DECRYPT_MODE, key);
|
||||
return cipher.doFinal(cipherText);
|
||||
}
|
||||
|
||||
public static byte[] encrypt_CBC_Padding(byte[] key, byte[] iv, byte[] data)
|
||||
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
|
||||
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
|
||||
InvalidAlgorithmParameterException {
|
||||
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
public static byte[] decrypt_CBC_Padding(byte[] key, byte[] iv, byte[] cipherText)
|
||||
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
|
||||
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
|
||||
InvalidAlgorithmParameterException {
|
||||
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
|
||||
return cipher.doFinal(cipherText);
|
||||
}
|
||||
|
||||
public static byte[] encrypt_CBC_NoPadding(byte[] key, byte[] iv, byte[] data)
|
||||
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
|
||||
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
|
||||
InvalidAlgorithmParameterException {
|
||||
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_NOPADDING, Cipher.ENCRYPT_MODE, key, iv);
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
public static byte[] decrypt_CBC_NoPadding(byte[] key, byte[] iv, byte[] cipherText)
|
||||
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
|
||||
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
|
||||
InvalidAlgorithmParameterException {
|
||||
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_NOPADDING, Cipher.DECRYPT_MODE, key, iv);
|
||||
return cipher.doFinal(cipherText);
|
||||
}
|
||||
|
||||
private static Cipher generateECBCipher(String algorithmName, int mode, byte[] key)
|
||||
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
|
||||
InvalidKeyException {
|
||||
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
|
||||
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
|
||||
cipher.init(mode, sm4Key);
|
||||
return cipher;
|
||||
}
|
||||
|
||||
private static Cipher generateCBCCipher(String algorithmName, int mode, byte[] key, byte[] iv)
|
||||
throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
|
||||
NoSuchProviderException, NoSuchPaddingException {
|
||||
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
|
||||
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
|
||||
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
|
||||
cipher.init(mode, sm4Key, ivParameterSpec);
|
||||
return cipher;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package TCPNet;
|
||||
import Security.BC_KeyManager;
|
||||
import TCPNet.request.BaseRequest;
|
||||
import TCPNet.response.BaseResponse;
|
||||
import Utils.Base64Helper;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.parser.JSONToken;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
@@ -59,7 +60,10 @@ class SSL_Message extends BaseRequest{
|
||||
Field thisf = thiscls.getDeclaredField(f.getName());
|
||||
thisf.setAccessible(true);
|
||||
if(thisf.getType()==(byte[].class)){
|
||||
thisf.set(this, ((String)(f.get(newObj))).getBytes(StandardCharsets.UTF_8));
|
||||
// byte[]需要解码base64
|
||||
String base64S=(String)(f.get(newObj));
|
||||
byte[] decodeBytes= Base64Helper.BlockChain_Base64Decode_GoLanUn(base64S);
|
||||
thisf.set(this, decodeBytes);
|
||||
}else {
|
||||
thisf.set(this, f.get(newObj));
|
||||
}
|
||||
@@ -154,15 +158,15 @@ public class SSL {
|
||||
System.out.println("secretkey: "+secretKey);
|
||||
// 用对称密钥解密应答信息
|
||||
byte[] decRes;
|
||||
// try {
|
||||
try {
|
||||
// todo:这里sm4有问题
|
||||
decRes="{\"Code\":200}".getBytes(StandardCharsets.UTF_8);
|
||||
// decRes=BC_KeyManager.SM4Decrypt(secretKey,resData);
|
||||
// } catch (IllegalBlockSizeException | InvalidKeyException | NoSuchProviderException
|
||||
// | NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException e) {
|
||||
// e.printStackTrace();
|
||||
// return null;
|
||||
// }
|
||||
// decRes="{\"Code\":200}".getBytes(StandardCharsets.UTF_8);
|
||||
decRes=BC_KeyManager.SM4Decrypt(secretKey,resData);
|
||||
} catch (IllegalBlockSizeException | InvalidKeyException | NoSuchProviderException
|
||||
| NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
// 将解密信息转为Java对象
|
||||
SSL_RespMessage resp=new SSL_RespMessage();
|
||||
|
||||
@@ -2,7 +2,7 @@ package TCPNet;
|
||||
|
||||
import Encoding.BC_Encoder;
|
||||
import Security.BC_KeyManager;
|
||||
import util.ByteHelper;
|
||||
import Utils.ByteHelper;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
|
||||
@@ -35,4 +35,14 @@ public class Base64Helper {
|
||||
Base64.Decoder decoder = Base64.getUrlDecoder();
|
||||
return decoder.decode(src.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 参考链接: https://blog.csdn.net/qq_36928715/article/details/110489464
|
||||
* golang的Unmarshal函数,自动把结构体中的base64转成了byte[],这里填补java的此功能
|
||||
* @return
|
||||
*/
|
||||
public static byte[] BlockChain_Base64Decode_GoLanUn(String src){
|
||||
edu.pku.commons.codec.binary.Base64 decoder = new edu.pku.commons.codec.binary.Base64();
|
||||
return decoder.decode(src);
|
||||
}
|
||||
}
|
||||
@@ -45,4 +45,354 @@ public class ByteHelper {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取从start到末尾的字节数组
|
||||
* @param buffer
|
||||
* @param startIndex
|
||||
* @return
|
||||
*/
|
||||
public static byte[] getTailBytes(byte[] buffer,int startIndex) {
|
||||
if(startIndex >= buffer.length || startIndex < 0)
|
||||
return null;
|
||||
int len=buffer.length-startIndex;
|
||||
byte[] newBytes=new byte[len];
|
||||
System.arraycopy(buffer,startIndex,newBytes,0,len);
|
||||
return newBytes;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 从byte[]数组指定开始位置获取第一个字节
|
||||
// *
|
||||
// * @param buffer
|
||||
// * @param start
|
||||
//// * @return
|
||||
//// */
|
||||
// public static byte getFirstByte(byte[] buffer, VlInt start) throws ByteHelperException {
|
||||
// int startInt= 0;
|
||||
// try {
|
||||
// startInt = start.getVlIntValue2Int();
|
||||
// } catch (VlIntException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// if(startInt >= buffer.length || startInt < 0){
|
||||
// throw new ByteHelperException("buffer out of bounds");
|
||||
// }
|
||||
// return buffer[startInt];
|
||||
// // byte[] firstbyte=new byte[1];
|
||||
// // System.arraycopy(buffer,startInt,firstbyte,0,firstbyte.length);
|
||||
// // return firstbyte[0];
|
||||
// }
|
||||
public static byte getFirstByte(byte[] buffer, int startInt) throws Exception {
|
||||
if(startInt >= buffer.length || startInt < 0){
|
||||
throw new Exception("buffer out of bounds");
|
||||
}
|
||||
return buffer[startInt];
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 从byte[]数组指定开始位置获取长度为len的字节数组
|
||||
// * todo: start位置可能是大于int类型的数值
|
||||
// * @param buffer
|
||||
// * @param start
|
||||
// * @return
|
||||
// */
|
||||
// public static byte[] getLenBytes(byte[] buffer, VlInt start,VlInt len) throws ByteHelperException {
|
||||
// int startInt= -1;
|
||||
// int lenInt = -1;
|
||||
// try {
|
||||
// startInt = start.getVlIntValue2Int();
|
||||
// lenInt=len.getVlIntValue2Int();
|
||||
// } catch (VlIntException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// if(startInt >= buffer.length || startInt < 0){
|
||||
// throw new ByteHelperException("buffer out of bounds");
|
||||
// }
|
||||
// if(lenInt < 0){
|
||||
// throw new ByteHelperException("len should > 0");
|
||||
// }
|
||||
// byte[] lenbytes=new byte[lenInt];
|
||||
//// byte[] lenbytes=new byte[1];
|
||||
// System.arraycopy(buffer,startInt,lenbytes,0,lenInt);
|
||||
// return lenbytes;
|
||||
// }
|
||||
// public static byte[] getLenBytes(byte[] buffer, VlInt start,int len){
|
||||
// int startInt= -1;
|
||||
// try {
|
||||
// startInt = start.getVlIntValue2Int();
|
||||
// } catch (VlIntException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// byte[] lenbytes=new byte[len];
|
||||
//// byte[] lenbytes=new byte[1];
|
||||
// System.arraycopy(buffer,startInt,lenbytes,0,len);
|
||||
// return lenbytes;
|
||||
// }
|
||||
public static byte[] getLenBytes(byte[] buffer, int startInt,int len){
|
||||
byte[] lenbytes=new byte[len];
|
||||
System.arraycopy(buffer,startInt,lenbytes,0,len);
|
||||
return lenbytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无符号int转byte[]
|
||||
* @param i_int
|
||||
* @return
|
||||
*/
|
||||
private static byte[] intToByteArray(int i_int) {
|
||||
byte[] result = new byte[4];
|
||||
//由高位到低位
|
||||
for(int i=0;i<4;i++) {
|
||||
int offset=(result.length-i-1)*8;
|
||||
result[i] = (byte) ((i_int >>>offset) & 0xff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无符号byte[]转int
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
private static int byteArrayToInt(byte[] bytes) {
|
||||
if(bytes.length!=4){
|
||||
return Integer.parseInt(null);
|
||||
}
|
||||
int value= 0;
|
||||
//由高位到低位
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int offset= (bytes.length - 1 - i) * 8;
|
||||
value +=(bytes[i] & 0x000000ff) << offset; //往高位游
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无符号long转byte[]
|
||||
* @param l_long
|
||||
* @return
|
||||
*/
|
||||
private static byte[] longToByteArray(long l_long) {
|
||||
byte[] result = new byte[8];
|
||||
for (int i = 0; i<8; i++) {
|
||||
int offset = (result.length - 1 - i) * 8;
|
||||
result[i] = (byte) ((l_long >>> offset) & 0xff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无符号byte[]转long
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
private static long byteArrayToLong(byte[] bytes) {
|
||||
if(bytes.length!=8){
|
||||
return Integer.parseInt(null);
|
||||
}
|
||||
long value= 0;
|
||||
//由高位到低位
|
||||
for (int i = 0; i < 8; i++) {
|
||||
int offset= (bytes.length - 1 - i) * 8;
|
||||
value +=((long)bytes[i] & 0xff) << offset; //往高位游
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无符号字节转int
|
||||
* @param b
|
||||
* @return
|
||||
*/
|
||||
// private static int unsignedbyte2int(byte b){
|
||||
// return (int) b&0xff;
|
||||
// }
|
||||
|
||||
/**
|
||||
* uint8转int
|
||||
* @param uint8
|
||||
* @return
|
||||
*/
|
||||
public static int uint8ToInt(byte uint8){
|
||||
return uint8 & 0xff;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个uint8转为的int,通过本函数再次转为byte
|
||||
* @param uint8
|
||||
* @return
|
||||
*/
|
||||
public static byte uint8ToByte(int uint8){
|
||||
return (byte)(uint8 & 0xff);
|
||||
}
|
||||
|
||||
/**
|
||||
* uint8转long
|
||||
* @param uint8
|
||||
* @return
|
||||
*/
|
||||
public static long uint8ToLong(byte uint8){
|
||||
return uint8ToInt(uint8);
|
||||
}
|
||||
|
||||
/**
|
||||
* uint16转int
|
||||
* @param uint16
|
||||
* @return
|
||||
*/
|
||||
public static int uint16ToInt(byte[] uint16){
|
||||
if(uint16.length!=2){
|
||||
return Integer.parseInt(null);
|
||||
}
|
||||
byte[] bytes=new byte[4];
|
||||
for(int i=0;i<2;i++) {
|
||||
bytes[i] = 0x00;
|
||||
}
|
||||
System.arraycopy(uint16,0,bytes,2,uint16.length);
|
||||
return byteArrayToInt(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个uint16转为的int,通过本函数再次转为byte[]
|
||||
* @param uint16
|
||||
* @return
|
||||
*/
|
||||
public static byte[] uint16ToByteArray(int uint16){
|
||||
byte[] result = new byte[2];
|
||||
for (int i = 0; i<2; i++) {
|
||||
int offset = (result.length - 1 - i) * 8;
|
||||
result[i] = (byte) ((uint16 >>> offset) & 0xff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* uint16转long
|
||||
* @param uint16
|
||||
* @return
|
||||
*/
|
||||
public static long uint16ToLong(byte[] uint16){
|
||||
return uint16ToInt(uint16);
|
||||
}
|
||||
|
||||
/**
|
||||
* uint32转long
|
||||
* @param uint32
|
||||
* @return
|
||||
*/
|
||||
public static long uint32ToLong(byte[] uint32){
|
||||
if(uint32.length!=4){
|
||||
return Long.parseLong(null);
|
||||
}
|
||||
byte[] bytes=new byte[8];
|
||||
for(int i=0;i<4;i++) {
|
||||
bytes[i] = 0x00;
|
||||
}
|
||||
System.arraycopy(uint32,0,bytes,4,uint32.length);
|
||||
// System.out.println(Arrays.toString(uint32) + "uint32ToLong: " + Arrays.toString(bytes));
|
||||
return byteArrayToLong(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个uint32转为的long,通过本函数再次转为byte[]
|
||||
* @param uint32
|
||||
* @return
|
||||
*/
|
||||
public static byte[] uint32ToByteArray(long uint32){
|
||||
byte[] result = new byte[4];
|
||||
for (int i = 0; i<4; i++) {
|
||||
int offset = (result.length - 1 - i) * 8;
|
||||
result[i] = (byte) ((uint32 >>> offset) & 0xff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* uint64转long
|
||||
* todo: 理论上可能发生越界
|
||||
* @param uint64
|
||||
* @return
|
||||
*/
|
||||
public static long uint64ToLong(byte[] uint64){
|
||||
if(uint64.length!=8){
|
||||
return Long.parseLong(null);
|
||||
}
|
||||
return byteArrayToLong(uint64);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 一个uint64转为的long,通过本函数再次转为byte[]
|
||||
* todo: 理论上可能发生越界
|
||||
* @param uint64
|
||||
* @return
|
||||
*/
|
||||
public static byte[] uint64ToByteArray(long uint64){
|
||||
byte[] result = new byte[8];
|
||||
for (int i = 0; i<8; i++) {
|
||||
int offset = (result.length - 1 - i) * 8;
|
||||
result[i] = (byte) ((uint64 >>> offset) & 0xff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// short整型转为byte类型的数组
|
||||
// private static byte[] unsigned_short_2byte(int length) {
|
||||
// byte[] targets = new byte[2];
|
||||
// for (int i = 0; i < 2; i++) {
|
||||
// int offset = (targets.length - 1 - i) * 8;
|
||||
// targets[i] = (byte) ((length >>> offset) & 0xff);
|
||||
// }
|
||||
// return targets;
|
||||
// }
|
||||
|
||||
//测试:对于uint8,应当测试1 127 128
|
||||
public static void main(String[] args){
|
||||
|
||||
// byte[] testBytes={0x01,0x02};
|
||||
// for(int i=0;i<2;i++) {
|
||||
// System.out.println(testBytes[i]&0xFF);
|
||||
//// System.out.println(Integer.toHexString(testBytes[i]&0xFF));
|
||||
// }
|
||||
byte b=-1;
|
||||
System.out.println(b&0xff);
|
||||
}
|
||||
|
||||
// 便于测试,新添加两个public方法:
|
||||
// 无符号byte[]转int
|
||||
// 传入的是长度为2或4的byte[]
|
||||
public static int new_byteArrayToInt(byte[] bytes){
|
||||
int value= 0;
|
||||
//由高位到低位
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int offset= (bytes.length - 1 - i) * 8;
|
||||
value +=(bytes[i] & 0x000000ff) << offset; //往高位游
|
||||
}
|
||||
return value;
|
||||
}
|
||||
// 便于测试,新添加两个public方法:
|
||||
// 无符号byte[]转int(溢出部分)
|
||||
// 传入的是长度为4的byte[]
|
||||
public static long new_byteArrayToAllInt(byte[] bytes){
|
||||
int v=new_byteArrayToInt(bytes);
|
||||
if(v<0){
|
||||
return (long) (v+Math.pow(2,32));
|
||||
}else{
|
||||
return v;
|
||||
}
|
||||
}
|
||||
// 无符号byte[]转long
|
||||
// 传入的是长度为8的byte[]
|
||||
public static long new_byteArrayToLong(byte[] bytes){
|
||||
long value= 0;
|
||||
//由高位到低位
|
||||
for (int i = 0; i < 8; i++) {
|
||||
int offset= (8 - 1 - i) * 8;
|
||||
value +=((long)bytes[i] & 0xff) << offset; //往高位游
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,17 @@
|
||||
package Utils;
|
||||
|
||||
import Security.BC_KeyManager;
|
||||
import edu.pku.commons.codec.binary.Base64;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/*
|
||||
* @Author: Wang Feng
|
||||
* @Description:
|
||||
@@ -12,10 +22,34 @@ import org.junit.Test;
|
||||
public class TestBase64Helper {
|
||||
@Test
|
||||
public void testBase64(){
|
||||
String test = "wefree";
|
||||
String test = "11342526728";
|
||||
String encodeText = Base64Helper.BlockChain_Base64Encode(test);
|
||||
String test2 = new String(Base64Helper.BlockChain_Base64Decode(encodeText));
|
||||
System.out.println(encodeText);
|
||||
System.out.println(test2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSM4(){
|
||||
String testBase="Ws1Q0WtKcy7/jiB3rP5mwg==";
|
||||
edu.pku.commons.codec.binary.Base64 decoder = new Base64();
|
||||
byte[] decodeB=decoder.decode(testBase);
|
||||
System.out.println(Arrays.toString(decodeB));
|
||||
System.out.println(new String(decodeB));
|
||||
try {
|
||||
System.out.println(new String(BC_KeyManager.SM4Decrypt("3775199046620077",decodeB)));
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchPaddingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (BadPaddingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchProviderException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user