org.bouncycastle.jce.provider.BouncyCastleProvider Java Examples

The following examples show how to use org.bouncycastle.jce.provider.BouncyCastleProvider. 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: NetconfControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
@Deactivate
public void deactivate() {
    netconfDeviceMap.values().forEach(device -> {
        if (device.isMasterSession()) {
            try {
                device.getSession().removeDeviceOutputListener(downListener);
            } catch (NetconfException e) {
                log.error("removeDeviceOutputListener Failed {}", e.getMessage());
            }
        }
        device.disconnect();
    });
    clusterCommunicator.removeSubscriber(SEND_REQUEST_SUBJECT_STRING);
    clusterCommunicator.removeSubscriber(SEND_REQUEST_SUBJECT_SET_STRING);
    clusterCommunicator.removeSubscriber(SEND_REPLY_SUBJECT_STRING);
    clusterCommunicator.removeSubscriber(SEND_REPLY_SUBJECT_SET_STRING);
    cfgService.unregisterProperties(getClass(), false);
    netconfDeviceListeners.clear();
    netconfDeviceMap.clear();
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    log.info("Stopped");
}
 
Example #2
Source File: Sm3DigestTest.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
@Test
void testSign() throws GeneralSecurityException, IOException {
    Path ks = Paths.get("src/test/resources", "USER.p12");
    Path in = Paths.get("target/DigitalSign/Doc_0/Signs/Sign_0/Signature.xml");
    Path out = Paths.get("target/DigitalSign/Doc_0/Signs/Sign_0/", SignDir.SignedValueFileName);

    Certificate cert = PKCS12Tools.ReadUserCert(ks, "private", "777777");
    PrivateKey prv = PKCS12Tools.ReadPrvKey(ks, "private", "777777");

    Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
    sg.initSign(prv);
    sg.update(Files.readAllBytes(in));
    byte[] sign = sg.sign();
    Files.write(out, sign);

    sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
    sg.initVerify(cert);
    sg.update(Files.readAllBytes(in));
    System.out.println(sg.verify(sign));
}
 
Example #3
Source File: RemoveSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://itext.2136553.n4.nabble.com/trying-to-remove-a-signature-from-pdf-file-tt4660983.html">
 * trying to remove a signature from pdf file
 * </a>
 * <br/>
 * <a href="http://itext.2136553.n4.nabble.com/attachment/4660983/0/PDFSignedFirmaCerta.pdf">
 * PDFSignedFirmaCerta.pdf
 * </a>
 * <p>
 * Indeed, this code fails with a {@link NullPointerException}. The cause is that a dubious construct
 * created by the signature software then is processed by iText code not sufficiently defensively programmed:
 * The signature claims to have an annotation on a page but that page does claim not to have any anotations
 * at all.
 * </p>
 */
@Test
public void testRemoveSignatureFromPDFSignedFirmaCerta() throws IOException, GeneralSecurityException, DocumentException
{
    try (   InputStream inputStream = getClass().getResourceAsStream("PDFSignedFirmaCerta.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "PDFSignedFirmaCerta-withoutSig.pdf")))
    {
        Provider provider = new BouncyCastleProvider();
        Security.addProvider(provider);

        PdfReader reader = new PdfReader(inputStream, null);
        AcroFields af = reader.getAcroFields();
        ArrayList<String> names = af.getSignatureNames();
        for (String name : names) {
            System.out.println("Signature name: " + name);
            System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
            PdfPKCS7 pk = af.verifySignature(name, provider.getName());
            System.out.println("SignatureDate: " + pk.getSignDate());
            System.out.println("Certificate: " + pk.getSigningCertificate());
            System.out.println("Document modified: " + !pk.verify());
            af.removeField(name);
        }
        PdfStamper stamper = new PdfStamper(reader, outputStream, '\0');
        stamper.close();
    }
}
 
Example #4
Source File: ToolHmacRipeMD.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * HmacRipeMD128消息摘要
 *
 * @param data
 *         待做消息摘要处理的数据
 * @param key
 *         密钥
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeHmacRipeMD128(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {

    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacRipeMD128");

    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());

    // 初始化Mac
    mac.init(secretKey);

    // 执行消息摘要
    return mac.doFinal(data);
}
 
Example #5
Source File: ToolECDSA.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 校验
 *
 * @param data
 *         待校验数据
 * @param publicKey
 *         公钥
 * @param sign
 *         数字签名
 *
 * @return boolean 校验成功返回true 失败返回false
 *
 * @throws Exception
 */
public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 转换公钥材料
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 生成公钥
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

    // 初始化Signature
    signature.initVerify(pubKey);

    // 更新
    signature.update(data);

    // 验证
    return signature.verify(sign);
}
 
Example #6
Source File: CryptoServiceImpl.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {

	if (Security.getProvider("BC") == null) {
	    Security.addProvider(new BouncyCastleProvider());
	}

	File merchantPrivateKeyFile = new File(merchantPrivateKeyFilename);
	if (!merchantPrivateKeyFile.isFile() || !merchantPrivateKeyFile.canRead()) {
		throw new IllegalArgumentException("Unable to load merchant private key from " + merchantPrivateKeyFile.getAbsolutePath());
	}

	merchantPrivateKey = initializePrivateKey(merchantPrivateKeyFile);
	
	File mipsPublicKeyFile = new File(mipsPublicKeyFilename);
	if (!mipsPublicKeyFile.isFile() || !mipsPublicKeyFile.canRead()) {
		throw new IllegalArgumentException("Unable to load mips public key from " + mipsPublicKeyFile.getAbsolutePath());
	}

	String mipsPublicKeyData = FileUtils.readFileToString(mipsPublicKeyFile);
	mipsPublicKey = initializePublicKey(mipsPublicKeyData);

}
 
Example #7
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 读取x509 证书
 *
 * @param pemPath
 * @return
 */
public static X509Certificate readX509Cert(String savePath) throws CertException {
    try {
        if (null == savePath) {
            throw new CertException("save path can't be null");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) readObject;
            return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate(holder);
        }
        pemParser.close();
        throw new CertException(savePath + "file read format failed");
    } catch (Exception e) {
        throw new CertException("read x509 cert failed", e);
    }
}
 
Example #8
Source File: EntPayServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private String encryptRSA(File publicKeyFile, String srcString) throws WxPayException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
    try (PEMParser reader = new PEMParser(new FileReader(publicKeyFile))) {
      final PublicKey publicKey = new JcaPEMKeyConverter().setProvider("BC")
        .getPublicKey((SubjectPublicKeyInfo) reader.readObject());

      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      byte[] encrypt = cipher.doFinal(srcString.getBytes());
      return Base64.encodeBase64String(encrypt);
    }
  } catch (Exception e) {
    throw new WxPayException("加密出错", e);
  }
}
 
Example #9
Source File: SignatureOperationTest.java    From crypto with Apache License 2.0 6 votes vote down vote up
@Test
public void testSHA1_WIEH_ECDSAByBouncyCastle(){
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.addProvider(bouncyCastleProvider);
    Configuration configuration = new Configuration();
    configuration.setKeyAlgorithm(Algorithms.ECDSA).setKeySize(256);
    NonSymmetricCryptography nonSymmetricCryptography = new NonSymmetricCryptography(configuration);
    Map<String,Key> keyMap = nonSymmetricCryptography.initKey();
    String privateKey = nonSymmetricCryptography.encodeKey(nonSymmetricCryptography.getPrivateKey(keyMap));
    String publicKey = nonSymmetricCryptography.encodeKey(nonSymmetricCryptography.getPublicKey(keyMap));
    System.out.println("ECDSA私钥:" + privateKey);
    System.out.println("ECDSA公钥:" + publicKey);
    configuration.setSignatureAlgorithm(Algorithms.SHA1_WIEH_ECDSA);
    SignatureOperation signatureOperation = new SignatureOperation(configuration);
    String sign = signatureOperation.sign(data, nonSymmetricCryptography.toPrivateKey(nonSymmetricCryptography.decodeKey(privateKey)));
    System.out.println("签名值:" + sign);
    System.out.println("验证签名:" + signatureOperation.verify(data, nonSymmetricCryptography.toPublicKey(nonSymmetricCryptography.decodeKey(publicKey)), sign));
}
 
Example #10
Source File: EciesEncryptionTest.java    From protect with MIT License 6 votes vote down vote up
@Test
public void testEncryptDecrypt() throws Exception {

	final String name = "secp256r1";

	// NOTE just "EC" also seems to work here
	final KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
	kpg.initialize(new ECGenParameterSpec(name));

	// Key pair to store public and private key
	final KeyPair keyPair = kpg.generateKeyPair();

	// Message to encrypt
	byte[] message = "hello".getBytes(StandardCharsets.UTF_8);

	// Encrypt
	final BigInteger r = EciesEncryption.generateR();
	byte[] encrypted = EciesEncryption.encrypt(message, r, keyPair.getPublic());

	// Decrypt
	byte[] decrypted = EciesEncryption.decrypt(encrypted, keyPair.getPrivate());
	System.out.println("Decrypted message: " + new String(decrypted));

	Assert.assertArrayEquals(message, decrypted);

}
 
Example #11
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 从pem私钥文件中获取sk
 * @return
 */
public static byte[] getPrivateKey(String filePath)throws Exception{
    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    String str = new String(content);
    String privateKeyPEM = str.replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("-----END PRIVATE KEY-----", "").replace("\n", "");
    Security.addProvider(new BouncyCastleProvider());
    KeyFactory keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyPEM) );
    BCECPrivateKey priKey = (BCECPrivateKey)keyf.generatePrivate(priPKCS8);
    return priKey.getD().toByteArray();
}
 
Example #12
Source File: TestSslUtils.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example #13
Source File: ComplexSignatureFields.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception
{
    RESULT_FOLDER.mkdirs();

    BouncyCastleProvider bcp = new BouncyCastleProvider();
    //Security.addProvider(bcp);
    Security.insertProviderAt(bcp, 1);

    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(KEYSTORE), PASSWORD);
    String alias = (String) ks.aliases().nextElement();
    pk = (PrivateKey) ks.getKey(alias, PASSWORD);
    chain = ks.getCertificateChain(alias);
}
 
Example #14
Source File: GPGFileDecryptor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Private util function that finds the private key from keyring collection based on keyId and passPhrase
 * @param pgpSec keyring collection
 * @param keyID keyID for this encryption file
 * @param passPhrase passPhrase for this encryption file
 * @throws PGPException
 */
private PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, String passPhrase)
    throws PGPException {

  PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
  if (pgpSecKey == null) {
    return null;
  }
  return pgpSecKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder()
          .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));
}
 
Example #15
Source File: KeyPairUtil.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] sign(byte[] toSign, PrivateKey privateKey, String signatureAlgorithm)
		throws GeneralSecurityException {
	Signature signature = Signature.getInstance(signatureAlgorithm, new BouncyCastleProvider());
	signature.initSign(privateKey);
	signature.update(toSign);
	return signature.sign();
}
 
Example #16
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
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();
}
 
Example #17
Source File: PackedAttestationStatementValidatorTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
private static AttestationCertificatePath generateCertPath(KeyPair pair, String signAlg) {

        try {
            Provider bcProvider = new BouncyCastleProvider();
            //Security.addProvider(bcProvider);

            long now = System.currentTimeMillis();
            Date from = new Date(now);
            Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(1));

            X500Name dnName = new X500Name("C=ORG, O=Dummy Org, OU=Authenticator Attestation, CN=Dummy");
            BigInteger certSerialNumber = BigInteger.ZERO;

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(from);
            calendar.add(Calendar.YEAR, 1);

            ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).build(pair.getPrivate());
            JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, from, to, dnName, pair.getPublic());

            BasicConstraints basicConstraints = new BasicConstraints(false);
            certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

            X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
            return new AttestationCertificatePath(Collections.singletonList(certificate));
        } catch (OperatorCreationException | CertificateException | CertIOException e) {
            throw new UnexpectedCheckedException(e);
        }
    }
 
Example #18
Source File: ToolMD4.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * MD4加密
 *
 * @param data
 *         待加密数据
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeMD4(byte[] data) throws NoSuchAlgorithmException {

    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化MessageDigest
    MessageDigest md = MessageDigest.getInstance("MD4");

    // 执行消息摘要
    return md.digest(data);
}
 
Example #19
Source File: ECCDecrypt.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * create BCECPrivateKey from privateKey
 *
 * @param privateKey
 * @return
 */
private BCECPrivateKey createBCECPrivateKey(BigInteger privateKey) {
    // Handle secret key
    ECPrivateKeySpec secretKeySpec =
            new ECPrivateKeySpec(privateKey, ECCParams.ecNamedCurveSpec);
    BCECPrivateKey bcecPrivateKey =
            new BCECPrivateKey("ECDSA", secretKeySpec, BouncyCastleProvider.CONFIGURATION);
    return bcecPrivateKey;
}
 
Example #20
Source File: ToolMD.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * Tiger加密
 *
 * @param data
 *         待加密数据
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeTiger(byte[] data) throws NoSuchAlgorithmException {

    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化MessageDigest
    MessageDigest md = MessageDigest.getInstance("Tiger");

    // 执行消息摘要
    return md.digest(data);
}
 
Example #21
Source File: PKCGenerate.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 生成测试SM2密钥对
 *
 * @return 密钥对
 */
public static KeyPair GenerateKeyPair() throws GeneralSecurityException {
    // 获取SM2椭圆曲线的参数
    final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
    // 获取一个椭圆曲线类型的密钥对生成器
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
    // 使用SM2参数初始化生成器
    kpg.initialize(sm2Spec);

    // 使用SM2的算法区域初始化密钥生成器
    kpg.initialize(sm2Spec, new SecureRandom());
    // 获取密钥对
    return kpg.generateKeyPair();
}
 
Example #22
Source File: ReferenceTest.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
public static Reference referenceCase() {
    Page res  = PageTest.pageCase();
    ST_Loc fileRef = new ST_Loc("/Doc_0/Pages/Page_0/Content.xml");
    try {
        MessageDigest sm3 = MessageDigest.getInstance("SM3", new BouncyCastleProvider());
        byte[] plainText = TestTool.xmlByte(res);
        sm3.update(plainText);
        byte[] checkValue = sm3.digest();
        return new Reference(fileRef, checkValue);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: Main.java    From bouncycastle-rsa-pem-write with MIT License 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchProviderException {
	Security.addProvider(new BouncyCastleProvider());
	LOGGER.info("BouncyCastle provider added.");
	
	KeyPair keyPair = generateRSAKeyPair();
	RSAPrivateKey priv = (RSAPrivateKey) keyPair.getPrivate();
	RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic();
	
	writePemFile(priv, "RSA PRIVATE KEY", "id_rsa");
	writePemFile(pub, "RSA PUBLIC KEY", "id_rsa.pub");
	
}
 
Example #24
Source File: SigningTest.java    From protect with MIT License 5 votes vote down vote up
private KeyPair generateKeyPair() {

		// Initalize key pair generator
		final KeyPairGenerator keyGen;
		try {
			keyGen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
			keyGen.initialize(new ECGenParameterSpec(CommonConfiguration.CURVE.getName()));
		} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) {
			throw new RuntimeException(e);
		}

		// Create key pair
		return keyGen.generateKeyPair();
	}
 
Example #25
Source File: H2HDummyEncryption.java    From Hive2Hive with MIT License 5 votes vote down vote up
public H2HDummyEncryption() {
	serializer = new FSTSerializer();

	// install the provider anyway because probably key pairs need to be generated
	if (Security.getProvider(SECURITY_PROVIDER) == null) {
		Security.addProvider(new BouncyCastleProvider());
	}
}
 
Example #26
Source File: CliperInstance.java    From pay with Apache License 2.0 5 votes vote down vote up
protected Cipher initialValue() {
    try {
        return Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
    } catch (Exception var2) {
        return null;
    }
}
 
Example #27
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testECDSASignature() throws Exception {

    try {
        Cipher.getInstance(AlgorithmUtils.ES_SHA_512_JAVA);
    } catch (Throwable t) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD);
        compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.ES512);
        compactProducer.getJwsHeaders().setKeyId(ECDSA_KID_VALUE);
        JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
        assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),
                     ECDSA_SIGNATURE_PROTECTED_HEADER_JSON);
        assertEquals(compactProducer.getUnsignedEncodedJws(),
                ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
        JsonWebKeys jwks = readKeySet("cookbookPrivateSet.txt");
        List<JsonWebKey> keys = jwks.getKeys();
        JsonWebKey ecKey = keys.get(0);
        compactProducer.signWith(new EcDsaJwsSignatureProvider(JwkUtils.toECPrivateKey(ecKey),
                                                               SignatureAlgorithm.ES512));
        assertEquals(compactProducer.getUnsignedEncodedJws(),
                     ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
        assertEquals(132, Base64UrlUtility.decode(compactProducer.getEncodedSignature()).length);

        JwsCompactConsumer compactConsumer = new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
        JsonWebKeys publicJwks = readKeySet("cookbookPublicSet.txt");
        List<JsonWebKey> publicKeys = publicJwks.getKeys();
        JsonWebKey ecPublicKey = publicKeys.get(0);
        assertTrue(compactConsumer.verifySignatureWith(ecPublicKey, SignatureAlgorithm.ES512));
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example #28
Source File: SESV4Container.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 对待签名数据进行电子签章
 * <p>
 * 注意:该方法不符合《GM/T 0031-2014 安全电子签章密码技术规范》 流程规范,生成的电子签章
 * 不具有效力,请使用符合国家标准具有型号证书的设备产生电子签章数据。
 * <p>
 * 该方法只用于测试调试。
 *
 * @param inData       待签名数据流
 * @param propertyInfo 签章属性信息
 * @return 签名或签章结果值
 * @throws IOException              流操作异常
 * @throws GeneralSecurityException 签名计算异常
 */
@Override
public byte[] sign(InputStream inData, String propertyInfo) throws IOException, GeneralSecurityException {

    MessageDigest md = getDigestFnc();
    // 签名原文杂凑值,也就是Signature.xml 文件的杂凑值
    byte[] dataHash = md.digest(IOUtils.toByteArray(inData));

    TBS_Sign toSign = new TBS_Sign()
            .setVersion(SES_Header.V4)
            .setEseal(seal)
            .setTimeInfo(new ASN1GeneralizedTime(new Date()))
            .setDataHash(dataHash)
            .setPropertyInfo(propertyInfo);

    Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
    sg.initSign(privateKey);
    sg.update(toSign.getEncoded("DER"));
    final byte[] sigVal = sg.sign();
    SES_Signature signature = new SES_Signature()
            .setToSign(toSign)
            .setCert(certificate)
            .setSignatureAlgID(GMObjectIdentifiers.sm2sign_with_sm3)
            .setSignature(sigVal);

    return signature.getEncoded("DER");
}
 
Example #29
Source File: TrustAddressGenerator.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static String preimageToAddress(byte[] preimage) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    Security.addProvider(new BouncyCastleProvider());

    // get the hash of the preimage text
    Keccak.Digest256 digest = new Keccak.Digest256();
    digest.update(preimage);
    byte[] hash = digest.digest();

    // use the hash to derive a new address
    BigInteger keyDerivationFactor = new BigInteger(Numeric.toHexStringNoPrefix(hash), 16);
    ECPoint donatePKPoint = extractPublicKey(decodeKey(masterPubKey));
    ECPoint digestPKPoint = donatePKPoint.multiply(keyDerivationFactor);
    return getAddress(digestPKPoint);
}
 
Example #30
Source File: ToolSHA2.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * SHA-224加密
 *
 * @param data
 *         待加密数据
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeSHA224(byte[] data) throws NoSuchAlgorithmException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化MessageDigest
    MessageDigest md = MessageDigest.getInstance("SHA-224");

    // 执行消息摘要
    return md.digest(data);
}