List of usage examples for org.bouncycastle.asn1 ASN1Integer ASN1Integer
public ASN1Integer(byte[] bytes)
From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java
License:LGPL
public static void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, CipherSpec cipher, char[] passwd) throws IOException { BufferedWriter out = makeBuffered(_out); PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) new ASN1InputStream(getEncoded(obj)).readObject()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters()); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(0)); v.add(new ASN1Integer(p.getP())); v.add(new ASN1Integer(p.getQ())); v.add(new ASN1Integer(p.getG())); BigInteger x = obj.getX();/*from ww w . j ava 2 s. c o m*/ BigInteger y = p.getG().modPow(x, p.getP()); v.add(new ASN1Integer(y)); v.add(new ASN1Integer(x)); aOut.writeObject(new DLSequence(v)); byte[] encoding = bOut.toByteArray(); if (cipher != null && passwd != null) { writePemEncrypted(out, PEM_STRING_DSA, encoding, cipher, passwd); } else { writePemPlain(out, PEM_STRING_DSA, encoding); } }
From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java
License:LGPL
public static void writeDHParameters(Writer _out, DHParameterSpec params) throws IOException { BufferedWriter out = makeBuffered(_out); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); ASN1EncodableVector v = new ASN1EncodableVector(); BigInteger value;//from w w w.j a v a2s . c o m if ((value = params.getP()) != null) { v.add(new ASN1Integer(value)); } if ((value = params.getG()) != null) { v.add(new ASN1Integer(value)); } aOut.writeObject(new DLSequence(v)); byte[] encoding = bOut.toByteArray(); out.write(BEF_G + PEM_STRING_DHPARAMS + AFT); out.newLine(); writeEncoded(out, encoding); out.write(BEF_E + PEM_STRING_DHPARAMS + AFT); out.newLine(); out.flush(); }
From source file:org.kse.crypto.privatekey.OpenSslPvkUtil.java
License:Open Source License
/** * OpenSSL encode a private key./*w w w. j a v a 2 s. com*/ * * @return The encoding * @param privateKey * The private key * @throws CryptoException * Problem encountered while getting the encoded private key */ public static byte[] get(PrivateKey privateKey) throws CryptoException { // DER encoding for each key type is a sequence ASN1EncodableVector vec = new ASN1EncodableVector(); if (privateKey instanceof ECPrivateKey) { try { org.bouncycastle.asn1.sec.ECPrivateKey ecPrivateKey = org.bouncycastle.asn1.sec.ECPrivateKey .getInstance(privateKey.getEncoded()); return ecPrivateKey.toASN1Primitive().getEncoded(); } catch (IOException e) { throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), e); } } else if (privateKey instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; vec.add(new ASN1Integer(VERSION)); vec.add(new ASN1Integer(rsaPrivateKey.getModulus())); vec.add(new ASN1Integer(rsaPrivateKey.getPublicExponent())); vec.add(new ASN1Integer(rsaPrivateKey.getPrivateExponent())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeP())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeQ())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentP())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentQ())); vec.add(new ASN1Integer(rsaPrivateKey.getCrtCoefficient())); } else { DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey; DSAParams dsaParams = dsaPrivateKey.getParams(); BigInteger primeModulusP = dsaParams.getP(); BigInteger primeQ = dsaParams.getQ(); BigInteger generatorG = dsaParams.getG(); BigInteger secretExponentX = dsaPrivateKey.getX(); // Derive public key from private key parts, ie Y = G^X mod P BigInteger publicExponentY = generatorG.modPow(secretExponentX, primeModulusP); vec.add(new ASN1Integer(VERSION)); vec.add(new ASN1Integer(primeModulusP)); vec.add(new ASN1Integer(primeQ)); vec.add(new ASN1Integer(generatorG)); vec.add(new ASN1Integer(publicExponentY)); vec.add(new ASN1Integer(secretExponentX)); } DERSequence derSequence = new DERSequence(vec); try { return derSequence.getEncoded(); } catch (IOException ex) { throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), ex); } }
From source file:org.ScripterRon.BitcoinCore.ECDSASignature.java
License:Apache License
/** * Encodes R and S as a DER-encoded byte stream * * @return DER-encoded byte stream *///from www .j a v a 2s .c om public byte[] encodeToDER() { byte[] encodedBytes = null; try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream(80)) { DERSequenceGenerator seq = new DERSequenceGenerator(outStream); seq.addObject(new ASN1Integer(r)); seq.addObject(new ASN1Integer(s)); seq.close(); encodedBytes = outStream.toByteArray(); } } catch (IOException exc) { throw new IllegalStateException("Unexpected IOException", exc); } return encodedBytes; }
From source file:org.spout.api.security.SecurityHandler.java
License:Open Source License
public byte[] encodeKey(CipherParameters key) { if (!(key instanceof RSAKeyParameters)) { return null; }/*from w ww.ja v a2 s .c om*/ if (((RSAKeyParameters) key).isPrivate()) { return null; } RSAKeyParameters rsaKey = (RSAKeyParameters) key; ASN1EncodableVector encodable = new ASN1EncodableVector(); encodable.add(new ASN1Integer(rsaKey.getModulus())); encodable.add(new ASN1Integer(rsaKey.getExponent())); return KeyUtil.getEncodedSubjectPublicKeyInfo( new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, new DERNull()), new DERSequence(encodable)); }
From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection.java
License:Open Source License
private byte[] encodeSignature(byte[] signature, KeyFormat keyFormat) throws IOException { // Make sure the signature we received is actually the expected number of bytes long! switch (keyFormat.keyFormatType()) { case RSAKeyFormatType: // no encoding necessary int modulusLength = ((RSAKeyFormat) keyFormat).getModulusLength(); if (signature.length != (modulusLength / 8)) { throw new IOException("Bad signature length! Expected " + (modulusLength / 8) + " bytes, got " + signature.length); }//from ww w . j av a 2 s .c o m break; case ECKeyFormatType: // "plain" encoding, see https://github.com/open-keychain/open-keychain/issues/2108 if (signature.length % 2 != 0) { throw new IOException("Bad signature length!"); } final byte[] br = new byte[signature.length / 2]; final byte[] bs = new byte[signature.length / 2]; for (int i = 0; i < br.length; ++i) { br[i] = signature[i]; bs[i] = signature[br.length + i]; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1OutputStream out = new ASN1OutputStream(baos); out.writeObject(new DERSequence(new ASN1Encodable[] { new ASN1Integer(br), new ASN1Integer(bs) })); out.flush(); signature = baos.toByteArray(); break; } return signature; }
From source file:org.tdmx.client.crypto.certificate.TdmxZoneInfo.java
License:Open Source License
/** * Create a TdmxZoneInfo descriptor which describes a versioned TDMX relay interface for a normalized domain name * (zone apex).//from w ww . j av a2 s . c o m * * @param version * currently only 1 * @param zoneRoot * must be uppercase * @param mrsUrl * the MRS relay URL, ie. http://mrs.serviceprovider.com/api/v01/mrs */ public TdmxZoneInfo(int version, String zoneRoot, String mrsUrl) { this.version = new ASN1Integer(version); this.zoneRoot = new DERIA5String(zoneRoot); this.mrsUrl = new DERIA5String(mrsUrl); }
From source file:org.xipki.ca.certprofile.XmlX509Certprofile.java
License:Open Source License
private void doInitialize(final String data) throws CertprofileException { byte[] bytes; try {// w w w . ja v a 2 s.c o m bytes = data.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { bytes = data.getBytes(); } X509ProfileType conf = XmlX509CertprofileUtil.parse(new ByteArrayInputStream(bytes)); if (conf.getVersion() != null) { int intVersion = conf.getVersion().intValue(); this.version = X509CertVersion.getInstance(intVersion); if (this.version == null) { throw new CertprofileException("invalid version " + intVersion); } } else { this.version = X509CertVersion.V3; } if (conf.getSignatureAlgorithms() != null) { List<String> algoNames = conf.getSignatureAlgorithms().getAlgorithm(); this.signatureAlgorithms = new ArrayList<>(algoNames.size()); for (String algoName : algoNames) { try { this.signatureAlgorithms.add(AlgorithmUtil.canonicalizeSignatureAlgo(algoName)); } catch (NoSuchAlgorithmException e) { throw new CertprofileException(e.getMessage(), e); } } } this.raOnly = conf.isRaOnly(); this.qaOnly = conf.isQaOnly(); this.validity = CertValidity.getInstance(conf.getValidity()); this.ca = conf.isCa(); this.notBeforeMidnight = "midnight".equalsIgnoreCase(conf.getNotBeforeTime()); String specialBehavior = conf.getSpecialBehavior(); if (specialBehavior != null) { this.specialBehavior = SpecialX509CertprofileBehavior.getInstance(specialBehavior); } if (conf.isDuplicateKey() != null) { duplicateKeyPermitted = conf.isDuplicateKey().booleanValue(); } if (conf.isDuplicateSubject() != null) { duplicateSubjectPermitted = conf.isDuplicateSubject().booleanValue(); } if (conf.isSerialNumberInReq() != null) { serialNumberInReqPermitted = conf.isSerialNumberInReq().booleanValue(); } // KeyAlgorithms KeyAlgorithms keyAlgos = conf.getKeyAlgorithms(); if (keyAlgos != null) { this.keyAlgorithms = XmlX509CertprofileUtil.buildKeyAlgorithms(keyAlgos); } // parameters Parameters confParams = conf.getParameters(); if (confParams == null) { parameters = null; } else { Map<String, String> tMap = new HashMap<>(); for (NameValueType nv : confParams.getParameter()) { tMap.put(nv.getName(), nv.getValue()); } parameters = Collections.unmodifiableMap(tMap); } // Subject Subject subject = conf.getSubject(); if (subject != null) { this.backwardsSubject = subject.isDnBackwards(); this.incSerialNoIfSubjectExists = subject.isIncSerialNumber(); this.subjectDNControls = new HashSet<RDNControl>(); this.subjectDNOptions = new HashMap<>(); for (RdnType t : subject.getRdn()) { DirectoryStringType directoryStringEnum = XmlX509CertprofileUtil .convertDirectoryStringType(t.getDirectoryStringType()); ASN1ObjectIdentifier type = new ASN1ObjectIdentifier(t.getType().getValue()); RDNControl occ = new RDNControl(type, t.getMinOccurs(), t.getMaxOccurs(), directoryStringEnum); this.subjectDNControls.add(occ); List<Pattern> patterns = null; if (CollectionUtil.isNotEmpty(t.getRegex())) { patterns = new LinkedList<>(); for (String regex : t.getRegex()) { Pattern pattern = Pattern.compile(regex); patterns.add(pattern); } } SubjectDNOption option = new SubjectDNOption(t.getPrefix(), t.getSuffix(), patterns, t.getMinLen(), t.getMaxLen()); this.subjectDNOptions.put(type, option); } } // Extensions ExtensionsType extensionsType = conf.getExtensions(); // Extension controls this.extensionControls = XmlX509CertprofileUtil.buildExtensionControls(extensionsType); // BasicConstrains ASN1ObjectIdentifier type = Extension.basicConstraints; if (extensionControls.containsKey(type)) { BasicConstraints extConf = (BasicConstraints) getExtensionValue(type, extensionsType, BasicConstraints.class); if (extConf != null) { this.pathLen = extConf.getPathLen(); } } // AuthorityInfoAccess type = Extension.authorityInfoAccess; if (extensionControls.containsKey(type)) { AuthorityInfoAccess extConf = (AuthorityInfoAccess) getExtensionValue(type, extensionsType, AuthorityInfoAccess.class); if (extConf != null) { Boolean b = extConf.isIncludeCaIssuers(); boolean includesCaIssuers = b == null ? true : b.booleanValue(); b = extConf.isIncludeOcsp(); boolean includesOcsp = b == null ? true : b.booleanValue(); this.aIAControl = new AuthorityInfoAccessControl(includesCaIssuers, includesOcsp); } } // Extension KeyUsage type = Extension.keyUsage; if (extensionControls.containsKey(type)) { KeyUsage extConf = (KeyUsage) getExtensionValue(type, extensionsType, KeyUsage.class); if (extConf != null) { this.keyusages = XmlX509CertprofileUtil.buildKeyUsageOptions(extConf); } } // ExtendedKeyUsage type = Extension.extendedKeyUsage; if (extensionControls.containsKey(type)) { ExtendedKeyUsage extConf = (ExtendedKeyUsage) getExtensionValue(type, extensionsType, ExtendedKeyUsage.class); if (extConf != null) { this.extendedKeyusages = XmlX509CertprofileUtil.buildExtKeyUsageOptions(extConf); } } // AuthorityKeyIdentifier type = Extension.authorityKeyIdentifier; if (extensionControls.containsKey(type)) { AuthorityKeyIdentifier extConf = (AuthorityKeyIdentifier) getExtensionValue(type, extensionsType, AuthorityKeyIdentifier.class); if (extConf != null) { this.includeIssuerAndSerialInAKI = extConf.isIncludeIssuerAndSerial(); } } // Certificate Policies type = Extension.certificatePolicies; if (extensionControls.containsKey(type)) { CertificatePolicies extConf = (CertificatePolicies) getExtensionValue(type, extensionsType, CertificatePolicies.class); if (extConf != null) { List<CertificatePolicyInformation> policyInfos = XmlX509CertprofileUtil .buildCertificatePolicies(extConf); org.bouncycastle.asn1.x509.CertificatePolicies value = X509CertUtil .createCertificatePolicies(policyInfos); this.certificatePolicies = new ExtensionValue(extensionControls.get(type).isCritical(), value); } } // Policy Mappings type = Extension.policyMappings; if (extensionControls.containsKey(type)) { PolicyMappings extConf = (PolicyMappings) getExtensionValue(type, extensionsType, PolicyMappings.class); if (extConf != null) { org.bouncycastle.asn1.x509.PolicyMappings value = XmlX509CertprofileUtil .buildPolicyMappings(extConf); this.policyMappings = new ExtensionValue(extensionControls.get(type).isCritical(), value); } } // Name Constrains type = Extension.nameConstraints; if (extensionControls.containsKey(type)) { NameConstraints extConf = (NameConstraints) getExtensionValue(type, extensionsType, NameConstraints.class); if (extConf != null) { org.bouncycastle.asn1.x509.NameConstraints value = XmlX509CertprofileUtil .buildNameConstrains(extConf); this.nameConstraints = new ExtensionValue(extensionControls.get(type).isCritical(), value); } } // Policy Constraints type = Extension.policyConstraints; if (extensionControls.containsKey(type)) { PolicyConstraints extConf = (PolicyConstraints) getExtensionValue(type, extensionsType, PolicyConstraints.class); if (extConf != null) { ASN1Sequence value = XmlX509CertprofileUtil.buildPolicyConstrains(extConf); this.policyConstraints = new ExtensionValue(extensionControls.get(type).isCritical(), value); } } // Inhibit anyPolicy type = Extension.inhibitAnyPolicy; if (extensionControls.containsKey(type)) { InhibitAnyPolicy extConf = (InhibitAnyPolicy) getExtensionValue(type, extensionsType, InhibitAnyPolicy.class); if (extConf != null) { int skipCerts = extConf.getSkipCerts(); if (skipCerts < 0) { throw new CertprofileException( "negative inhibitAnyPolicy.skipCerts is not allowed: " + skipCerts); } ASN1Integer value = new ASN1Integer(BigInteger.valueOf(skipCerts)); this.inhibitAnyPolicy = new ExtensionValue(extensionControls.get(type).isCritical(), value); } } // admission type = ObjectIdentifiers.id_extension_admission; if (extensionControls.containsKey(type)) { Admission extConf = (Admission) getExtensionValue(type, extensionsType, Admission.class); if (extConf != null) { List<ASN1ObjectIdentifier> professionOIDs; List<String> professionItems; List<String> items = type == null ? null : extConf.getProfessionItem(); professionItems = CollectionUtil.unmodifiableList(items, true, true); List<OidWithDescType> oidWithDescs = (type == null) ? null : extConf.getProfessionOid(); professionOIDs = XmlX509CertprofileUtil.toOIDList(oidWithDescs); this.admission = createAdmission(extensionControls.get(type).isCritical(), professionOIDs, professionItems, extConf.getRegistrationNumber(), extConf.getAddProfessionInfo()); } } // SubjectAltNameMode type = Extension.subjectAlternativeName; if (extensionControls.containsKey(type)) { SubjectAltName extConf = (SubjectAltName) getExtensionValue(type, extensionsType, SubjectAltName.class); if (extConf != null) { this.allowedSubjectAltNameModes = XmlX509CertprofileUtil.buildGeneralNameMode(extConf); } } // SubjectInfoAccess type = Extension.subjectInfoAccess; if (extensionControls.containsKey(type)) { SubjectInfoAccess extConf = (SubjectInfoAccess) getExtensionValue(type, extensionsType, SubjectInfoAccess.class); if (extConf != null) { List<Access> list = extConf.getAccess(); this.allowedSubjectInfoAccessModes = new HashMap<>(); for (Access entry : list) { this.allowedSubjectInfoAccessModes.put( new ASN1ObjectIdentifier(entry.getAccessMethod().getValue()), XmlX509CertprofileUtil.buildGeneralNameMode(entry.getAccessLocation())); } } } // constant extensions this.constantExtensions = XmlX509CertprofileUtil.buildConstantExtesions(extensionsType); }
From source file:org.xipki.ca.certprofile.XmlX509CertprofileUtil.java
License:Open Source License
public static ASN1Sequence buildPolicyConstrains(final PolicyConstraints type) throws CertprofileException { Integer requireExplicitPolicy = type.getRequireExplicitPolicy(); if (requireExplicitPolicy != null && requireExplicitPolicy < 0) { throw new CertprofileException( "negative requireExplicitPolicy is not allowed: " + requireExplicitPolicy); }//from w w w .ja va 2 s. c o m Integer inhibitPolicyMapping = type.getInhibitPolicyMapping(); if (inhibitPolicyMapping != null && inhibitPolicyMapping < 0) { throw new CertprofileException("negative inhibitPolicyMapping is not allowed: " + inhibitPolicyMapping); } if (requireExplicitPolicy == null && inhibitPolicyMapping == null) { return null; } final boolean explicit = false; ASN1EncodableVector vec = new ASN1EncodableVector(); if (requireExplicitPolicy != null) { vec.add(new DERTaggedObject(explicit, 0, new ASN1Integer(BigInteger.valueOf(requireExplicitPolicy)))); } if (inhibitPolicyMapping != null) { vec.add(new DERTaggedObject(explicit, 1, new ASN1Integer(BigInteger.valueOf(inhibitPolicyMapping)))); } return new DERSequence(vec); }
From source file:org.xipki.ca.client.impl.CmpRequestor.java
License:Open Source License
protected PKIMessage buildMessageWithXipkAction(final int action, final ASN1Encodable value) throws CmpRequestorException { PKIHeader header = buildPKIHeader(null); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(action)); if (value != null) { v.add(value);//from w w w .java 2 s . co m } InfoTypeAndValue itv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp, new DERSequence(v)); GenMsgContent genMsgContent = new GenMsgContent(itv); PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, genMsgContent); PKIMessage pkiMessage = new PKIMessage(header, body); return pkiMessage; }