use of com.github.zhenwei.core.asn1.pkcs.Sm2Cipher in project LinLong-Java by zhenwei1108.
the class SM2Engine method decryptGm.
private byte[] decryptGm(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
Sm2Cipher sm2Cipher = Sm2Cipher.getInstance(in).setMode(mode);
ASN1Integer x = sm2Cipher.getX();
ASN1Integer y = sm2Cipher.getY();
ECPoint c1P = ecParams.getCurve().createPoint(x.getValue(), y.getValue());
byte[] c1 = c1P.getEncoded(false);
ECPoint s = c1P.multiply(ecParams.getH());
if (s.isInfinity()) {
throw new InvalidCipherTextException("[h]C1 at infinity");
}
c1P = c1P.multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize();
byte[] c2 = sm2Cipher.getCipher().getOctets();
kdf(digest, c1P, c2);
byte[] c3 = new byte[digest.getDigestSize()];
addFieldElement(digest, c1P.getAffineXCoord());
digest.update(c2, 0, c2.length);
addFieldElement(digest, c1P.getAffineYCoord());
digest.doFinal(c3, 0);
int check = 0;
byte[] hash = sm2Cipher.getHash().getOctets();
for (int i = 0; i != c3.length; i++) {
check |= c3[i] ^ hash[i];
}
Arrays.fill(c1, (byte) 0);
Arrays.fill(c3, (byte) 0);
if (check != 0) {
Arrays.fill(c2, (byte) 0);
throw new InvalidCipherTextException("invalid cipher text");
}
return c2;
}
use of com.github.zhenwei.core.asn1.pkcs.Sm2Cipher in project LinLong-Java by zhenwei1108.
the class SM2Engine method encryptGm.
// todo 实现SM2Cipher
private byte[] encryptGm(byte[] in, int inOff, int inLen) throws IOException {
byte[] cipher = new byte[inLen];
System.arraycopy(in, inOff, cipher, 0, cipher.length);
ECMultiplier multiplier = createBasePointMultiplier();
ECPoint kPB;
BigInteger x, y;
do {
BigInteger k = nextK();
ECPoint c1P = multiplier.multiply(ecParams.getG(), k).normalize();
// x , y
x = c1P.getAffineXCoord().toBigInteger();
y = c1P.getAffineYCoord().toBigInteger();
kPB = ((ECPublicKeyParameters) ecKey).getQ().multiply(k).normalize();
kdf(digest, kPB, cipher);
} while (notEncrypted(cipher, in, inOff));
byte[] hash = new byte[digest.getDigestSize()];
addFieldElement(digest, kPB.getAffineXCoord());
digest.update(in, inOff, inLen);
addFieldElement(digest, kPB.getAffineYCoord());
digest.doFinal(hash, 0);
return new Sm2Cipher(x, y, hash, cipher).setMode(mode).getEncoded(ASN1Encoding.DER);
}
Aggregations