Java Code Examples for org.bouncycastle.asn1.ASN1InputStream#close()

The following examples show how to use org.bouncycastle.asn1.ASN1InputStream#close() . 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: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 2
Source File: BouncyCastleCrypto.java    From fabric-api with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 3
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 6 votes vote down vote up
private void parseDsaKeyPair(byte[] blob) throws GeneralSecurityException,
        IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();

    ASN1Integer p = (ASN1Integer) seq.getObjectAt(1);
    ASN1Integer q = (ASN1Integer) seq.getObjectAt(2);
    ASN1Integer g = (ASN1Integer) seq.getObjectAt(3);
    ASN1Integer y = (ASN1Integer) seq.getObjectAt(4);
    ASN1Integer x = (ASN1Integer) seq.getObjectAt(5);
    DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(),
            q.getValue(), g.getValue());
    DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(),
            g.getValue());

    KeyFactory kf = KeyFactory.getInstance("DSA");
    privateKey = kf.generatePrivate(privSpec);
    publicKey = kf.generatePublic(pubSpec);
}
 
Example 4
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    aIn.close();
    bIn.close();
    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    SignerInformation signer = c.iterator().next();
    Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
    Iterator<X509CertificateHolder> certIt = certCollection.iterator();
    X509CertificateHolder certHolder = certIt.next();
    boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
    if (!verifResult) {
        return false;
    }
    return true;
}
 
Example 5
Source File: ECDSASignatureProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static byte[] asn1derToConcatenatedRS(final byte[] derEncodedSignatureValue, int signLength) throws IOException {
    int len = signLength / 2;

    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();

    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), len);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), len);

    byte[] concatenatedSignatureValue = new byte[signLength];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, len);
    System.arraycopy(s, 0, concatenatedSignatureValue, len, len);

    return concatenatedSignatureValue;
}
 
Example 6
Source File: SslConfigurer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName)
  throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException {
  
  RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
  RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
  
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  
  ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded());
  SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject());
  publicKeyStream.close();
  
  X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())),
      new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
      new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)),
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      pubKey);
  
  RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus());
  ContentSigner contentSigner = sigGen.build(keyParams);
  
  X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner);
  
  JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");
  return certConverter.getCertificate(certificateHolder);
}
 
Example 7
Source File: LocalSignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Write the certificate file with a digital signature.
 */
private void writeSignatureBlock(CMSTypedData data,
                                 X509Certificate publicKey,
                                 PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" +
                                                                   privateKey.getAlgorithm()).build(
            privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                                                                         .build()).setDirectSignature(
            true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}
 
Example 8
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey,
        PrivateKey privateKey)
                    throws IOException,
                    CertificateEncodingException,
                    OperatorCreationException,
                    CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(
                                   "SHA1with" + privateKey.getAlgorithm())
                               .build(privateKey);
    gen.addSignerInfoGenerator(
        new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder()
            .build())
        .setDirectSignature(true)
        .build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}
 
Example 9
Source File: Asn1.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * DER - From byte[] to Big Integer rs
 * UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER 0x06 DER [ITU-X690-2008] encoded
 * ECDSA signature [RFC5480] on the secp256k1 curve. I.e. a DER encoded
 * SEQUENCE { r INTEGER, s INTEGER }
 * 
 * @param signature
 * @return
 * @throws IOException
 */
public static BigInteger[] decodeToBigIntegerArray(byte[] signature)
		throws IOException {
	ASN1InputStream decoder = new ASN1InputStream(signature);
	DLSequence seq = (DLSequence) decoder.readObject();
	ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
	ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);
	decoder.close();
	BigInteger[] ret = new BigInteger[2];
	ret[0] = r.getPositiveValue();
	ret[1] = s.getPositiveValue();
	return ret;
}
 
Example 10
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public static ECPrivateKey parseEcKey(byte[] blob) throws GeneralSecurityException,
        IOException, InvalidCipherTextException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    org.bouncycastle.asn1.sec.ECPrivateKey pk = org.bouncycastle.asn1.sec.ECPrivateKey
            .getInstance(ain.readObject());
    ain.close();

    return toJcaPrivateKey(pk);
}
 
Example 11
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public void parseRsaKeyPair(byte[] b) throws GeneralSecurityException, IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(b));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();

    org.bouncycastle.asn1.pkcs.RSAPrivateKey pk = org.bouncycastle.asn1.pkcs.RSAPrivateKey
            .getInstance(seq);
    privateKey = toJcaPrivateKey(pk);
    publicKey = toJcaPublicKey(pk);
}
 
Example 12
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public static RSAPrivateKey parseRsaKey(byte[] b) throws GeneralSecurityException, IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(b));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();
    for (int i = 0; i < seq.size(); i++) {
        ASN1Integer p = (ASN1Integer) seq.getObjectAt(i);
        System.out.printf("%d::%s\n", i, p.toString());
    }

    org.bouncycastle.asn1.pkcs.RSAPrivateKey pk = org.bouncycastle.asn1.pkcs.RSAPrivateKey
            .getInstance(seq);
    return toJcaPrivateKey(pk);
}
 
Example 13
Source File: ScepServlet.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected PKIMessage generatePkiMessage(InputStream is) throws IOException {
  ASN1InputStream asn1Stream = new ASN1InputStream(Args.notNull(is, "is"));

  try {
    return PKIMessage.getInstance(asn1Stream.readObject());
  } finally {
    try {
      asn1Stream.close();
    } catch (Exception ex) {
      LOG.error("could not close stream: {}", ex.getMessage());
    }
  }
}
 
Example 14
Source File: HttpScepServlet.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected PKIMessage generatePkiMessage(InputStream is) throws IOException {
  ASN1InputStream asn1Stream = new ASN1InputStream(is);

  try {
    return PKIMessage.getInstance(asn1Stream.readObject());
  } finally {
    try {
      asn1Stream.close();
    } catch (Exception ex) {
      LOG.error("could not close ASN1 stream: {}", asn1Stream);
    }
  }
}
 
Example 15
Source File: CipherSuiteUtil.java    From DeepViolet with Apache License 2.0 3 votes vote down vote up
/**
 * Convert <code>der</code> encoded data to <code>ASN1Primitive</code>.
 * For more information, 
 * (<a href="http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java">StackOverflow: How do I decode a DER encoded string in Java?</a>) 
 * @param data byte[] of <code>der</code> encoded data
 * @return <code>ASN1Primitive</code> representation of <code>der</code> encoded data
 * @throws IOException
 */
static final ASN1Primitive toDERObject(byte[] data) throws IOException {
	   
	ByteArrayInputStream inStream = new ByteArrayInputStream(data);
	
	ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
    
    ASN1Primitive p = asnInputStream.readObject();

    asnInputStream.close();
    
    return p;
}