org.bouncycastle.crypto.CryptoException Java Examples

The following examples show how to use org.bouncycastle.crypto.CryptoException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SM2Signer.java    From xipki with Apache License 2.0 6 votes vote down vote up
public byte[] generateSignatureForMessage(byte[] userId, byte[] message) throws CryptoException {
  // CHECKSTYLE:SKIP
  byte[] z;
  if (userId == null) {
    // use default userId
    z = GMUtil.getSM2Z(GMObjectIdentifiers.sm2p256v1,
        pubPoint.getAffineXCoord().toBigInteger(),
        pubPoint.getAffineYCoord().toBigInteger());
  } else {
    z = GMUtil.getSM2Z(userId, GMObjectIdentifiers.sm2p256v1,
      pubPoint.getAffineXCoord().toBigInteger(),
      pubPoint.getAffineYCoord().toBigInteger());
  }
  digest.reset();
  digest.update(z, 0, z.length);
  digest.update(message, 0, message.length);
  byte[] hash = new byte[digest.getDigestSize()];
  digest.doFinal(hash, 0);
  return generateSignatureForHash(hash);
}
 
Example #2
Source File: Crypto.java    From mangooio with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts or decrypts a given byte array of data
 *
 * @param data The data to encrypt or decrypt
 * @return A clear text or encrypted byte array
 */
private byte[] cipherData(final byte[] data) {
    byte[] result = null;
    try {
        final byte[] buffer = new byte[this.paddedBufferedBlockCipher.getOutputSize(data.length)];

        final int processedBytes = this.paddedBufferedBlockCipher.processBytes(data, 0, data.length, buffer, 0);
        final int finalBytes = this.paddedBufferedBlockCipher.doFinal(buffer, processedBytes);

        result = new byte[processedBytes + finalBytes];
        System.arraycopy(buffer, 0, result, 0, result.length);
    } catch (final CryptoException e) {
        LOG.error("Failed to encrypt/decrypt data array", e);
    }

    return result;
}
 
Example #3
Source File: SM2Sign.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * The new sm2 signature algorithm with better performance
 *
 * @param message
 * @param ecKeyPair
 * @return
 */
public static Sign.SignatureData sign2(byte[] message, ECKeyPair ecKeyPair) {

    SM2Signer sm2Signer = new SM2Signer();

    ECPrivateKeyParameters eCPrivateKeyParameters =
            new ECPrivateKeyParameters(ecKeyPair.getPrivateKey(), eCDomainParameters);

    sm2Signer.initWithCache(
            true,
            new ParametersWithID(new ParametersWithRandom(eCPrivateKeyParameters), identValue));

    org.bouncycastle.crypto.digests.SM3Digest sm3Digest =
            new org.bouncycastle.crypto.digests.SM3Digest();

    byte[] md = new byte[sm3Digest.getDigestSize()];
    sm3Digest.update(message, 0, message.length);
    sm3Digest.doFinal(md, 0);

    sm2Signer.update(md, 0, md.length);

    byte[] r = null;
    byte[] s = null;
    byte[] pub = null;

    try {
        BigInteger[] bigIntegers = sm2Signer.generateSignature2();

        pub = Numeric.toBytesPadded(ecKeyPair.getPublicKey(), 64);
        r = SM2Algorithm.getEncoded(bigIntegers[0]);
        s = SM2Algorithm.getEncoded(bigIntegers[1]);
    } catch (CryptoException e) {
        throw new RuntimeException(e);
    }

    return new Sign.SignatureData((byte) 0, r, s, pub);
}
 
Example #4
Source File: P11RSAPSSSignatureSpi.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] engineSign() throws SignatureException {
  try {
    return pss.generateSignature();
  } catch (CryptoException ex) {
    throw new SignatureException(ex.getMessage(), ex);
  }
}
 
Example #5
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pssDER() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(pubKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(pubKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example #6
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pss() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey);
	ASN1Primitive primitive = spkInfo.parsePublicKey();
	
	PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded());
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(publicKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(publicKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example #7
Source File: PcfAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String doSign(byte[] message, String instanceKeyPem) throws CryptoException {

		RSAPrivateKeySpec privateKey = PemObject.fromKey(instanceKeyPem).getRSAKeySpec();
		PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH);

		signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent()));
		signer.update(message, 0, message.length);

		byte[] signature = signer.generateSignature();
		return Base64Utils.encodeToUrlSafeString(signature);
	}
 
Example #8
Source File: PcfAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String sign(String message, String privateKeyPem) {

		try {
			return doSign(message.getBytes(StandardCharsets.US_ASCII), privateKeyPem);
		}
		catch (CryptoException e) {
			throw new VaultException("Cannot sign PCF login", e);
		}
	}
 
Example #9
Source File: SM2Signer.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public BigInteger[] generateSignature2() throws CryptoException {
    byte[] eHash = digestDoFinal();

    BigInteger n = ecParams.getN();
    BigInteger e = calculateE(eHash);
    BigInteger d = ((ECPrivateKeyParameters) ecKey).getD();

    BigInteger r, s;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            // A3
            k = kCalculator.nextK();

            // A4
            ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();

            // A5
            r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
        } while (r.equals(ZERO) || r.add(k).equals(n));

        // A6
        BigInteger dPlus1ModN = d.add(ONE).modInverse(n);

        s = k.subtract(r.multiply(d)).mod(n);
        s = dPlus1ModN.multiply(s).mod(n);
    } while (s.equals(ZERO));

    return new BigInteger[] {r, s};
}
 
Example #10
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 5 votes vote down vote up
@Override
public byte[] rsaSign(byte[] m, byte[] privateKey) {
	validateRsaSign(m, privateKey);

	try {
		PSSSigner pss = pssSha384(true, privateKey);
		pss.update(m, 0, m.length);
		return pss.generateSignature();
	} catch (CryptoException e) {
		// Not documented
		throw new CryptoProviderException("CryptoException", e);
	}
}
 
Example #11
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void base64() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CryptoException, CspException {
    Security.addProvider(new BouncyCastleProvider());
    String sk = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
            "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
            "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
            "C8r6EmyE";
    KeyFactory keyf = keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(sk));
    BCECPrivateKey priKey = (BCECPrivateKey) keyf.generatePrivate(priPKCS8);
    System.out.println("16进制私钥:" + priKey.getD().toString(16));

    String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
    byte[] idBytes = FileUtils.readFileBytes(cert_path);
    Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    byte[] pb = certificate.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    System.out.println(certificate.getSubject());
    System.out.println("tbs 公钥" + Hex.toHexString(pb));
    System.out.println("公钥:" + Hex.toHexString(publickey));
    System.out.println("公钥长度:" + publickey.length);


    SM2 sm2 = new SM2();
    byte[] v = sm2.sign(priKey.getD().toByteArray(), "123".getBytes());
    System.out.println(sm2.verify(publickey, v, "123".getBytes()));

}
 
Example #12
Source File: SM2.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * 对数据进行签名
 *
 * @param privateKey
 * @param msg
 * @return
 * @throws CryptoException
 */
public byte[] sign(byte[] privateKey, byte[] msg) throws CspException {
    if (null == privateKey) {
        throw new CspException("privateKey is null");
    }
    if (privateKey.length == 0) {
        throw new CspException("privateKey's length is 0");
    }
    if (null==msg) {
        throw new CspException("plainText is null");
    }
    if (msg.length == 0) {
        throw new CspException("plainText's length is 0");
    }
    SM2Signer signer = new SM2Signer();
    BigInteger d = byte2BigInteger(privateKey);
    ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(d, ecc_bc_spec);
    signer.init(true, privateKeyParameters);
    signer.update(msg, 0, msg.length);
    byte[] sig = new byte[0];
    try {
        sig = signer.generateSignature();
    } catch (CryptoException e) {
        log.error(e.getMessage());
        throw new CspException(e);
    }
    return sig;
}
 
Example #13
Source File: SM2PreprocessSignerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws CryptoException {
    AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
    ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
    ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

    SM2PreprocessSigner signer = new SM2PreprocessSigner();
    CipherParameters pwr = new ParametersWithRandom(priKey, new SecureRandom());
    signer.init(true, pwr);
    byte[] eHash1 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length);
    byte[] sign1 = signer.generateSignature(eHash1);

    signer = new SM2PreprocessSigner();
    signer.init(false, pubKey);
    byte[] eHash2 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length);
    if (!Arrays.equals(eHash1, eHash2)) {
        Assert.fail();
    }
    if (!signer.verifySignature(eHash1, sign1)) {
        Assert.fail();
    }
}
 
Example #14
Source File: SMAccount.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public byte[] sign(byte[] sourceData) {
    try {
        byte[] publicKey = ByteUtil.fromHex(this.publicKey);
        byte[] signature = SM2Util.sign(keyPair, sourceData);
        return ByteUtil.merge(SMFlag, publicKey, signature);
    } catch (CryptoException e) {
        logger.error("sign transaction error " + e.getMessage());
        return ByteUtil.EMPTY_BYTE_ARRAY;
    }
}
 
Example #15
Source File: SM2Signer.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] generateSignature() throws CryptoException {
    byte[] eHash = digestDoFinal();

    BigInteger n = ecParams.getN();
    BigInteger e = calculateE(eHash);
    BigInteger d = ((ECPrivateKeyParameters) ecKey).getD();

    BigInteger r, s;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            // A3
            k = kCalculator.nextK();

            // A4
            ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();

            // A5
            r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
        } while (r.equals(ZERO) || r.add(k).equals(n));

        // A6
        BigInteger dPlus1ModN = d.add(ONE).modInverse(n);

        s = k.subtract(r.multiply(d)).mod(n);
        s = dPlus1ModN.multiply(s).mod(n);
    } while (s.equals(ZERO));

    // A7
    try {
        return derEncode(r, s);
    } catch (IOException ex) {
        throw new CryptoException("unable to encode signature: " + ex.getMessage(), ex);
    }
}
 
Example #16
Source File: SM2PreprocessSigner.java    From gmhelper with Apache License 2.0 4 votes vote down vote up
public byte[] generateSignature(byte[] eHash) throws CryptoException {
    BigInteger n = ecParams.getN();
    BigInteger e = calculateE(eHash);
    BigInteger d = ((ECPrivateKeyParameters) ecKey).getD();

    BigInteger r, s;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            // A3
            k = kCalculator.nextK();

            // A4
            ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();

            // A5
            r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
        }
        while (r.equals(ZERO) || r.add(k).equals(n));

        // A6
        BigInteger dPlus1ModN = d.add(ONE).modInverse(n);

        s = k.subtract(r.multiply(d)).mod(n);
        s = dPlus1ModN.multiply(s).mod(n);
    }
    while (s.equals(ZERO));

    // A7
    try {
        return derEncode(r, s);
    } catch (IOException ex) {
        throw new CryptoException("unable to encode signature: " + ex.getMessage(), ex);
    }
}
 
Example #17
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 4 votes vote down vote up
byte[] generateSignature() throws DataLengthException, CryptoException {
  byte[] signature = pssSigner.generateSignature();
  pssSigner.reset();
  return signature;
}
 
Example #18
Source File: SM2Signer.java    From xipki with Apache License 2.0 4 votes vote down vote up
public byte[] generateSignatureForHash(byte[] eHash) throws CryptoException {
  BigInteger n = ecParams.getN();
  BigInteger e = new BigInteger(1, eHash);
  BigInteger d = ((ECPrivateKeyParameters)ecKey).getD();

  BigInteger r;
  BigInteger s;

  ECMultiplier basePointMultiplier = new FixedPointCombMultiplier();

  // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
  do { // generate s
    BigInteger k;
    do { // generate r
      // A3
      k = kCalculator.nextK();

      // A4
      ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();

      // A5
      r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
    } while (r.equals(ECConstants.ZERO) || r.add(k).equals(n));

    // A6
    // CHECKSTYLE:SKIP
    BigInteger dPlus1ModN = d.add(ECConstants.ONE).modInverse(n);

    s = k.subtract(r.multiply(d)).mod(n);
    s = dPlus1ModN.multiply(s).mod(n);
  } while (s.equals(ECConstants.ZERO));

  // A7
  try {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(r));
    v.add(new ASN1Integer(s));
    return new DERSequence(v).getEncoded(ASN1Encoding.DER);
  } catch (IOException ex) {
    throw new CryptoException("unable to encode signature: " + ex.getMessage(), ex);
  }
}
 
Example #19
Source File: SM2Util.java    From javasdk with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * get signature by sm2 key pair, use default userID.
 *
 * @param keyPair ECC key pair
 * @param srcData source data
 * @return signature bytes
 * @throws CryptoException -
 */
public static byte[] sign(AsymmetricCipherKeyPair keyPair, byte[] srcData) throws CryptoException {
    SM2Signer signer = new SM2Signer();
    CipherParameters param = new ParametersWithRandom(keyPair.getPrivate(), new SecureRandom());
    signer.init(true, param);
    signer.update(srcData, 0, srcData.length);
    return signer.generateSignature();
}
 
Example #20
Source File: SM2Util.java    From javasdk with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * get signature by sm2 key pair, use default userID.
 *
 * @param keyPair private key bytes
 * @param srcData source data
 * @return signature bytes
 * @throws CryptoException -
 */
public static byte[] sign(byte[] keyPair, byte[] srcData) throws CryptoException {
    ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, keyPair), SM2Util.DOMAIN_PARAMS);
    AsymmetricCipherKeyPair asymmetricCipherKeyPair = new AsymmetricCipherKeyPair(null, privateKeyParameters);
    return sign(asymmetricCipherKeyPair, srcData);
}
 
Example #21
Source File: SM2Util.java    From gmhelper with Apache License 2.0 2 votes vote down vote up
/**
 * 私钥签名
 *
 * @param priKey  私钥
 * @param withId  可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
 * @param srcData 原文
 * @return DER编码后的签名值
 * @throws CryptoException
 */
public static byte[] sign(BCECPrivateKey priKey, byte[] withId, byte[] srcData) throws CryptoException {
    ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
    return sign(priKeyParameters, withId, srcData);
}
 
Example #22
Source File: SM2Util.java    From gmhelper with Apache License 2.0 2 votes vote down vote up
/**
 * 签名
 * 不指定withId,则默认withId为字节数组:"1234567812345678".getBytes()
 *
 * @param priKeyParameters 私钥
 * @param srcData          原文
 * @return DER编码后的签名值
 * @throws CryptoException
 */
public static byte[] sign(ECPrivateKeyParameters priKeyParameters, byte[] srcData) throws CryptoException {
    return sign(priKeyParameters, null, srcData);
}
 
Example #23
Source File: SM2Util.java    From gmhelper with Apache License 2.0 2 votes vote down vote up
/**
 * 签名
 *
 * @param priKey  私钥
 * @param srcData 原文
 * @return DER编码后的签名值
 * @throws CryptoException
 */
public static byte[] sign(BCECPrivateKey priKey, byte[] srcData) throws CryptoException {
    ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
    return sign(priKeyParameters, null, srcData);
}