org.hyperledger.fabric.sdk.exception.CryptoException Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.exception.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: HLSDKJCryptoSuiteFactory.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public CryptoSuite getCryptoSuite(Properties properties) throws CryptoException, InvalidArgumentException {

    CryptoSuite ret = cache.get(properties);
    if (ret == null) {
        try {
            CryptoPrimitives cp = new CryptoPrimitives();
            cp.setProperties(properties);
            cp.init();
            ret = cp;
        } catch (Exception e) {
            throw new CryptoException(e.getMessage(), e);
        }

        cache.put(properties, ret);

    }

    return ret;

}
 
Example #2
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * addCACertificatesToTrustStore adds a CA certs in a stream to the trust store  used for signature validation
 *
 * @param bis an X.509 certificate stream in PEM format in bytes
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
public void addCACertificatesToTrustStore(BufferedInputStream bis) throws CryptoException, InvalidArgumentException {

    if (bis == null) {
        throw new InvalidArgumentException("The certificate stream bis cannot be null");
    }

    try {
        final Collection<? extends Certificate> certificates = cf.generateCertificates(bis);
        for (Certificate certificate : certificates) {
            addCACertificateToTrustStore(certificate);
        }

    } catch (CertificateException e) {
        throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e);
    }
}
 
Example #3
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * addCACertificateToTrustStore adds a CA cert to the set of certificates used for signature validation
 *
 * @param caCertPem an X.509 certificate in PEM format
 * @param alias     an alias associated with the certificate. Used as shorthand for the certificate during crypto operations
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
public void addCACertificateToTrustStore(File caCertPem, String alias) throws CryptoException, InvalidArgumentException {

    if (caCertPem == null) {
        throw new InvalidArgumentException("The certificate cannot be null");
    }

    if (alias == null || alias.isEmpty()) {
        throw new InvalidArgumentException("You must assign an alias to a certificate when adding to the trust store");
    }

    try {
        try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(FileUtils.readFileToByteArray(caCertPem)))) {

            Certificate caCert = cf.generateCertificate(bis);
            addCACertificateToTrustStore(caCert, alias);
        }
    } catch (CertificateException | IOException e) {
        throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e);
    }

}
 
Example #4
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public Certificate bytesToCertificate(byte[] certBytes) throws CryptoException {
        if (certBytes == null || certBytes.length == 0) {
            throw new CryptoException("bytesToCertificate: input null or zero length");
        }

        return getX509Certificate(certBytes);
//        X509Certificate certificate;
//        try {
//            BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(certBytes));
//            CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
//            certificate = (X509Certificate) certFactory.generateCertificate(pem);
//        } catch (CertificateException e) {
//            String emsg = "Unable to converts byte array to certificate. error : " + e.getMessage();
//            logger.error(emsg);
//            logger.debug("input bytes array :" + new String(certBytes));
//            throw new CryptoException(emsg, e);
//        }
//
//        return certificate;
    }
 
Example #5
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// TODO need to regen key now that we're using CryptoSuite
public void testSign() {

    byte[] plainText = "123456".getBytes(UTF_8);
    byte[] signature;
    try {
        PrivateKey key = (PrivateKey) crypto.getTrustStore().getKey("key", "123456".toCharArray());
        signature = crypto.sign(key, plainText);

        BufferedInputStream bis = new BufferedInputStream(
                this.getClass().getResourceAsStream("/keypair-signed.crt"));
        byte[] cert = IOUtils.toByteArray(bis);
        bis.close();

        assertTrue(crypto.verify(cert, SIGNING_ALGORITHM, signature, plainText));
    } catch (KeyStoreException | CryptoException | IOException | UnrecoverableKeyException
            | NoSuchAlgorithmException e) {
        fail("Could not verify signature. Error: " + e.getMessage());
    }
}
 
Example #6
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCACertificateToTrustStoreBadStore() throws Exception {

    thrown.expect(CryptoException.class);
    thrown.expectMessage("Unable to add");

    // Create an uninitialized key store
    KeyStore tmpKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // Ensure that crypto is using that store
    KeyStore saveKeyStore = (KeyStore) setField(crypto, "trustStore", tmpKeyStore);

    try {
        crypto.addCACertificateToTrustStore(testCACert, "alias");
    } finally {
        // Ensure we set it back so that subsequent tests will not be affected
        setField(crypto, "trustStore", saveKeyStore);
    }
}
 
Example #7
Source File: ProtoUtils.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public static Common.Envelope createSeekInfoEnvelope(TransactionContext transactionContext, Ab.SeekInfo seekInfo, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException {
    Common.ChannelHeader seekInfoHeader = createChannelHeader(Common.HeaderType.DELIVER_SEEK_INFO,
            transactionContext.getTxID(), transactionContext.getChannelID(), transactionContext.getEpoch(),
            transactionContext.getFabricTimestamp(), null, tlsCertHash);

    Common.SignatureHeader signatureHeader = Common.SignatureHeader.newBuilder()
            .setCreator(transactionContext.getIdentity().toByteString())
            .setNonce(transactionContext.getNonce())
            .build();

    Common.Header seekHeader = Common.Header.newBuilder()
            .setSignatureHeader(signatureHeader.toByteString())
            .setChannelHeader(seekInfoHeader.toByteString())
            .build();

    Common.Payload seekPayload = Common.Payload.newBuilder()
            .setHeader(seekHeader)
            .setData(seekInfo.toByteString())
            .build();

    return Common.Envelope.newBuilder().setSignature(transactionContext.signByteString(seekPayload.toByteArray()))
            .setPayload(seekPayload.toByteString())
            .build();
}
 
Example #8
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test (expected = CryptoException.class)
public void testAddCACertificateToTrustStoreInvalidCertFile() throws CryptoException {
    try {
        crypto.addCACertificateToTrustStore(new File("/bad-ca1.crt"), "abc");
    } catch (InvalidArgumentException e) {
        fail("testAddCACertificateToTrustStoreInvalidCertFile should not throw InvalidArgumentException. Error: " + e.getMessage());
    }
}
 
Example #9
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test (expected = CryptoException.class)
public void testAddCACertificateToTrustStoreNoFile() throws CryptoException {
    try {
        crypto.addCACertificateToTrustStore(new File("does/not/exist"), "abc");
    } catch (InvalidArgumentException e) {
        fail("testAddCACertificateToTrustStoreNoFile should not throw InvalidArgumentException. Error: " + e.getMessage());
    }
}
 
Example #10
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test (expected = InvalidArgumentException.class)
public void testAddCACertificateToTrustStoreEmptyAlias() throws InvalidArgumentException {
    try {
        crypto.addCACertificateToTrustStore(new File("something"), "");
    } catch (CryptoException e) {
        fail("testAddCACertificateToTrustStoreEmptyAlias should not throw CryptoException. Error: " + e.getMessage());
    }
}
 
Example #11
Source File: RevocationAuthority.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Credential Revocation Information object
 *
 * @param key              Private key
 * @param unrevokedHandles Array of unrevoked revocation handles
 * @param epoch            The counter (representing a time window) in which this CRI is valid
 * @param alg              Revocation algorithm
 * @return CredentialRevocationInformation object
 */
public static Idemix.CredentialRevocationInformation createCRI(PrivateKey key, BIG[] unrevokedHandles, int epoch, RevocationAlgorithm alg) throws CryptoException {
    Idemix.CredentialRevocationInformation.Builder builder = Idemix.CredentialRevocationInformation.newBuilder();
    builder.setRevocationAlg(alg.ordinal());
    builder.setEpoch(epoch);

    // Create epoch key
    WeakBB.KeyPair keyPair = WeakBB.weakBBKeyGen();
    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // Dummy PK in the proto
        builder.setEpochPk(IdemixUtils.transformToProto(IdemixUtils.genG2));
    } else {
        // Real PK only if we are going to use it
        builder.setEpochPk(IdemixUtils.transformToProto(keyPair.getPk()));
    }

    // Sign epoch + epoch key with the long term key
    byte[] signed;
    try {
        Idemix.CredentialRevocationInformation cri = builder.build();
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initSign(key);
        ecdsa.update(cri.toByteArray());
        signed = ecdsa.sign();

        builder.setEpochPkSig(ByteString.copyFrom(signed));
    } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new CryptoException("Error processing the signature");
    }

    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // build and return the credential information object
        return builder.build();
    } else {
        // If alg not supported, return null
        throw new IllegalArgumentException("Algorithm " + alg.name() + " not supported");
    }
}
 
Example #12
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyNullInput() {
    try {
        assertFalse(crypto.verify(null, SIGNING_ALGORITHM, null, null));
    } catch (CryptoException e) {
        fail("testVerifyNullInput should not have thrown exception. Error: " + e.getMessage());
    }
}
 
Example #13
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test (expected = InvalidArgumentException.class)
public void testAddCACertificateToTrustStoreNoCert() throws InvalidArgumentException {
    try {
        crypto.addCACertificateToTrustStore((Certificate) null, "abc");
    } catch (CryptoException e) {
        fail("testAddCACertificateToTrustStoreNoCert should not have thrown CryptoException. Error " + e.getMessage());
    }
}
 
Example #14
Source File: HFClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public void setCryptoSuite(CryptoSuite cryptoSuite) throws CryptoException, InvalidArgumentException {
    if (null == cryptoSuite) {
        throw new InvalidArgumentException("CryptoSuite parameter is null.");
    }
    if (this.cryptoSuite != null && cryptoSuite != this.cryptoSuite) {
        throw new InvalidArgumentException("CryptoSuite may only be set once.");

    }

    this.cryptoSuite = cryptoSuite;

}
 
Example #15
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Return PrivateKey  from pem bytes.
 *
 * @param pemKey pem-encoded private key
 * @return
 */
public PrivateKey bytesToPrivateKey(byte[] pemKey) throws CryptoException {
    PrivateKey pk = null;
    CryptoException ce = null;

    try {
        PemReader pr = new PemReader(new StringReader(new String(pemKey)));
        PemObject po = pr.readPemObject();
        PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

        if (po.getType().equals("PRIVATE KEY")) {
            pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
        } else {
            logger.trace("Found private key with type " + po.getType());
            PEMKeyPair kp = (PEMKeyPair) pem.readObject();
            pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to convert private key bytes", e);
    }
    return pk;
}
 
Example #16
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createTrustStore() throws CryptoException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        setTrustStore(keyStore);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | InvalidArgumentException e) {
        throw new CryptoException("Cannot create trust store. Error: " + e.getMessage(), e);
    }
}
 
Example #17
Source File: IdemixSigningIdentity.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] sign(byte[] msg) throws CryptoException, InvalidArgumentException {
    if (msg == null) {
        throw new InvalidArgumentException("Input must not be null");
    }
    return new IdemixPseudonymSignature(this.sk, this.pseudonym, this.ipk, msg).toProto().toByteArray();
}
 
Example #18
Source File: ProtoUtils.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public static Common.Envelope createSeekInfoEnvelope(TransactionContext transactionContext, Ab.SeekPosition startPosition,
                                              Ab.SeekPosition stopPosition,
                                              Ab.SeekInfo.SeekBehavior seekBehavior, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException {
    return createSeekInfoEnvelope(transactionContext, Ab.SeekInfo.newBuilder()
            .setStart(startPosition)
            .setStop(stopPosition)
            .setBehavior(seekBehavior)
            .build(), tlsCertHash);
}
 
Example #19
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void addCACertificateToTrustStore(Certificate certificate) throws InvalidArgumentException, CryptoException {

        String alias;
        if (certificate instanceof X509Certificate) {
            alias = ((X509Certificate) certificate).getSerialNumber().toString();
        } else { // not likely ...
            alias = Integer.toString(certificate.hashCode());
        }
        addCACertificateToTrustStore(certificate, alias);
    }
 
Example #20
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * addCACertificateToTrustStore adds a CA cert to the set of certificates used for signature validation
 *
 * @param caCert an X.509 certificate
 * @param alias  an alias associated with the certificate. Used as shorthand for the certificate during crypto operations
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
void addCACertificateToTrustStore(Certificate caCert, String alias) throws InvalidArgumentException, CryptoException {

    if (alias == null || alias.isEmpty()) {
        throw new InvalidArgumentException("You must assign an alias to a certificate when adding to the trust store.");
    }

    if (caCert == null) {
        throw new InvalidArgumentException("Certificate cannot be null.");
    }

    try {
        if (config.extraLogLevel(10)) {
            if (null != diagnosticFileDumper) {
                logger.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + diagnosticFileDumper.createDiagnosticFile(alias + "cert: " + caCert.toString()));
            }
        }
        synchronized (certificateSet) {
            if (certificateSet.contains(alias)) {
                return;
            }

            getTrustStore().setCertificateEntry(alias, caCert);
            certificateSet.add(alias);

        }
    } catch (KeyStoreException e) {
        String emsg = "Unable to add CA certificate to trust store. Error: " + e.getMessage();
        logger.error(emsg, e);
        throw new CryptoException(emsg, e);
    }
}
 
Example #21
Source File: IdemixTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean call() throws CryptoException {
    for (int i = ITERATIONS; i > 0; --i) {
        test();
    }
    return true;
}
 
Example #22
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public void loadCACertificatesAsBytes(Collection<byte[]> certificatesBytes) throws CryptoException {
    if (certificatesBytes == null || certificatesBytes.size() == 0) {
        throw new CryptoException("List of CA certificates is empty. Nothing to load.");
    }

    ArrayList<Certificate> certList = new ArrayList<>();
    for (byte[] certBytes : certificatesBytes) {
        certList.add(bytesToCertificate(certBytes));
    }
    loadCACertificates(certList);

}
 
Example #23
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
boolean validateCertificate(Certificate cert) {
    boolean isValidated;

    if (cert == null) {
        return false;
    }

    try {
        KeyStore keyStore = getTrustStore();

        PKIXParameters parms = new PKIXParameters(keyStore);
        parms.setRevocationEnabled(false);

        CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX

        ArrayList<Certificate> start = new ArrayList<>();
        start.add(cert);
        CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
        CertPath certPath = certFactory.generateCertPath(start);

        certValidator.validate(certPath, parms);
        isValidated = true;
    } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException
            | CertificateException | CertPathValidatorException | CryptoException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate"
                + cert.toString());
        isValidated = false;
    }

    return isValidated;
}
 
Example #24
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private KeyPair generateKey(String encryptionName, String curveName) throws CryptoException {
    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = SECURITY_PROVIDER == null ? KeyPairGenerator.getInstance(encryptionName) :
                KeyPairGenerator.getInstance(encryptionName, SECURITY_PROVIDER);
        g.initialize(ecGenSpec, new SecureRandom());
        return g.generateKeyPair();
    } catch (Exception exp) {
        throw new CryptoException("Unable to generate key pair", exp);
    }
}
 
Example #25
Source File: IdemixIdentitiesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void testIdemixSigningIdentityBroken() throws IOException {
    try {
        createIdemixSigningIdentity(MSP1Broken);
    } catch (CryptoException | InvalidArgumentException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        fail("Unexpected Exception" + e.getMessage());
    }

}
 
Example #26
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Sign data with the specified elliptic curve private key.
 *
 * @param privateKey elliptic curve private key.
 * @param data       data to sign
 * @return the signed data.
 * @throws CryptoException
 */
private byte[] ecdsaSignToBytes(ECPrivateKey privateKey, byte[] data) throws CryptoException {
    if (data == null) {
        throw new CryptoException("Data that to be signed is null.");
    }
    if (data.length == 0) {
        throw new CryptoException("Data to be signed was empty.");
    }

    try {
        X9ECParameters params = ECNamedCurveTable.getByName(curveName);
        BigInteger curveN = params.getN();

        Signature sig = SECURITY_PROVIDER == null ? Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM) :
                Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
        sig.initSign(privateKey);
        sig.update(data);
        byte[] signature = sig.sign();

        BigInteger[] sigs = decodeECDSASignature(signature);

        sigs = preventMalleability(sigs, curveN);

        try (ByteArrayOutputStream s = new ByteArrayOutputStream()) {

            DERSequenceGenerator seq = new DERSequenceGenerator(s);
            seq.addObject(new ASN1Integer(sigs[0]));
            seq.addObject(new ASN1Integer(sigs[1]));
            seq.close();
            return s.toByteArray();
        }

    } catch (Exception e) {
        throw new CryptoException("Could not sign the message using private key", e);
    }

}
 
Example #27
Source File: IdemixIdentitiesTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidArgumentException.class)
public void testIdemixSigningIdentityInputNullPk() throws InvalidArgumentException {
    try {
        new IdemixSigningIdentity(null, revocationPk, MSP1OU1, sk, cred, cri, OU1, IdemixRoles.MEMBER.getValue());
    } catch (CryptoException e) {
        fail("Unexpected Crypto exception");
    }
}
 
Example #28
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public void init() throws CryptoException, InvalidArgumentException {
    if (inited.getAndSet(true)) {
        throw new InvalidArgumentException("Crypto suite already initialized");
    } else {
        resetConfiguration();
    }

}
 
Example #29
Source File: IdemixSigningIdentity.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verifySignature(byte[] msg, byte[] sig) throws CryptoException, InvalidArgumentException {

    if (msg == null) {
        throw new InvalidArgumentException("Message must not be null");
    }

    if (sig == null) {
        throw new InvalidArgumentException("Signature must not be null");
    }

    Idemix.NymSignature nymSigProto = null;
    try {
        nymSigProto = Idemix.NymSignature.parseFrom(sig);
    } catch (InvalidProtocolBufferException e) {
        logger.error("Idemix Nym Signature parsing error, dumping \nSignature: " + Arrays.toString(sig) + " \nMessage: " + Arrays.toString(msg));
        throw new CryptoException("Could not parse Idemix Nym Signature", e);
    }

    IdemixPseudonymSignature nymSig = new IdemixPseudonymSignature(nymSigProto);
    if (!nymSig.verify(this.pseudonym.getNym(), this.ipk, msg)) {
        logger.error("Idemix Nym Signature verification error, dumping \nSignature: " + Arrays.toString(sig) + " \nMessage: " + Arrays.toString(msg));
        return false;
    }

    return true;
}
 
Example #30
Source File: TestUtils.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] sign(byte[] msg) throws CryptoException {
    try {
        return CryptoSuite.Factory.getCryptoSuite().sign(this.enrollment.getKey(), msg);
    } catch (Exception e) {
        throw new CryptoException(e.getMessage(), e);
    }
}