List of usage examples for org.bouncycastle.asn1 ASN1Integer ASN1Integer
public ASN1Integer(byte[] bytes)
From source file:at.asitplus.regkassen.common.util.CryptoUtil.java
License:Apache License
/** * Helper method to convert concatenated signature values (as used by the JWS-standard) to * DER-encoded signature values (e.g. used by Java) * * @param concatenatedSignatureValue// w ww.j a v a 2 s. c om * concatenated signature value (as used by JWS standard) * @return DER-encoded signature value * @throws IOException */ public static byte[] convertJWSConcatenatedToDEREncodedSignature(final byte[] concatenatedSignatureValue) throws IOException { final byte[] r = new byte[33]; final byte[] s = new byte[33]; System.arraycopy(concatenatedSignatureValue, 0, r, 1, 32); System.arraycopy(concatenatedSignatureValue, 32, s, 1, 32); final BigInteger rBigInteger = new BigInteger(r); final BigInteger sBigInteger = new BigInteger(s); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DERSequenceGenerator seqGen = new DERSequenceGenerator(bos); seqGen.addObject(new ASN1Integer(rBigInteger.toByteArray())); seqGen.addObject(new ASN1Integer(sBigInteger.toByteArray())); seqGen.close(); bos.close(); final byte[] derEncodedSignatureValue = bos.toByteArray(); return derEncodedSignatureValue; }
From source file:bft.BFTNode.java
private byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException { //convert long to byte array //ByteArrayOutputStream bos = new ByteArrayOutputStream(); //ObjectOutput out = new ObjectOutputStream(bos); //out.writeLong(header.getNumber()); //out.flush(); //bos.flush(); //out.close(); //bos.close(); //byte[] number = bos.toByteArray(); // encode the header in ASN1 format ByteArrayOutputStream bos = new ByteArrayOutputStream(); ASN1OutputStream asnos = new ASN1OutputStream(bos); asnos.writeObject(new ASN1Integer((int) header.getNumber())); //asnos.writeObject(new DERInteger((int) header.getNumber())); asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray())); asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray())); asnos.flush();// ww w. j ava2 s. c o m bos.flush(); asnos.close(); bos.close(); byte[] buffer = bos.toByteArray(); //Add golang idiosyncrasies byte[] bytes = new byte[buffer.length + 2]; bytes[0] = 48; // no idea what this means, but golang's encoding uses it bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang for (int i = 0; i < buffer.length; i++) { // concatenate bytes[i + 2] = buffer[i]; } return bytes; }
From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java
License:Apache License
/** * Reconstruct the private key from the reconstruction data * * @param identifyingInfo the identity portion of the implicit certificate * @param reconstructionPoint the reconstruction point for the implicit certificate * @param privateKeyReconstructionData the private key reconstruction data associated with the * implicit certificate// ww w. j av a 2 s . c o m * @param ephemeralPrivateKey the requesters ephemeral private key * * @return the private key associated with the implicit certificate * * @throws IOException when there are errors with, or malformed provided data */ public PrivateKey reconstructPrivateKey(byte[] identifyingInfo, byte[] reconstructionPoint, byte[] privateKeyReconstructionData, PrivateKey ephemeralPrivateKey) throws IOException { // curve point order BigInteger n = curveParameters.getN(); // calculate H(Certu) for (byte b : identifyingInfo) { digest.update(b); } for (byte b : reconstructionPoint) { digest.update(b); } // compute the integer e from H(Certu) BigInteger e = calculateE(n, digest.digest()).mod(n); // compute the private Key dU = r + e*kU (mod n) BigInteger r = octetStringToInteger(privateKeyReconstructionData); // Check that the 'r' is less than 'n' if (n.compareTo(r) != 1) { throw new IOException("Octet String value is larger than modulus"); } // Private key dU. BigInteger dU = ((BCECPrivateKey) ephemeralPrivateKey).getD(); dU = e.multiply(dU); dU = r.add(dU); dU = dU.mod(n); return BouncyCastleProvider .getPrivateKey(new PrivateKeyInfo(algorithmId, new ASN1Integer(dU.toByteArray()))); }
From source file:ca.trustpoint.m2m.M2mCertificate.java
License:Apache License
/** * Returns the DER encoded to be signed certificate data. This is what would be sent to a CA for * signing, or the data that will be verified with the signature. * * @return The DER encoded to be signed certificate data. * @throws IOException if the encoding fails. *///from www.j a va2s. c o m public byte[] getTBSCertificate() throws IOException { if (!isTbsCertificateValid()) { throw new IOException("One or more TBS certificate fields are invalid."); } ASN1EncodableVector elements = new ASN1EncodableVector(); /* * Since the default is v1 (0), we do not need to explicitly add this to the ASN.1 output. * * elements.add( new DERTaggedObject( false, TbsCertificateFields.VERSION.getTagNumber(), new * ASN1Integer(VERSION))); */ elements.add(new DERTaggedObject(false, TbsCertificateFields.SERIAL_NUMBER.getTagNumber(), new DEROctetString(serialNumber))); if (caKeyDefinition != null) { if (caKeyDefinition.getAlgorithm() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM.getTagNumber(), ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedAlgorithm()))); } if (caKeyDefinition.getParameters() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM_PARAMETERS.getTagNumber(), ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedParameters()))); } } if (issuer != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.ISSUER.getTagNumber(), DERSequence.getInstance(issuer.getEncoded()))); } if (validFrom != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_FROM.getTagNumber(), // We record seconds, not milliseconds, hence the / 1000 new DEROctetString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray()))); } if (validDuration != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_DURATION.getTagNumber(), new DEROctetString(BigInteger.valueOf(validDuration.intValue()).toByteArray()))); } elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT.getTagNumber(), DERSequence.getInstance(subject.getEncoded()))); if (publicKeyDefinition != null) { if (publicKeyDefinition.getAlgorithm() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY_ALGORITHM.getTagNumber(), ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedAlgorithm()))); } if (publicKeyDefinition.getParameters() != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY_ALGORITHM_PARAMETERS.getTagNumber(), ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedParameters()))); } } if (publicKey != null) { byte[] publicKeyBytes = KeyConversionUtils.convertEcPublicKeyToRawBytes(publicKey, isPublicKeyCompressed); elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY.getTagNumber(), new DEROctetString(publicKeyBytes))); } if (authorityKeyIdentifier != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.AUTHORITY_KEY_ID.getTagNumber(), ASN1Primitive.fromByteArray(authorityKeyIdentifier.getEncoded()))); } if (subjectKeyIdentifier != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT_KEY_ID.getTagNumber(), new DEROctetString(subjectKeyIdentifier))); } if (keyUsage != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.KEY_USAGE.getTagNumber(), ASN1Primitive.fromByteArray(keyUsage.getEncoded()))); } if (basicConstraints != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.BASIC_CONSTRAINTS.getTagNumber(), new ASN1Integer(basicConstraints.intValue()))); } if (certificatePolicy != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CERTIFICATE_POLICY.getTagNumber(), new ASN1ObjectIdentifier(certificatePolicy))); } if (subjectAlternativeName != null) { elements.add(new DERTaggedObject(true, TbsCertificateFields.SUBJECT_ALTERNATE_NAME.getTagNumber(), DERTaggedObject.getInstance(subjectAlternativeName.getEncoded()))); } if (issuerAlternativeName != null) { elements.add(new DERTaggedObject(true, TbsCertificateFields.ISSUER_ALTERNATE_NAME.getTagNumber(), DERTaggedObject.getInstance(issuerAlternativeName.getEncoded()))); } if (extendedKeyUsage != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENDED_KEY_USAGE.getTagNumber(), new ASN1ObjectIdentifier(extendedKeyUsage))); } if (authenticationInfoAccessOcsp != null) { elements.add( new DERTaggedObject(false, TbsCertificateFields.AUTHENTICATION_INFO_ACCESS_OCSP.getTagNumber(), new DERIA5String(authenticationInfoAccessOcsp.toString()))); } if (crlDistributionPointUri != null) { elements.add(new DERTaggedObject(false, TbsCertificateFields.CRL_DISTRIBUTION_POINT_URI.getTagNumber(), new DERIA5String(crlDistributionPointUri.toString()))); } if (!extensions.isEmpty()) { ASN1EncodableVector toBeEncodedExtensions = new ASN1EncodableVector(); for (Extension extension : extensions) { toBeEncodedExtensions.add(new DERSequence(extension.getEncoded())); } elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENSIONS.getTagNumber(), new DERSequence(toBeEncodedExtensions))); } return ((new DERSequence(elements)).getEncoded()); }
From source file:ca.trustpoint.m2m.M2mCertificateFactoryTest.java
License:Apache License
@BeforeClass public static void initializeTests() throws Exception { // Construct certificate data // A full certificate M2mCertificate cert = new M2mCertificate(); // serialNumber byte[] serialNumber = Hex.decode("F964EF36"); cert.setSerialNumber(serialNumber);/*from w w w. j a va2s . c o m*/ // cAAlgorithm, CAAlgParams KeyAlgorithmDefinition caKeyDefinition = new KeyAlgorithmDefinition(); caKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1); caKeyDefinition.setParameters(Hex.decode("102030405060708090A0B0C0E0F0")); cert.setCaKeyDefinition(caKeyDefinition); // issuer EntityName issuer = new EntityName(); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyRoot")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC")); issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f00")); cert.setIssuer(issuer); // validFrom Calendar calendar = new GregorianCalendar(2016, 7, 1); Date validFrom = calendar.getTime(); cert.setValidFrom(validFrom); // validDuration cert.setValidDuration(60 * 60 * 24 * 365); // subject EntityName subject = new EntityName(); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyTest")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC")); subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f01")); cert.setSubject(subject); // pKAlgorithm, pKAlgParams KeyAlgorithmDefinition publicKeyDefinition = new KeyAlgorithmDefinition(); publicKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1); publicKeyDefinition.setParameters(Hex.decode("0102030405060708090A0B0C0E0F")); cert.setPublicKeyDefinition(publicKeyDefinition); // pubKey byte[] rawPublicKey = Hex.decode("040078EF059D605AB85B6A25A6EF31A1A73A632D3CB04DC606A8CA0B58239661" + "68CFAF6131D8D9B53F6BDF6B62946EC4B41D618FA3FF7F8BBFACBFD4F64FE3C3" + "3DA9D200A47AE528DC50B6F3876D7F5BA3C082D9927751E1A8C4F934D90942B3" + "5C57DFE311B2663E8D0187AD4EDE31BF9CD2AD8317107360522FDB6975AB2CD6" + "6DC029981F"); boolean isCompressed = KeyConversionUtils.isCompressedEcPoint(rawPublicKey); cert.setIsPublicKeyCompressed(isCompressed); PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey); cert.setPublicKey(publicKey); // authKeyId AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(); authKeyId.setKeyIdentifier(Hex.decode("793F0C56")); GeneralName authKeyIdIssuer = new GeneralName(GeneralNameAttributeId.DnsName, "authKeyIdIssuer"); authKeyId.setCertificateIssuer(authKeyIdIssuer); authKeyId.setCertificateSerialNumber(new BigInteger(Hex.decode("729CB27DAE30"))); cert.setAuthorityKeyIdentifier(authKeyId); // subjKeyId cert.setSubjectKeyIdentifier(Hex.decode("729CB27DAE31")); // keyUsage KeyUsage keyUsage = new KeyUsage(); keyUsage.setDigitalSignature(true); cert.setKeyUsage(keyUsage); // basicConstraints cert.setBasicConstraints(5); // certificatePolicy cert.setCertificatePolicy("1.2.66.148.0.12"); // subjectAltName GeneralName subjectAltName = new GeneralName(GeneralNameAttributeId.DnsName, "subjectAltName"); cert.setSubjectAlternativeName(subjectAltName); // issuerAltName GeneralName issuerAltName = new GeneralName(GeneralNameAttributeId.DnsName, "issuerAltName"); cert.setIssuerAlternativeName(issuerAltName); // extendedKeyUsage cert.setExtendedKeyUsage("1.3.22.174.22"); // authInfoAccessOCSP URI authInfoAccessOCSP = new URI("https://ocsptest.trustpointinnovation.com"); cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP); // cRLDistribPointURI URI cRLDistribPointURI = new URI("https://ocsptest.trustpointinnovation.com"); cert.setCrlDistributionPointUri(cRLDistribPointURI); // x509extensions String oid1 = "1.5.24.632.0"; String oid2 = "1.5.24.632.1"; byte[] value1 = Hex.decode("003a772fb1"); byte[] value2 = Hex.decode("98f2b10e27"); cert.addExtension(oid1, true, value1); cert.addExtension(oid2, false, value2); // cACalcValue byte[] caCalcValue = Hex.decode("3081880242014F15CAF8EF38626B2C7CFA85B9544E028668290CADB45F62E215" + "3EAAF5A9D51AF5BF0D02F2C057D3856B5CBFB3529C25B8481405924039FA612D" + "422AE9A1A85591024201868D3DFE5FC2BEDD2F7468B0B17ED2708E76CD0D37C4" + "4F4D0BB88693752046FCFC56D9818B32533B8992923C2C81499400AC44FBBECD" + "6324D8AE1DD41EC73A0B2A"); cert.setCaCalcValue(caCalcValue); // get encoded data fullCertData = cert.getEncoded(); int mySignerIndex = 0; int myIssuerIndex = 1; int bluelineIndex = 2; int certsTotal = 3; // construct certificate array ASN1Encodable[] certArray = new ASN1Encodable[certsTotal]; certArray[mySignerIndex] = ASN1Primitive.fromByteArray(signerData); certArray[myIssuerIndex] = ASN1Primitive.fromByteArray(issuerData); certArray[bluelineIndex] = ASN1Primitive.fromByteArray(rootcaData); ASN1EncodableVector vCerts; // Construct PKI Path encoding input data vCerts = new ASN1EncodableVector(); vCerts.add(certArray[bluelineIndex]); vCerts.add(certArray[myIssuerIndex]); vCerts.add(certArray[mySignerIndex]); pkiPathInputData = new DERSequence(vCerts).getEncoded(); // Construct PKCS7 encoding input data ASN1EncodableVector vContentInfo = new ASN1EncodableVector(); // contentType ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.data; vContentInfo.add(contentType); // content: signedData ASN1EncodableVector vSignedData = new ASN1EncodableVector(); // version ASN1Integer sdVersion = new ASN1Integer(BigInteger.ONE); vSignedData.add(sdVersion); // digestAlgorithmIds DERSet sdDigestAlgorithmIds = new DERSet(); vSignedData.add(sdDigestAlgorithmIds); // contentInfo without content BERSequence sdContentInfo = new BERSequence(PKCSObjectIdentifiers.data); vSignedData.add(sdContentInfo); // certificates [0] IMPLICIT SET OF certificate vCerts = new ASN1EncodableVector(); vCerts.add(certArray[mySignerIndex]); vCerts.add(certArray[myIssuerIndex]); vCerts.add(certArray[bluelineIndex]); DERTaggedObject sdCertificates = new DERTaggedObject(false, 0, new DERSet(vCerts)); vSignedData.add(sdCertificates); // signerInfos DERSet sdSignerInfos = new DERSet(); vSignedData.add(sdSignerInfos); // content [0] EXPLICIT SEQUENCE signedData BERSequence signedData = new BERSequence(vSignedData); BERTaggedObject content = new BERTaggedObject(true, 0, signedData); vContentInfo.add(content); BERSequence contentInfo = new BERSequence(vContentInfo); pkcs7InputData = contentInfo.getEncoded(); // Contruct cert path data list // Certificates are store in M2MCertPath from target to trust anchor. expectedCertPathData = new byte[][] { signerData, issuerData, rootcaData }; }
From source file:ca.trustpoint.m2m.M2mCertPath.java
License:Apache License
/** * Encode the CertPath using PKCS#7 format. * * @return a byte array containing the binary encoding of the PKCS#7 object * @exception CertificateEncodingException if an exception occurs *//*from ww w .ja v a 2 s . c om*/ private byte[] encodePkcs7() throws CertificateEncodingException { ASN1EncodableVector encodedList = new ASN1EncodableVector(); for (M2mCertificate certificate : certificates) { if (isDuplicateCertificate(certificate)) { throw new CertificateEncodingException("Duplicate certificate detected in path."); } try { encodedList.add(ASN1Primitive.fromByteArray(certificate.getEncoded())); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate data.", ex); } } SignedData sd = new SignedData(new ASN1Integer(BigInteger.ONE), // version new DERSet(), // digestAlgorithmIds new ContentInfo(PKCSObjectIdentifiers.data, null), // contentInfo new DERSet(encodedList), // certificates (optional) null, // CRLs (optional) new DERSet() // signerInfos ); // make it a content info sequence ContentInfo ci = new ContentInfo(PKCSObjectIdentifiers.data, sd); try { return ci.getEncoded(); } catch (IOException ex) { throw new CertificateEncodingException("Error encoding certificate path.", ex); } }
From source file:com.android.verity.BootSignature.java
License:Apache License
public BootSignature(String target, int length) { this.formatVersion = new ASN1Integer(0); this.target = new DERPrintableString(target); this.length = new ASN1Integer(length); this.algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption); }
From source file:com.android.verity.BootKey.java
License:Apache License
public BootKeystore() { this.formatVersion = new ASN1Integer(0); this.keyBag = new ASN1EncodableVector(); }
From source file:com.facebook.delegatedrecovery.RecoveryToken.java
License:Open Source License
private byte[] getSignature(final byte[] rawArray, final ECPrivateKey privateKey) throws IOException { if (this.signature != null) { throw new IllegalStateException("This token already has a signature."); }/*from w w w . ja v a 2 s .c om*/ final BigInteger privatePoint = privateKey.getS(); final SHA256Digest digest = new SHA256Digest(); final byte[] hash = new byte[digest.getByteLength()]; digest.update(rawArray, 0, rawArray.length); digest.doFinal(hash, 0); final ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); signer.init(true, new ECPrivateKeyParameters(privatePoint, DelegatedRecoveryUtils.P256_DOMAIN_PARAMS)); final BigInteger[] signature = signer.generateSignature(hash); final ByteArrayOutputStream s = new ByteArrayOutputStream(); final DERSequenceGenerator seq = new DERSequenceGenerator(s); seq.addObject(new ASN1Integer(signature[0])); seq.addObject(new ASN1Integer(signature[1])); seq.close(); return s.toByteArray(); }
From source file:com.github.horrorho.inflatabledonkey.data.der.BackupEscrow.java
License:Open Source License
@Override public ASN1Primitive toASN1Primitive() { ASN1EncodableVector vector = DER.vector(new DEROctetString(wrappedKey()), new DEROctetString(data()), new DEROctetString(x()), new ASN1Integer(y), new DEROctetString(masterKeyPublic())); DERSequence sequence = new DERSequence(vector); return DER.toApplicationSpecific(APPLICATION_TAG, sequence); }