org.bouncycastle.crypto.params.ParametersWithRandom Java Examples

The following examples show how to use org.bouncycastle.crypto.params.ParametersWithRandom. 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: ECDSASigner.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void init(boolean forSigning, CipherParameters param) {
    SecureRandom providedRandom = null;

    if (forSigning) {
        if (param instanceof ParametersWithRandom) {
            ParametersWithRandom rParam = (ParametersWithRandom) param;

            this.key = (ECPrivateKeyParameters) rParam.getParameters();
            providedRandom = rParam.getRandom();
        } else {
            this.key = (ECPrivateKeyParameters) param;
        }
    } else {
        this.key = (ECPublicKeyParameters) param;
    }

    this.random =
            initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom);
}
 
Example #2
Source File: P11RSAPSSSignatureSpi.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
    throws InvalidKeyException {
  if (!(privateKey instanceof P11PrivateKey)) {
    throw new InvalidKeyException("privateKey is not instanceof "
        + P11PrivateKey.class.getName());
  }

  String algo = privateKey.getAlgorithm();
  if (!"RSA".equals(algo)) {
    throw new InvalidKeyException("privateKey is not an RSA private key: " + algo);
  }

  this.signingKey = (P11PrivateKey) privateKey;

  pss = new org.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest,
      saltLength, trailer);

  P11RSAKeyParameter p11KeyParam = P11RSAKeyParameter.getInstance(
      signingKey.getP11CryptService(), signingKey.getIdentityId());
  if (random == null) {
    pss.init(true, p11KeyParam);
  } else {
    pss.init(true, new ParametersWithRandom(p11KeyParam, random));
  }
}
 
Example #3
Source File: SM2Util.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * @param mode             指定密文结构,旧标准的为C1C2C3,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
 * @param pubKeyParameters 公钥
 * @param srcData          原文
 * @return 根据mode不同,输出的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
 * @throws InvalidCipherTextException
 */
public static byte[] encrypt(Mode mode, ECPublicKeyParameters pubKeyParameters, byte[] srcData)
        throws InvalidCipherTextException {
    SM2Engine engine = new SM2Engine(mode);
    ParametersWithRandom pwr = new ParametersWithRandom(pubKeyParameters, new SecureRandom());
    engine.init(true, pwr);
    return engine.processBlock(srcData, 0, srcData.length);
}
 
Example #4
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 #5
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 #6
Source File: Crypto.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypts an given encrypted text using the given key
 *
 * @param encrytedText The encrypted text
 * @param key The encryption key
 * @return The clear text or null if decryption fails
 */
public String decrypt(String encrytedText, String key) {
    Objects.requireNonNull(encrytedText, Required.ENCRYPTED_TEXT.toString());
    Objects.requireNonNull(key, Required.KEY.toString());

    CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(StandardCharsets.UTF_8)));
    this.paddedBufferedBlockCipher.init(false, cipherParameters);
    
    return new String(cipherData(base64Decoder.decode(encrytedText)), StandardCharsets.UTF_8);
}
 
Example #7
Source File: Crypto.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts a given plain text using the given key
 *
 * Encryption is done by using AES and CBC Cipher and a key length of 256 bit
 *
 * @param plainText The plain text to encrypt
 * @param key The key to use for encryption
 * @return The encrypted text or null if encryption fails
 */
public String encrypt(final String plainText, final String key) {
    Objects.requireNonNull(plainText, Required.PLAIN_TEXT.toString());
    Objects.requireNonNull(key, Required.KEY.toString());

    CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(StandardCharsets.UTF_8)));
    this.paddedBufferedBlockCipher.init(true, cipherParameters);
    
    return new String(base64Encoder.encode(cipherData(plainText.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
}
 
Example #8
Source File: DSAPlainDigestSigner.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public void init(boolean forSigning, CipherParameters parameters) {
  this.forSigning = forSigning;

  AsymmetricKeyParameter param = (parameters instanceof ParametersWithRandom)
      ? (AsymmetricKeyParameter) ((ParametersWithRandom) parameters).getParameters()
      : (AsymmetricKeyParameter) parameters;

  Args.notNull(param, "param");
  if (param instanceof ECPublicKeyParameters) {
    keyBitLen = ((ECPublicKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof ECPrivateKeyParameters) {
    keyBitLen = ((ECPrivateKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof DSAPublicKeyParameters) {
    keyBitLen = ((DSAPublicKeyParameters) param).getParameters().getQ().bitLength();
  } else if (param instanceof DSAPrivateKeyParameters) {
    keyBitLen = ((DSAPrivateKeyParameters) param).getParameters().getQ().bitLength();
  } else {
    throw new IllegalArgumentException("unknown parameters: " + param.getClass().getName());
  }

  if (forSigning && !param.isPrivate()) {
    throw new IllegalArgumentException("Signing Requires Private Key.");
  }

  if (!forSigning && param.isPrivate()) {
    throw new IllegalArgumentException("Verification Requires Public Key.");
  }

  reset();
  dsaSigner.init(forSigning, parameters);
}
 
Example #9
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 4 votes vote down vote up
RSAPSS(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId, SecureRandom random)
    throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);
  Args.notNull(random, "random");

  ASN1ObjectIdentifier sigOid = signatureAlgId.getAlgorithm();
  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigOid)) {
    throw new XiSecurityException("unsupported signature algorithm "
        + signatureAlgId.getAlgorithm());
  }

  RSASSAPSSparams asn1Params = RSASSAPSSparams.getInstance(signatureAlgId.getParameters());
  ASN1ObjectIdentifier digestAlgOid = asn1Params.getHashAlgorithm().getAlgorithm();
  HashAlgo hashAlgo = HashAlgo.getInstance(digestAlgOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported hash algorithm " + digestAlgOid.getId());
  }

  P11SlotIdentifier slotId = identityId.getSlotId();
  P11Slot slot = cryptService.getSlot(slotId);

  long mech = hashAlgMechMap.get(hashAlgo).longValue();
  if (slot.supportsMechanism(mech)) {
    this.mechanism = mech;
    this.parameters = new P11Params.P11RSAPkcsPssParams(asn1Params);
    this.outputStream = new ByteArrayOutputStream();
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_PKCS_PSS)) {
    this.mechanism = PKCS11Constants.CKM_RSA_PKCS_PSS;
    this.parameters = new P11Params.P11RSAPkcsPssParams(asn1Params);
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_X_509)) {
    this.mechanism = PKCS11Constants.CKM_RSA_X_509;
    this.parameters = null;
    AsymmetricBlockCipher cipher = new P11PlainRSASigner();
    P11RSAKeyParameter keyParam;
    try {
      keyParam = P11RSAKeyParameter.getInstance(cryptService, identityId);
    } catch (InvalidKeyException ex) {
      throw new XiSecurityException(ex.getMessage(), ex);
    }
    PSSSigner pssSigner = SignerUtil.createPSSRSASigner(signatureAlgId, cipher);
    pssSigner.init(true, new ParametersWithRandom(keyParam, random));
    this.outputStream = new PSSSignerOutputStream(pssSigner);
  } else {
    throw new XiSecurityException("unsupported signature algorithm "
        + sigOid.getId() + " with " + hashAlgo);
  }
}
 
Example #10
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 #11
Source File: Sm2Util.java    From littleca with Apache License 2.0 3 votes vote down vote up
/**
 * ECC公钥加密
 *
 * @param pubKey  ECC公钥
 * @param srcData 源数据
 * @return SM2密文,实际包含三部分:ECC公钥、真正的密文、公钥和原文的SM3-HASH值
 * @throws InvalidCipherTextException
 */
public static byte[] encrypt(Sm2PublicKey pubKey, byte[] srcData)
    throws InvalidCipherTextException {
    SM2Engine engine = new SM2Engine();
    ParametersWithRandom pwr = new ParametersWithRandom(pubKey.getPublicKeyParameters(), new SecureRandom());
    engine.init(true, pwr);
    return engine.processBlock(srcData, 0, srcData.length);
}
 
Example #12
Source File: SM2Util.java    From jiguang-java-client-common with MIT License 3 votes vote down vote up
/**
 * ECC公钥加密
 *
 * @param pubKeyParameters ECC公钥
 * @param srcData          源数据
 * @return SM2密文,实际包含三部分:ECC公钥、真正的密文、公钥和原文的SM3-HASH值
 * @throws InvalidCipherTextException
 */
public static byte[] encrypt(ECPublicKeyParameters pubKeyParameters, byte[] srcData)
    throws InvalidCipherTextException {
    SM2Engine engine = new SM2Engine();
    ParametersWithRandom pwr = new ParametersWithRandom(pubKeyParameters, new SecureRandom());
    engine.init(true, pwr);
    return engine.processBlock(srcData, 0, srcData.length);
}