identity(without persist & without test)

This commit is contained in:
ghy committed 2021-03-09 15:22:58 +08:00
1 parent 9d370a5353
commit 755ddc2129
21 files changed
+588 -144

No files matched your search

@@ -0,0 +1,95 @@
package minsecurity.crypto.sm2;
import minsecurity.crypto.PrivateKeyInterface;
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) {
if(d.length == 32 || d.length == 33)
privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
else {
try {
throw new SM2Exception("SM2私钥中,参数d长度应为32/33");
} catch (SM2Exception e) {
e.printStackTrace();
}
}
}
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() {
return privateKey.getD().toByteArray();
}
@Override
public boolean setBytes(byte[] d) {
if(d.length != 32 && d.length != 33)
return false;
privateKey = new ECPrivateKeyParameters(new BigInteger(d), SM2Base.DOMAIN_PARAMS);
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;
}