org.spongycastle.asn1.ASN1Integer Java Examples

The following examples show how to use org.spongycastle.asn1.ASN1Integer. 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: BTCUtils.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public static boolean verify(byte[] publicKey, byte[] signature, byte[] msg) {
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters EC_PARAMS = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    synchronized (EC_PARAMS) {
        boolean valid;
        ECDSASigner signerVer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        try {
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(EC_PARAMS.getCurve().decodePoint(publicKey), EC_PARAMS);
            signerVer.init(false, pubKey);
            ASN1InputStream derSigStream = new ASN1InputStream(signature);
            DLSequence seq = (DLSequence) derSigStream.readObject();
            BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
            BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
            derSigStream.close();
            valid = signerVer.verifySignature(msg, r, s);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return valid;
    }
}
 
Example #2
Source File: Crypto.java    From particle-android with Apache License 2.0 6 votes vote down vote up
static PublicKey buildPublicKey(byte[] rawBytes) throws CryptoException {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rawBytes));
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo
                .getInstance(new ASN1InputStream(bIn.readObject().getEncoded()).readObject());
        DLSequence dlSequence = (DLSequence) ASN1Primitive.fromByteArray(info.getPublicKeyData().getBytes());
        BigInteger modulus = ((ASN1Integer) dlSequence.getObjectAt(0)).getPositiveValue();
        BigInteger exponent = ((ASN1Integer) dlSequence.getObjectAt(1)).getPositiveValue();

        RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory kf = getRSAKeyFactory();
        return kf.generatePublic(spec);
    } catch (InvalidKeySpecException | IOException e) {
        throw new CryptoException(e);
    }
}
 
Example #3
Source File: Crypto.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
static PublicKey buildPublicKey(byte[] rawBytes) throws CryptoException {
    try {
        //FIXME replacing X509EncodedKeySpec because of problem with 8.1
        //Since 8.1 Bouncycastle cryptography was replaced with implementation from Conscrypt
        //https://developer.android.com/about/versions/oreo/android-8.1.html
        //either it's a bug in Conscrypt, our public key DER structure or use of X509EncodedKeySpec changed
        //alternative needed as this adds expensive Spongycastle dependence
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rawBytes));
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo
                .getInstance(new ASN1InputStream(bIn.readObject().getEncoded()).readObject());
        DLSequence dlSequence = (DLSequence) ASN1Primitive.fromByteArray(info.getPublicKeyData().getBytes());
        BigInteger modulus = ((ASN1Integer) dlSequence.getObjectAt(0)).getPositiveValue();
        BigInteger exponent = ((ASN1Integer) dlSequence.getObjectAt(1)).getPositiveValue();

        RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory kf = getRSAKeyFactory();
        return kf.generatePublic(spec);
    } catch (InvalidKeySpecException | IOException e) {
        throw new CryptoException(e);
    }
}
 
Example #4
Source File: ECKey.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by the BitCoin reference
 * implementation in its wallet storage format.
 */
public byte[] toASN1() {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(400);

        // ASN1_SEQUENCE(EC_PRIVATEKEY) = {
        //   ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
        //   ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
        //   ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
        //   ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
        // } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(1)); // version
        seq.addObject(new DEROctetString(priv.toByteArray()));
        seq.addObject(new DERTaggedObject(0, SECNamedCurves.getByName("secp256k1").toASN1Primitive()));
        seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen, writing to memory stream.
    }
}
 
Example #5
Source File: ECKey.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private static BigInteger extractPrivateKeyFromASN1(byte[] asn1privkey) {
    // To understand this code, see the definition of the ASN.1 format for EC private keys in the OpenSSL source
    // code in ec_asn1.c:
    //
    // ASN1_SEQUENCE(EC_PRIVATEKEY) = {
    //   ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
    //   ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
    //   ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
    //   ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
    // } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
    //
    try {
        ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
        DLSequence seq = (DLSequence) decoder.readObject();
        checkArgument(seq.size() == 4, "Input does not appear to be an ASN.1 OpenSSL EC private key");
        checkArgument(((ASN1Integer) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE),
                "Input is of wrong version");
        Object obj = seq.getObjectAt(1);
        byte[] bits = ((ASN1OctetString) obj).getOctets();
        decoder.close();
        return new BigInteger(1, bits);
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen, reading from memory stream.
    }
}
 
Example #6
Source File: SM2Util.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static ByteArrayOutputStream derByteStream(BigInteger r,BigInteger s) throws IOException {
    // Usually 70-72 bytes.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(r));
    seq.addObject(new ASN1Integer(s));
    seq.close();
    return bos;
}
 
Example #7
Source File: ZCashTransaction_taddr.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getInputSignature(Tx_in input) throws ZCashException {
  byte[] personalization = Bytes.concat(ZCASH_SIGNATURE_HASH_PERSONALIZATION, Utils.int32BytesLE(consensusBranchId));
  Blake2bDigest tx_digest = new Blake2bDigest(null, 32, null, personalization);
  byte[] preimage = Bytes.concat(
    tx_sig_bytes,
    input.txid,
    Utils.int32BytesLE(input.index),
    Utils.compactSizeIntLE(input.script.length),
    input.script,
    Utils.int64BytesLE(input.value),
    Utils.int32BytesLE(input.sequence)
  );

  byte[] hash = new byte[32];
  tx_digest.update(preimage, 0, preimage.length);
  tx_digest.doFinal(hash, 0);
  Sha256Hash sha256Hash = new Sha256Hash(hash);
  ECKey.ECDSASignature sig = privKey.sign(sha256Hash);
  sig = sig.toCanonicalised();
  ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
  try {
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(sig.r));
    seq.addObject(new ASN1Integer(sig.s));
    seq.close();
  } catch (IOException e) {
    throw new ZCashException("Cannot encode signature into transaction in ZCashTransaction_taddr.getInputSignature", e);
  }

  return bos.toByteArray();
}
 
Example #8
Source File: ZCashTransaction_taddr.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getInputSignature(Tx_in input) throws ZCashException {
  byte[] personalization = Bytes.concat(ZCASH_SIGNATURE_HASH_PERSONALIZATION, Utils.int32BytesLE(consensusBranchId));
  Blake2bDigest tx_digest = new Blake2bDigest(null, 32, null, personalization);
  byte[] preimage = Bytes.concat(
    tx_sig_bytes,
    input.txid,
    Utils.int32BytesLE(input.index),
    Utils.compactSizeIntLE(input.script.length),
    input.script,
    Utils.int64BytesLE(input.value),
    Utils.int32BytesLE(input.sequence)
  );

  byte[] hash = new byte[32];
  tx_digest.update(preimage, 0, preimage.length);
  tx_digest.doFinal(hash, 0);
  Sha256Hash sha256Hash = new Sha256Hash(hash);
  ECKey.ECDSASignature sig = privKey.sign(sha256Hash);
  sig = sig.toCanonicalised();
  ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
  try {
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(sig.r));
    seq.addObject(new ASN1Integer(sig.s));
    seq.close();
  } catch (IOException e) {
    throw new ZCashException("Cannot encode signature into transaction in ZCashTransaction_taddr.getInputSignature", e);
  }

  return bos.toByteArray();
}
 
Example #9
Source File: ECDSAAlgorithm.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
protected ByteArrayOutputStream derByteStream() throws IOException {
    // Usually 70-72 bytes.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(r));
    seq.addObject(new ASN1Integer(s));
    seq.close();
    return bos;
}
 
Example #10
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
protected ByteArrayOutputStream derByteStream() throws IOException {
    // Usually 70-72 bytes.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(r));
    seq.addObject(new ASN1Integer(s));
    seq.close();
    return bos;
}
 
Example #11
Source File: Asn1.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 	 * DER - From Big Integer rs to byte[]
 	 * 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 byte[] getEncoded(BigInteger[] sigs)
		throws IOException {
	ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
	DERSequenceGenerator seq = new DERSequenceGenerator(bos);
	seq.addObject(new ASN1Integer(sigs[0]));
	seq.addObject(new ASN1Integer(sigs[1]));
	seq.close();
	return bos.toByteArray();
}
 
Example #12
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 #13
Source File: ECKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
protected ByteArrayOutputStream derByteStream() throws IOException {
    // Usually 70-72 bytes.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
    DERSequenceGenerator seq = new DERSequenceGenerator(bos);
    seq.addObject(new ASN1Integer(r));
    seq.addObject(new ASN1Integer(s));
    seq.close();
    return bos;
}