Elliptic curve registry for ANSSI.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
Return a representing the contents of the BIT STRING. The final byte, if any,
may include pad bits. See .
A with its source as the BIT STRING content.
Return a representing the contents of the BIT STRING, where the content is
expected to be octet-aligned (this will be automatically checked during parsing).
A with its source as the BIT STRING content.
Return the number of pad bits, if any, in the final byte, if any, read from
.
This number is in the range zero to seven. That number of the least significant bits of the final byte, if
any, are not part of the contents and should be ignored. NOTE: Must be called AFTER the stream has been
fully processed. (Does not need to be called if was used instead of
.
The number of pad bits. In the range zero to seven.
Return the DER encoding of the object, null if the DER encoding can not be made.
@return a DER byte array, null otherwise.
Mutable class for building ASN.1 constructed objects such as SETs or SEQUENCEs.
GeneralizedTime ASN.1 type
a general purpose ASN.1 decoder - note: this class differs from the
others in that it returns null after it has read the last object in
the stream. If an ASN.1 Null is encountered a Der/BER Null object is
returned.
Create an ASN1InputStream based on the input byte array. The length of DER objects in
the stream is automatically limited to the length of the input array.
@param input array containing ASN.1 encoded data.
Create an ASN1InputStream where no DER object will be longer than limit.
@param input stream containing ASN.1 encoded data.
@param limit maximum size of a DER encoded object.
build an object given its tag and the number of bytes to construct it from.
A Null object.
Create a base ASN.1 object from a byte array.
The byte array to parse.
The base ASN.1 object represented by the byte array.
If there is a problem parsing the data, or parsing an object did not exhaust the available data.
Read a base ASN.1 object from a stream.
The stream to parse.
The base ASN.1 object represented by the byte array.
If there is a problem parsing the data.
Return an ObjectDescriptor from the passed in object.
@param obj an ASN1ObjectDescriptor or an object that can be converted into one.
@exception IllegalArgumentException if the object cannot be converted.
@return an ASN1ObjectDescriptor instance, or null.
Return an ObjectDescriptor from a tagged object.
@param taggedObject the tagged object holding the object we want.
@param declaredExplicit true if the object is meant to be explicitly tagged, false otherwise.
@exception IllegalArgumentException if the tagged object cannot be converted.
@return an ASN1ObjectDescriptor instance, or null.
return an Octet string from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
return an octet string from a tagged object.
@param taggedObject the tagged object holding the object we want.
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
@param string the octets making up the octet string.
Return the content of the OCTET STRING as a .
A represnting the OCTET STRING's content.
return an Asn1Sequence from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Return an ASN1 sequence from a tagged object. There is a special
case here, if an object appears to have been explicitly tagged on
reading but we were expecting it to be implicitly tagged in the
normal course of events it indicates that we lost the surrounding
sequence - so we need to add it back (this will happen if the tagged
object is a sequence that contains other sequences). If you are
dealing with implicitly tagged sequences you really should
be using this method.
@param taggedObject the tagged object.
@param declaredExplicit true if the object is meant to be explicitly tagged, false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
return the object at the sequence position indicated by index.
@param index the sequence number (starting at zero) of the object
@return the object at the sequence position indicated by index.
return an ASN1Set from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Return an ASN1 set from a tagged object. There is a special
case here, if an object appears to have been explicitly tagged on
reading but we were expecting it to be implicitly tagged in the
normal course of events it indicates that we lost the surrounding
set - so we need to add it back (this will happen if the tagged
object is a sequence that contains other sequences). If you are
dealing with implicitly tagged sets you really should
be using this method.
@param taggedObject the tagged object.
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
return the object at the set position indicated by index.
@param index the set number (starting at zero) of the object
@return the object at the set position indicated by index.
ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
a [n] where n is some number - these are assumed to follow the construction
rules (as with sequences).
@param explicitly true if the object is explicitly tagged.
@param tagNo the tag number for this object.
@param obj the tagged object.
return whether or not the object may be explicitly tagged.
Note: if the object has been read from an input stream, the only
time you can be sure if isExplicit is returning the true state of
affairs is if it returns false. An implicitly tagged object may appear
to be explicitly tagged, so you need to understand the context under
which the reading was done as well, see GetObject below.
return whatever was following the tag.
Note: tagged objects are generally context dependent if you're
trying to extract a tagged object you should be going via the
appropriate GetInstance method.
Needed for open types, until we have better type-guided parsing support. Use sparingly for other
purposes, and prefer {@link #getExplicitBaseTagged()}, {@link #getImplicitBaseTagged(int, int)} or
{@link #getBaseUniversal(boolean, int)} where possible. Before using, check for matching tag
{@link #getTagClass() class} and {@link #getTagNo() number}.
Needed for open types, until we have better type-guided parsing support. Use
sparingly for other purposes, and prefer {@link #getExplicitBaseTagged()} or
{@link #getBaseUniversal(boolean, int)} where possible. Before using, check
for matching tag {@link #getTagClass() class} and {@link #getTagNo() number}.
Needed for open types, until we have better type-guided parsing support.
Use sparingly for other purposes, and prefer or
where possible. Before using, check for matching tag
class and number.
UTCTime ASN.1 type
return a UTC Time from the passed in object.
@exception ArgumentException if the object cannot be converted.
Return an adjusted date in the range of 1950 - 2049.
iso.org.dod.internet.private.enterprise.legion-of-the-bouncy-castle
1.3.6.1.4.1.22554
pbe(1) algorithms
1.3.6.1.4.1.22554.1
SHA-1(1)
1.3.6.1.4.1.22554.1.1
SHA-2.SHA-256; 1.3.6.1.4.1.22554.1.2.1
SHA-2.SHA-384; 1.3.6.1.4.1.22554.1.2.2
SHA-2.SHA-512; 1.3.6.1.4.1.22554.1.2.3
SHA-2.SHA-224; 1.3.6.1.4.1.22554.1.2.4
PKCS-5(1)|PKCS-12(2)
SHA-1.PKCS5; 1.3.6.1.4.1.22554.1.1.1
SHA-1.PKCS12; 1.3.6.1.4.1.22554.1.1.2
SHA-256.PKCS12; 1.3.6.1.4.1.22554.1.2.1.1
SHA-256.PKCS12; 1.3.6.1.4.1.22554.1.2.1.2
AES(1) . (CBC-128(2)|CBC-192(22)|CBC-256(42))
1.3.6.1.4.1.22554.1.1.2.1.2
1.3.6.1.4.1.22554.1.1.2.1.22
1.3.6.1.4.1.22554.1.1.2.1.42
1.3.6.1.4.1.22554.1.1.2.2.2
1.3.6.1.4.1.22554.1.1.2.2.22
1.3.6.1.4.1.22554.1.1.2.2.42
signature(2) algorithms
Sphincs-256
XMSS
XMSS^MT
SPHINCS+
Picnic
key_exchange(3) algorithms
NewHope
X.509 extension(4) values
1.3.6.1.4.1.22554.4
KEM(4) algorithms
Classic McEliece
SABER
SIKE
Kyber
BIKE
HQC
Extension to tie an alternate certificate to the containing certificate.
LinkedCertificate := SEQUENCE {
digest DigestInfo, -- digest of PQC certificate
certLocation GeneralName, -- location of PQC certificate
certIssuer [0] Name OPTIONAL, -- issuer of PQC cert (if different from current certificate)
cACerts [1] GeneralNames OPTIONAL, -- CA certificates for PQC cert (one of more locations)
}
A parser for indefinite-length BIT STRINGs.
create an empty sequence
create a sequence containing one object
create a sequence containing two objects
create a sequence containing a vector of objects.
create an empty set
create a set containing one object
create a set containing a vector of objects.
BER TaggedObject - in ASN.1 notation this is any object preceded by
a [n] where n is some number - these are assumed to follow the construction
rules (as with sequences).
@param tagNo the tag number for this object.
@param obj the tagged object.
@param isExplicit true if an explicitly tagged object.
@param tagNo the tag number for this object.
@param obj the tagged object.
See https://www.bsi.bund.de/cae/servlet/contentblob/471398/publicationFile/30615/BSI-TR-03111_pdf.pdf
0.4.0.127.0.7.1
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963 OID: 0.4.0.127.0.7.1.1.5.1.1
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function SHA-1
OID: 0.4.0.127.0.7.1.1.5.1.1.1
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function SHA224
OID: 0.4.0.127.0.7.1.1.5.1.1.2
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function SHA256
OID: 0.4.0.127.0.7.1.1.5.1.1.3
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function SHA384
OID: 0.4.0.127.0.7.1.1.5.1.1.4
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function SHA512
OID: 0.4.0.127.0.7.1.1.5.1.1.5
ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
with hash function RIPEMD160
OID: 0.4.0.127.0.7.1.1.5.1.1.6
Key Derivation Function for Session Keys
CAKeyUpdAnnContent ::= SEQUENCE {
oldWithNew CmpCertificate, -- old pub signed with new priv
newWithOld CmpCertificate, -- new pub signed with old priv
newWithNew CmpCertificate -- new pub signed with new priv
}
@return a basic ASN.1 object representation.
CertAnnContent ::= CMPCertificate
CertConfirmContent ::= SEQUENCE OF CertStatus
@return a basic ASN.1 object representation.
CertifiedKeyPair ::= SEQUENCE {
certOrEncCert CertOrEncCert,
privateKey [0] EncryptedValue OPTIONAL,
-- see [CRMF] for comment on encoding
publicationInfo [1] PKIPublicationInfo OPTIONAL
}
@return a basic ASN.1 object representation.
CertOrEncCert ::= CHOICE {
certificate [0] CMPCertificate,
encryptedCert [1] EncryptedKey
}
@return a basic ASN.1 object representation.
CertRepMessage ::= SEQUENCE {
caPubs [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate
OPTIONAL,
response SEQUENCE OF CertResponse
}
@return a basic ASN.1 object representation.
GenMsg: {id-it 19}, < absent >
GenRep: {id-it 19}, CertReqTemplateContent | < absent >
CertReqTemplateValue ::= CertReqTemplateContent
CertReqTemplateContent ::= SEQUENCE {
certTemplate CertTemplate,
keySpec Controls OPTIONAL }
Controls ::= SEQUENCE SIZE (1..MAX) OF AttributeTypeAndValue
CertResponse ::= SEQUENCE {
certReqId INTEGER,
-- to match this response with corresponding request (a value
-- of -1 is to be used if certReqId is not specified in the
-- corresponding request)
status PKIStatusInfo,
certifiedKeyPair CertifiedKeyPair OPTIONAL,
rspInfo OCTET STRING OPTIONAL
-- analogous to the id-regInfo-utf8Pairs string defined
-- for regInfo in CertReqMsg [CRMF]
}
@return a basic ASN.1 object representation.
CertStatus ::= SEQUENCE {
certHash OCTET STRING,
certReqId INTEGER,
statusInfo PKIStatusInfo OPTIONAL,
hashAlg [0] AlgorithmIdentifier{DIGEST-ALGORITHM, {...}} OPTIONAL
}
@return a basic ASN.1 object representation.
Challenge ::= SEQUENCE {
owf AlgorithmIdentifier OPTIONAL,
-- MUST be present in the first Challenge; MAY be omitted in
-- any subsequent Challenge in POPODecKeyChallContent (if
-- omitted, then the owf used in the immediately preceding
-- Challenge is to be used).
witness OCTET STRING,
-- the result of applying the one-way function (owf) to a
-- randomly-generated INTEGER, A. [Note that a different
-- INTEGER MUST be used for each Challenge.]
challenge OCTET STRING
-- the encryption (under the public key for which the cert.
-- request is being made) of Rand, where Rand is specified as
-- Rand ::= SEQUENCE {
-- int INTEGER,
-- - the randomly-generated INTEGER A (above)
-- sender GeneralName
-- - the sender's name (as included in PKIHeader)
-- }
}
Challenge ::= SEQUENCE {
owf AlgorithmIdentifier OPTIONAL,
-- MUST be present in the first Challenge; MAY be omitted in
-- any subsequent Challenge in POPODecKeyChallContent (if
-- omitted, then the owf used in the immediately preceding
-- Challenge is to be used).
witness OCTET STRING,
-- the result of applying the one-way function (owf) to a
-- randomly-generated INTEGER, A. [Note that a different
-- INTEGER MUST be used for each Challenge.]
challenge OCTET STRING
-- the encryption (under the public key for which the cert.
-- request is being made) of Rand, where Rand is specified as
-- Rand ::= SEQUENCE {
-- int INTEGER,
-- - the randomly-generated INTEGER A (above)
-- sender GeneralName
-- - the sender's name (as included in PKIHeader)
-- }
}
@return a basic ASN.1 object representation.
Rand is the inner type
Note: the addition of other certificates is a BC extension. If you use this constructor they
will be added with an explicit tag value of type.
@param type the type of the certificate (used as a tag value).
@param otherCert the object representing the certificate
CMPCertificate ::= CHOICE {
x509v3PKCert Certificate
x509v2AttrCert [1] AttributeCertificate
}
Note: the addition of attribute certificates is a BC extension.
@return a basic ASN.1 object representation.
id-PasswordBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 13}
id-DHBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 30}
RFC 4120: it-id: PKIX.4 = 1.3.6.1.5.5.7.4
RFC 4120: 1.3.6.1.5.5.7.4.1
RFC 4120: 1.3.6.1.5.5.7.4.2
RFC 4120: 1.3.6.1.5.5.7.4.3
RFC 4120: 1.3.6.1.5.5.7.4.4
RFC 4120: 1.3.6.1.5.5.7.4.5
RFC 4120: 1.3.6.1.5.5.7.4.6
RFC 4120: 1.3.6.1.5.5.7.4.7
RFC 4120: 1.3.6.1.5.5.7.4.10
RFC 4120: 1.3.6.1.5.5.7.4.11
RFC 4120: 1.3.6.1.5.5.7.4.12
RFC 4120: 1.3.6.1.5.5.7.4.13
RFC 4120: 1.3.6.1.5.5.7.4.14
RFC 4120: 1.3.6.1.5.5.7.4.15
RFC 4120: 1.3.6.1.5.5.7.4.16
Update 16, RFC 4210
{id-it 17}
Update 16, RFC 4210
GenRep: {id-it 18}, RootCaKeyUpdateContent
Update 16, RFC 4210
{id-it 19}
Update 16, RFC 4210
GenMsg: {id-it 20}, RootCaCertValue
Update-16 to RFC 4210
id-it-certProfile OBJECT IDENTIFIER ::= {id-it 21}
RFC 4211: it-pkip: PKIX.5 = 1.3.6.1.5.5.7.5
RFC 4211: it-regCtrl: 1.3.6.1.5.5.7.5.1
RFC 4211: it-regInfo: 1.3.6.1.5.5.7.5.2
1.3.6.1.5.5.7.5.1.1
1.3.6.1.5.5.7.5.1.2
1.3.6.1.5.5.7.5.1.3
1.3.6.1.5.5.7.5.1.4
1.3.6.1.5.5.7.5.1.5
1.3.6.1.5.5.7.5.1.6
From RFC4210:
id-regCtrl-altCertTemplate OBJECT IDENTIFIER ::= {id-regCtrl 7}; 1.3.6.1.5.5.7.1.7
RFC 4211: it-regInfo-utf8Pairs: 1.3.6.1.5.5.7.5.2.1
RFC 4211: it-regInfo-certReq: 1.3.6.1.5.5.7.5.2.1
1.2.840.113549.1.9.16.1.21
id-ct OBJECT IDENTIFIER ::= { id-smime 1 } -- content types
id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21}
id-regCtrl-algId OBJECT IDENTIFIER ::= { iso(1)
identified-organization(3) dod(6) internet(1) security(5)
mechanisms(5) pkix(7) pkip(5) regCtrl(1) 11 }
id-regCtrl-rsaKeyLen OBJECT IDENTIFIER ::= { iso(1)
identified-organization(3) dod(6) internet(1) security(5)
mechanisms(5) pkix(7) pkip(5) regCtrl(1) 12 }
CrlAnnContent ::= SEQUENCE OF CertificateList
@return a basic ASN.1 object representation.
GenMsg: {id-it TBD1}, SEQUENCE SIZE (1..MAX) OF CRLStatus
GenRep: {id-it TBD2}, SEQUENCE SIZE (1..MAX) OF
CertificateList | < absent >
CRLSource ::= CHOICE {
dpn [0] DistributionPointName,
issuer [1] GeneralNames }
CRLStatus ::= SEQUENCE {
source CRLSource,
thisUpdate Time OPTIONAL }
DHBMParameter ::= SEQUENCE {
owf AlgorithmIdentifier,
-- AlgId for a One-Way Function (SHA-1 recommended)
mac AlgorithmIdentifier
-- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
} -- or HMAC [RFC2104, RFC2202])
ErrorMsgContent ::= SEQUENCE {
pKIStatusInfo PKIStatusInfo,
errorCode INTEGER OPTIONAL,
-- implementation-specific error codes
errorDetails PKIFreeText OPTIONAL
-- implementation-specific error details
}
ErrorMsgContent ::= SEQUENCE {
pKIStatusInfo PKIStatusInfo,
errorCode INTEGER OPTIONAL,
-- implementation-specific error codes
errorDetails PKIFreeText OPTIONAL
-- implementation-specific error details
}
@return a basic ASN.1 object representation.
GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
@return a basic ASN.1 object representation.
GenRepContent ::= SEQUENCE OF InfoTypeAndValue
@return a basic ASN.1 object representation.
Example InfoTypeAndValue contents include, but are not limited
to, the following (un-comment in this ASN.1 module and use as
appropriate for a given environment):
id-it-caProtEncCert OBJECT IDENTIFIER ::= {id-it 1}
CAProtEncCertValue ::= CMPCertificate
id-it-signKeyPairTypes OBJECT IDENTIFIER ::= {id-it 2}
SignKeyPairTypesValue ::= SEQUENCE OF AlgorithmIdentifier
id-it-encKeyPairTypes OBJECT IDENTIFIER ::= {id-it 3}
EncKeyPairTypesValue ::= SEQUENCE OF AlgorithmIdentifier
id-it-preferredSymmAlg OBJECT IDENTIFIER ::= {id-it 4}
PreferredSymmAlgValue ::= AlgorithmIdentifier
id-it-caKeyUpdateInfo OBJECT IDENTIFIER ::= {id-it 5}
CAKeyUpdateInfoValue ::= CAKeyUpdAnnContent
id-it-currentCRL OBJECT IDENTIFIER ::= {id-it 6}
CurrentCRLValue ::= CertificateList
id-it-unsupportedOIDs OBJECT IDENTIFIER ::= {id-it 7}
UnsupportedOIDsValue ::= SEQUENCE OF OBJECT IDENTIFIER
id-it-keyPairParamReq OBJECT IDENTIFIER ::= {id-it 10}
KeyPairParamReqValue ::= OBJECT IDENTIFIER
id-it-keyPairParamRep OBJECT IDENTIFIER ::= {id-it 11}
KeyPairParamRepValue ::= AlgorithmIdentifer
id-it-revPassphrase OBJECT IDENTIFIER ::= {id-it 12}
RevPassphraseValue ::= EncryptedValue
id-it-implicitConfirm OBJECT IDENTIFIER ::= {id-it 13}
ImplicitConfirmValue ::= NULL
id-it-confirmWaitTime OBJECT IDENTIFIER ::= {id-it 14}
ConfirmWaitTimeValue ::= GeneralizedTime
id-it-origPKIMessage OBJECT IDENTIFIER ::= {id-it 15}
OrigPKIMessageValue ::= PKIMessages
id-it-suppLangTags OBJECT IDENTIFIER ::= {id-it 16}
SuppLangTagsValue ::= SEQUENCE OF UTF8String
where
id-pkix OBJECT IDENTIFIER ::= {
iso(1) identified-organization(3)
dod(6) internet(1) security(5) mechanisms(5) pkix(7)}
and
id-it OBJECT IDENTIFIER ::= {id-pkix 4}
InfoTypeAndValue ::= SEQUENCE {
infoType OBJECT IDENTIFIER,
infoValue ANY DEFINED BY infoType OPTIONAL
}
@return a basic ASN.1 object representation.
KeyRecRepContent ::= SEQUENCE {
status PKIStatusInfo,
newSigCert [0] CMPCertificate OPTIONAL,
caCerts [1] SEQUENCE SIZE (1..MAX) OF
CMPCertificate OPTIONAL,
keyPairHist [2] SEQUENCE SIZE (1..MAX) OF
CertifiedKeyPair OPTIONAL
}
@return a basic ASN.1 object representation.
NestedMessageContent ::= PKIMessages
OOBCert ::= CMPCertificate
OOBCertHash ::= SEQUENCE {
hashAlg [0] AlgorithmIdentifier OPTIONAL,
certId [1] CertId OPTIONAL,
hashVal BIT STRING
-- hashVal is calculated over the DER encoding of the
-- self-signed certificate with the identifier certID.
}
OobCertHash ::= SEQUENCE {
hashAlg [0] AlgorithmIdentifier OPTIONAL,
certId [1] CertId OPTIONAL,
hashVal BIT STRING
-- hashVal is calculated over the Der encoding of the
-- self-signed certificate with the identifier certID.
}
@return a basic ASN.1 object representation.
PBMParameter ::= SEQUENCE {
salt OCTET STRING,
-- note: implementations MAY wish to limit acceptable sizes
-- of this string to values appropriate for their environment
-- in order to reduce the risk of denial-of-service attacks
owf AlgorithmIdentifier,
-- AlgId for a One-Way Function (SHA-1 recommended)
iterationCount INTEGER,
-- number of times the OWF is applied
-- note: implementations MAY wish to limit acceptable sizes
-- of this integer to values appropriate for their environment
-- in order to reduce the risk of denial-of-service attacks
mac AlgorithmIdentifier
-- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
} -- or HMAC [RFC2104, RFC2202])
PbmParameter ::= SEQUENCE {
salt OCTET STRING,
-- note: implementations MAY wish to limit acceptable sizes
-- of this string to values appropriate for their environment
-- in order to reduce the risk of denial-of-service attacks
owf AlgorithmIdentifier,
-- AlgId for a One-Way Function (SHA-1 recommended)
iterationCount INTEGER,
-- number of times the OWF is applied
-- note: implementations MAY wish to limit acceptable sizes
-- of this integer to values appropriate for their environment
-- in order to reduce the risk of denial-of-service attacks
mac AlgorithmIdentifier
-- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
} -- or HMAC [RFC2104, RFC2202])
@return a basic ASN.1 object representation.
PKIBody ::= CHOICE { -- message-specific body elements
ir [0] CertReqMessages, --Initialization Request
ip [1] CertRepMessage, --Initialization Response
cr [2] CertReqMessages, --Certification Request
cp [3] CertRepMessage, --Certification Response
p10cr [4] CertificationRequest, --imported from [PKCS10]
popdecc [5] POPODecKeyChallContent, --pop Challenge
popdecr [6] POPODecKeyRespContent, --pop Response
kur [7] CertReqMessages, --Key Update Request
kup [8] CertRepMessage, --Key Update Response
krr [9] CertReqMessages, --Key Recovery Request
krp [10] KeyRecRepContent, --Key Recovery Response
rr [11] RevReqContent, --Revocation Request
rp [12] RevRepContent, --Revocation Response
ccr [13] CertReqMessages, --Cross-Cert. Request
ccp [14] CertRepMessage, --Cross-Cert. Response
ckuann [15] CAKeyUpdAnnContent, --CA Key Update Ann.
cann [16] CertAnnContent, --Certificate Ann.
rann [17] RevAnnContent, --Revocation Ann.
crlann [18] CRLAnnContent, --CRL Announcement
pkiconf [19] PKIConfirmContent, --Confirmation
nested [20] NestedMessageContent, --Nested Message
genm [21] GenMsgContent, --General Message
genp [22] GenRepContent, --General Response
error [23] ErrorMsgContent, --Error Message
certConf [24] CertConfirmContent, --Certificate confirm
pollReq [25] PollReqContent, --Polling request
pollRep [26] PollRepContent --Polling response
}
Creates a new PkiBody.
@param type one of the TYPE_* constants
@param content message content
PkiBody ::= CHOICE { -- message-specific body elements
ir [0] CertReqMessages, --Initialization Request
ip [1] CertRepMessage, --Initialization Response
cr [2] CertReqMessages, --Certification Request
cp [3] CertRepMessage, --Certification Response
p10cr [4] CertificationRequest, --imported from [PKCS10]
popdecc [5] POPODecKeyChallContent, --pop Challenge
popdecr [6] POPODecKeyRespContent, --pop Response
kur [7] CertReqMessages, --Key Update Request
kup [8] CertRepMessage, --Key Update Response
krr [9] CertReqMessages, --Key Recovery Request
krp [10] KeyRecRepContent, --Key Recovery Response
rr [11] RevReqContent, --Revocation Request
rp [12] RevRepContent, --Revocation Response
ccr [13] CertReqMessages, --Cross-Cert. Request
ccp [14] CertRepMessage, --Cross-Cert. Response
ckuann [15] CAKeyUpdAnnContent, --CA Key Update Ann.
cann [16] CertAnnContent, --Certificate Ann.
rann [17] RevAnnContent, --Revocation Ann.
crlann [18] CRLAnnContent, --CRL Announcement
pkiconf [19] PKIConfirmContent, --Confirmation
nested [20] NestedMessageContent, --Nested Message
genm [21] GenMsgContent, --General Message
genp [22] GenRepContent, --General Response
error [23] ErrorMsgContent, --Error Message
certConf [24] CertConfirmContent, --Certificate confirm
pollReq [25] PollReqContent, --Polling request
pollRep [26] PollRepContent --Polling response
}
@return a basic ASN.1 object representation.
PKIConfirmContent ::= NULL
PkiConfirmContent ::= NULL
@return a basic ASN.1 object representation.
PKIFailureInfo ::= BIT STRING {
badAlg (0),
-- unrecognized or unsupported Algorithm Identifier
badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
badRequest (2),
-- transaction not permitted or supported
badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
badCertId (4), -- no certificate could be found matching the provided criteria
badDataFormat (5),
-- the data submitted has the wrong format
wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
incorrectData (7), -- the requester's data is incorrect (for notary services)
missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
badPOP (9) -- the proof-of-possession failed
certRevoked (10),
certConfirmed (11),
wrongIntegrity (12),
badRecipientNonce (13),
timeNotAvailable (14),
-- the TSA's time source is not available
unacceptedPolicy (15),
-- the requested TSA policy is not supported by the TSA
unacceptedExtension (16),
-- the requested extension is not supported by the TSA
addInfoNotAvailable (17)
-- the additional information requested could not be understood
-- or is not available
badSenderNonce (18),
badCertTemplate (19),
signerNotTrusted (20),
transactionIdInUse (21),
unsupportedVersion (22),
notAuthorized (23),
systemUnavail (24),
systemFailure (25),
-- the request cannot be handled due to system failure
duplicateCertReq (26)
Basic constructor.
Return the UTF8STRING at index.
@param index index of the string of interest
@return the string at index.
PkiFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
Value for a "null" recipient or sender.
PkiHeader ::= SEQUENCE {
pvno INTEGER { cmp1999(1), cmp2000(2) },
sender GeneralName,
-- identifies the sender
recipient GeneralName,
-- identifies the intended recipient
messageTime [0] GeneralizedTime OPTIONAL,
-- time of production of this message (used when sender
-- believes that the transport will be "suitable"; i.e.,
-- that the time will still be meaningful upon receipt)
protectionAlg [1] AlgorithmIdentifier OPTIONAL,
-- algorithm used for calculation of protection bits
senderKID [2] KeyIdentifier OPTIONAL,
recipKID [3] KeyIdentifier OPTIONAL,
-- to identify specific keys used for protection
transactionID [4] OCTET STRING OPTIONAL,
-- identifies the transaction; i.e., this will be the same in
-- corresponding request, response, certConf, and PKIConf
-- messages
senderNonce [5] OCTET STRING OPTIONAL,
recipNonce [6] OCTET STRING OPTIONAL,
-- nonces used to provide replay protection, senderNonce
-- is inserted by the creator of this message; recipNonce
-- is a nonce previously inserted in a related message by
-- the intended recipient of this message
freeText [7] PKIFreeText OPTIONAL,
-- this may be used to indicate context-specific instructions
-- (this field is intended for human consumption)
generalInfo [8] SEQUENCE SIZE (1..MAX) OF
InfoTypeAndValue OPTIONAL
-- this may be used to convey context-specific information
-- (this field not primarily intended for human consumption)
}
@return a basic ASN.1 object representation.
PKIHeader ::= SEQUENCE {
pvno INTEGER { cmp1999(1), cmp2000(2) },
sender GeneralName,
-- identifies the sender
recipient GeneralName,
-- identifies the intended recipient
messageTime [0] GeneralizedTime OPTIONAL,
-- time of production of this message (used when sender
-- believes that the transport will be "suitable"; i.e.,
-- that the time will still be meaningful upon receipt)
protectionAlg [1] AlgorithmIdentifier OPTIONAL,
-- algorithm used for calculation of protection bits
senderKID [2] KeyIdentifier OPTIONAL,
recipKID [3] KeyIdentifier OPTIONAL,
-- to identify specific keys used for protection
transactionID [4] OCTET STRING OPTIONAL,
-- identifies the transaction; i.e., this will be the same in
-- corresponding request, response, certConf, and PKIConf
-- messages
senderNonce [5] OCTET STRING OPTIONAL,
recipNonce [6] OCTET STRING OPTIONAL,
-- nonces used to provide replay protection, senderNonce
-- is inserted by the creator of this message; recipNonce
-- is a nonce previously inserted in a related message by
-- the intended recipient of this message
freeText [7] PKIFreeText OPTIONAL,
-- this may be used to indicate context-specific instructions
-- (this field is intended for human consumption)
generalInfo [8] SEQUENCE SIZE (1..MAX) OF
InfoTypeAndValue OPTIONAL
-- this may be used to convey context-specific information
-- (this field not primarily intended for human consumption)
}
@return a basic ASN.1 object representation.
Creates a new PkiMessage.
@param header message header
@param body message body
@param protection message protection (may be null)
@param extraCerts extra certificates (may be null)
PkiMessage ::= SEQUENCE {
header PKIHeader,
body PKIBody,
protection [0] PKIProtection OPTIONAL,
extraCerts [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate
OPTIONAL
}
@return a basic ASN.1 object representation.
PkiMessages ::= SEQUENCE SIZE (1..MAX) OF PkiMessage
@return a basic ASN.1 object representation.
@param status
@param status
@param statusString
PkiStatusInfo ::= SEQUENCE {
status PKIStatus, (INTEGER)
statusString PkiFreeText OPTIONAL,
failInfo PkiFailureInfo OPTIONAL (BIT STRING)
}
PKIStatus:
granted (0), -- you got exactly what you asked for
grantedWithMods (1), -- you got something like what you asked for
rejection (2), -- you don't get it, more information elsewhere in the message
waiting (3), -- the request body part has not yet been processed, expect to hear more later
revocationWarning (4), -- this message contains a warning that a revocation is imminent
revocationNotification (5), -- notification that a revocation has occurred
keyUpdateWarning (6) -- update already done for the oldCertId specified in CertReqMsg
PkiFailureInfo:
badAlg (0), -- unrecognized or unsupported Algorithm Identifier
badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
badRequest (2), -- transaction not permitted or supported
badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
badCertId (4), -- no certificate could be found matching the provided criteria
badDataFormat (5), -- the data submitted has the wrong format
wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
incorrectData (7), -- the requester's data is incorrect (for notary services)
missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
badPOP (9) -- the proof-of-possession failed
PollRepContent ::= SEQUENCE OF SEQUENCE {
certReqId INTEGER,
checkAfter INTEGER, -- time in seconds
reason PKIFreeText OPTIONAL }
PollRepContent ::= SEQUENCE OF SEQUENCE {
certReqId INTEGER,
checkAfter INTEGER, -- time in seconds
reason PKIFreeText OPTIONAL
}
@return a basic ASN.1 object representation.
Create a pollReqContent for a single certReqId.
@param certReqId the certificate request ID.
Create a pollReqContent for a multiple certReqIds.
@param certReqIds the certificate request IDs.
Create a pollReqContent for a single certReqId.
@param certReqId the certificate request ID.
Create a pollReqContent for a multiple certReqIds.
@param certReqIds the certificate request IDs.
PollReqContent ::= SEQUENCE OF SEQUENCE {
certReqId INTEGER
}
@return a basic ASN.1 object representation.
PopoDecKeyChallContent ::= SEQUENCE OF Challenge
@return a basic ASN.1 object representation.
PopoDecKeyRespContent ::= SEQUENCE OF INTEGER
@return a basic ASN.1 object representation.
ProtectedPart ::= SEQUENCE {
header PKIHeader,
body PKIBody
}
@return a basic ASN.1 object representation.
RevAnnContent ::= SEQUENCE {
status PKIStatus,
certId CertId,
willBeRevokedAt GeneralizedTime,
badSinceDate GeneralizedTime,
crlDetails Extensions OPTIONAL
-- extra CRL details (e.g., crl number, reason, location, etc.)
}
@return a basic ASN.1 object representation.
RevDetails ::= SEQUENCE {
certDetails CertTemplate,
-- allows requester to specify as much as they can about
-- the cert. for which revocation is requested
-- (e.g., for cases in which serialNumber is not available)
crlEntryDetails Extensions OPTIONAL
-- requested crlEntryExtensions
}
RevDetails ::= SEQUENCE {
certDetails CertTemplate,
-- allows requester to specify as much as they can about
-- the cert. for which revocation is requested
-- (e.g., for cases in which serialNumber is not available)
crlEntryDetails Extensions OPTIONAL
-- requested crlEntryExtensions
}
@return a basic ASN.1 object representation.
RevRepContent ::= SEQUENCE {
status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
-- in same order as was sent in RevReqContent
revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId
OPTIONAL,
-- IDs for which revocation was requested
-- (same order as status)
crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
-- the resulting CRLs (there may be more than one)
}
RevRepContent ::= SEQUENCE {
status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
-- in same order as was sent in RevReqContent
revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
-- IDs for which revocation was requested
-- (same order as status)
crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
-- the resulting CRLs (there may be more than one)
}
@return a basic ASN.1 object representation.
RevReqContent ::= SEQUENCE OF RevDetails
@return a basic ASN.1 object representation.
GenMsg: {id-it 20}, RootCaCertValue | < absent >
GenRep: {id-it 18}, RootCaKeyUpdateContent | < absent >
RootCaCertValue ::= CMPCertificate
RootCaKeyUpdateValue ::= RootCaKeyUpdateContent
RootCaKeyUpdateContent ::= SEQUENCE {
newWithNew CMPCertificate,
newWithOld [0] CMPCertificate OPTIONAL,
oldWithNew [1] CMPCertificate OPTIONAL
}
return an Attribute object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
Attribute ::= SEQUENCE {
attrType OBJECT IDENTIFIER,
attrValues SET OF AttributeValue
}
Attributes ::=
SET SIZE(1..MAX) OF Attribute -- according to RFC 5652
@return
Return the first attribute matching the given OBJECT IDENTIFIER
Return all the attributes matching the OBJECT IDENTIFIER oid. The vector will be
empty if there are no attributes of the required type present.
@param oid type of attribute required.
@return a vector of all the attributes found of type oid.
Return a new table with the passed in attribute added.
@param attrType
@param attrValue
@return
return an AuthenticatedData object from a tagged object.
@param obj the tagged object holding the object we want.
@param isExplicit true if the object is meant to be explicitly
tagged false otherwise.
@throws ArgumentException if the object held by the
tagged object cannot be converted.
return an AuthenticatedData object from the given object.
@param obj the object we want converted.
@throws ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
AuthenticatedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
macAlgorithm MessageAuthenticationCodeAlgorithm,
digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
encapContentInfo EncapsulatedContentInfo,
authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
mac MessageAuthenticationCode,
unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }
AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
MessageAuthenticationCode ::= OCTET STRING
Produce an object suitable for an Asn1OutputStream.
AuthenticatedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
macAlgorithm MessageAuthenticationCodeAlgorithm,
digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
encapContentInfo EncapsulatedContentInfo,
authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
mac MessageAuthenticationCode,
unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }
AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
MessageAuthenticationCode ::= OCTET STRING
return an AuthEnvelopedData object from a tagged object.
@param obj the tagged object holding the object we want.
@param isExplicit true if the object is meant to be explicitly
tagged false otherwise.
@throws ArgumentException if the object held by the
tagged object cannot be converted.
return an AuthEnvelopedData object from the given object.
@param obj the object we want converted.
@throws ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
AuthEnvelopedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
authEncryptedContentInfo EncryptedContentInfo,
authAttrs [1] IMPLICIT AuthAttributes OPTIONAL,
mac MessageAuthenticationCode,
unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
AuthEnvelopedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
authEncryptedContentInfo EncryptedContentInfo,
authAttrs [1] IMPLICIT AuthAttributes OPTIONAL,
mac MessageAuthenticationCode,
unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL }
The other Revocation Info arc
id-ri OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
dod(6) internet(1) security(5) mechanisms(5) pkix(7) ri(16) }
RFC 3274 - CMS Compressed Data.
CompressedData ::= Sequence {
version CMSVersion,
compressionAlgorithm CompressionAlgorithmIdentifier,
encapContentInfo EncapsulatedContentInfo
}
return a CompressedData object from a tagged object.
@param ato the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a CompressedData object from the given object.
@param _obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
RFC 3274 - CMS Compressed Data.
CompressedData ::= SEQUENCE {
version CMSVersion,
compressionAlgorithm CompressionAlgorithmIdentifier,
encapContentInfo EncapsulatedContentInfo
}
Produce an object suitable for an Asn1OutputStream.
ContentInfo ::= Sequence {
contentType ContentType,
content
[0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
ContentInfo ::= SEQUENCE {
contentType ContentType,
content
[0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
return an AuthEnvelopedData object from a tagged object.
@param obj the tagged object holding the object we want.
@param isExplicit true if the object is meant to be explicitly
tagged false otherwise.
@throws ArgumentException if the object held by the
tagged object cannot be converted.
return an AuthEnvelopedData object from the given object.
@param obj the object we want converted.
@throws ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
MQVuserKeyingMaterial ::= SEQUENCE {
ephemeralPublicKey OriginatorPublicKey,
addedukm [0] EXPLICIT UserKeyingMaterial OPTIONAL }
return an EncryptedContentInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
EncryptedContentInfo ::= Sequence {
contentType ContentType,
contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
}
EncryptedContentInfo ::= SEQUENCE {
contentType ContentType,
contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
}
EncryptedData ::= SEQUENCE {
version CMSVersion,
encryptedContentInfo EncryptedContentInfo,
unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
@return a basic ASN.1 object representation.
return an EnvelopedData object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return an EnvelopedData object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
EnvelopedData ::= Sequence {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
encryptedContentInfo EncryptedContentInfo,
unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
}
Produce an object suitable for an Asn1OutputStream.
EnvelopedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
recipientInfos RecipientInfos,
encryptedContentInfo EncryptedContentInfo,
unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
}
return a KekIdentifier object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a KekIdentifier object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
KekIdentifier ::= Sequence {
keyIdentifier OCTET STRING,
date GeneralizedTime OPTIONAL,
other OtherKeyAttribute OPTIONAL
}
return a KekRecipientInfo object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a KekRecipientInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
KekRecipientInfo ::= Sequence {
version CMSVersion, -- always set to 4
kekID KekIdentifier,
keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
encryptedKey EncryptedKey
}
return an KeyAgreeRecipientIdentifier object from a tagged object.
@param obj the tagged object holding the object we want.
@param isExplicit true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return an KeyAgreeRecipientIdentifier object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
KeyAgreeRecipientIdentifier ::= CHOICE {
issuerAndSerialNumber IssuerAndSerialNumber,
rKeyId [0] IMPLICIT RecipientKeyIdentifier
}
return a KeyAgreeRecipientInfo object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a KeyAgreeRecipientInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
* Produce an object suitable for an Asn1OutputStream.
*
* KeyAgreeRecipientInfo ::= Sequence {
* version CMSVersion, -- always set to 3
* originator [0] EXPLICIT OriginatorIdentifierOrKey,
* ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* recipientEncryptedKeys RecipientEncryptedKeys
* }
*
* UserKeyingMaterial ::= OCTET STRING
*
return a KeyTransRecipientInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
KeyTransRecipientInfo ::= Sequence {
version CMSVersion, -- always set to 0 or 2
rid RecipientIdentifier,
keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
encryptedKey EncryptedKey
}
MetaData ::= SEQUENCE {
hashProtected BOOLEAN,
fileName UTF8String OPTIONAL,
mediaType IA5String OPTIONAL,
otherMetaData Attributes OPTIONAL
}
@return
return an OriginatorIdentifierOrKey object from a tagged object.
@param o the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return an OriginatorIdentifierOrKey object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
OriginatorIdentifierOrKey ::= CHOICE {
issuerAndSerialNumber IssuerAndSerialNumber,
subjectKeyIdentifier [0] SubjectKeyIdentifier,
originatorKey [1] OriginatorPublicKey
}
SubjectKeyIdentifier ::= OCTET STRING
return an OriginatorInfo object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return an OriginatorInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
OriginatorInfo ::= Sequence {
certs [0] IMPLICIT CertificateSet OPTIONAL,
crls [1] IMPLICIT CertificateRevocationLists OPTIONAL
}
return an OriginatorPublicKey object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return an OriginatorPublicKey object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
OriginatorPublicKey ::= Sequence {
algorithm AlgorithmIdentifier,
publicKey BIT STRING
}
return an OtherKeyAttribute object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
OtherKeyAttribute ::= Sequence {
keyAttrId OBJECT IDENTIFIER,
keyAttr ANY DEFINED BY keyAttrId OPTIONAL
}
return a OtherRecipientInfo object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a OtherRecipientInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
OtherRecipientInfo ::= Sequence {
oriType OBJECT IDENTIFIER,
oriValue ANY DEFINED BY oriType }
return a OtherRevocationInfoFormat object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicit true if the object is meant to be explicitly
tagged false otherwise.
@exception IllegalArgumentException if the object held by the
tagged object cannot be converted.
return a OtherRevocationInfoFormat object from the given object.
@param obj the object we want converted.
@exception IllegalArgumentException if the object cannot be converted.
Produce an object suitable for an ASN1OutputStream.
OtherRevocationInfoFormat ::= SEQUENCE {
otherRevInfoFormat OBJECT IDENTIFIER,
otherRevInfo ANY DEFINED BY otherRevInfoFormat }
return a PasswordRecipientInfo object from a tagged object.
@param obj the tagged object holding the object we want.
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a PasswordRecipientInfo object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
PasswordRecipientInfo ::= Sequence {
version CMSVersion, -- Always set to 0
keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
OPTIONAL,
keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
encryptedKey EncryptedKey }
return an RecipientEncryptedKey object from a tagged object.
@param obj the tagged object holding the object we want.
@param isExplicit true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a RecipientEncryptedKey object from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
RecipientEncryptedKey ::= SEQUENCE {
rid KeyAgreeRecipientIdentifier,
encryptedKey EncryptedKey
}
return a RecipientIdentifier object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
RecipientIdentifier ::= CHOICE {
issuerAndSerialNumber IssuerAndSerialNumber,
subjectKeyIdentifier [0] SubjectKeyIdentifier
}
SubjectKeyIdentifier ::= OCTET STRING
Produce an object suitable for an Asn1OutputStream.
RecipientInfo ::= CHOICE {
ktri KeyTransRecipientInfo,
kari [1] KeyAgreeRecipientInfo,
kekri [2] KekRecipientInfo,
pwri [3] PasswordRecipientInfo,
ori [4] OtherRecipientInfo }
return a RecipientKeyIdentifier object from a tagged object.
@param _ato the tagged object holding the object we want.
@param _explicit true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the object held by the
tagged object cannot be converted.
return a RecipientKeyIdentifier object from the given object.
@param _obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
RecipientKeyIdentifier ::= Sequence {
subjectKeyIdentifier SubjectKeyIdentifier,
date GeneralizedTime OPTIONAL,
other OtherKeyAttribute OPTIONAL
}
SubjectKeyIdentifier ::= OCTET STRING
ScvpReqRes ::= SEQUENCE {
request [0] EXPLICIT ContentInfo OPTIONAL,
response ContentInfo }
@return the ASN.1 primitive representation.
a signed data object.
Produce an object suitable for an Asn1OutputStream.
SignedData ::= Sequence {
version CMSVersion,
digestAlgorithms DigestAlgorithmIdentifiers,
encapContentInfo EncapsulatedContentInfo,
certificates [0] IMPLICIT CertificateSet OPTIONAL,
crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
signerInfos SignerInfos
}
SignedData ::= SEQUENCE {
version CMSVersion,
digestAlgorithms DigestAlgorithmIdentifiers,
encapContentInfo EncapsulatedContentInfo,
certificates [0] IMPLICIT CertificateSet OPTIONAL,
crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
signerInfos SignerInfos
}
return a SignerIdentifier object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
SignerIdentifier ::= CHOICE {
issuerAndSerialNumber IssuerAndSerialNumber,
subjectKeyIdentifier [0] SubjectKeyIdentifier
}
SubjectKeyIdentifier ::= OCTET STRING
Produce an object suitable for an Asn1OutputStream.
SignerInfo ::= Sequence {
version Version,
SignerIdentifier sid,
digestAlgorithm DigestAlgorithmIdentifier,
authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
encryptedDigest EncryptedDigest,
unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
}
EncryptedDigest ::= OCTET STRING
DigestAlgorithmIdentifier ::= AlgorithmIdentifier
DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
creates a time object from a given date - if the date is between 1950
and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
is used.
Produce an object suitable for an Asn1OutputStream.
Time ::= CHOICE {
utcTime UTCTime,
generalTime GeneralizedTime }
TimeStampAndCRL ::= SEQUENCE {
timeStamp TimeStampToken, -- according to RFC 3161
crl CertificateList OPTIONAL -- according to RFC 5280
}
@return
TimeStampedData ::= SEQUENCE {
version INTEGER { v1(1) },
dataUri IA5String OPTIONAL,
metaData MetaData OPTIONAL,
content OCTET STRING OPTIONAL,
temporalEvidence Evidence
}
@return
TimeStampTokenEvidence ::=
SEQUENCE SIZE(1..MAX) OF TimeStampAndCrl
@return
AttributeTypeAndValue ::= SEQUENCE {
type OBJECT IDENTIFIER,
value ANY DEFINED BY type }
@return a basic ASN.1 object representation.
CertId ::= SEQUENCE {
issuer GeneralName,
serialNumber INTEGER }
@return a basic ASN.1 object representation.
CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg
@return a basic ASN.1 object representation.
Creates a new CertReqMsg.
@param certReq CertRequest
@param popo may be null
@param regInfo may be null
CertReqMsg ::= SEQUENCE {
certReq CertRequest,
pop ProofOfPossession OPTIONAL,
-- content depends upon key type
regInfo SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL }
@return a basic ASN.1 object representation.
CertRequest ::= SEQUENCE {
certReqId INTEGER, -- ID for matching request and reply
certTemplate CertTemplate, -- Selected fields of cert to be issued
controls Controls OPTIONAL } -- Attributes affecting issuance
@return a basic ASN.1 object representation.
CertTemplate ::= SEQUENCE {
version [0] Version OPTIONAL,
serialNumber [1] INTEGER OPTIONAL,
signingAlg [2] AlgorithmIdentifier OPTIONAL,
issuer [3] Name OPTIONAL,
validity [4] OptionalValidity OPTIONAL,
subject [5] Name OPTIONAL,
publicKey [6] SubjectPublicKeyInfo OPTIONAL,
issuerUID [7] UniqueIdentifier OPTIONAL,
subjectUID [8] UniqueIdentifier OPTIONAL,
extensions [9] Extensions OPTIONAL }
@return a basic ASN.1 object representation.
Sets the X.509 version. Note: for X509v3, use 2 here.
Sets the issuer unique ID (deprecated in X.509v3)
Sets the subject unique ID (deprecated in X.509v3)
CertTemplate ::= SEQUENCE {
version [0] Version OPTIONAL,
serialNumber [1] INTEGER OPTIONAL,
signingAlg [2] AlgorithmIdentifier OPTIONAL,
issuer [3] Name OPTIONAL,
validity [4] OptionalValidity OPTIONAL,
subject [5] Name OPTIONAL,
publicKey [6] SubjectPublicKeyInfo OPTIONAL,
issuerUID [7] UniqueIdentifier OPTIONAL,
subjectUID [8] UniqueIdentifier OPTIONAL,
extensions [9] Extensions OPTIONAL }
@return a basic ASN.1 object representation.
Controls ::= SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue
@return a basic ASN.1 object representation.
EncKeyWithID ::= SEQUENCE {
privateKey PrivateKeyInfo,
identifier CHOICE {
string UTF8String,
generalName GeneralName
} OPTIONAL
}
@return
EncryptedKey ::= CHOICE {
encryptedValue EncryptedValue, -- deprecated
envelopedData [0] EnvelopedData }
-- The encrypted private key MUST be placed in the envelopedData
-- encryptedContentInfo encryptedContent OCTET STRING.
(IMPLICIT TAGS)
EncryptedValue ::= SEQUENCE {
intendedAlg [0] AlgorithmIdentifier OPTIONAL,
-- the intended algorithm for which the value will be used
symmAlg [1] AlgorithmIdentifier OPTIONAL,
-- the symmetric algorithm used to encrypt the value
encSymmKey [2] BIT STRING OPTIONAL,
-- the (encrypted) symmetric key used to encrypt the value
keyAlg [3] AlgorithmIdentifier OPTIONAL,
-- algorithm used to encrypt the symmetric key
valueHint [4] OCTET STRING OPTIONAL,
-- a brief description or identifier of the encValue content
-- (may be meaningful only to the sending entity, and used only
-- if EncryptedValue might be re-examined by the sending entity
-- in the future)
encValue BIT STRING }
-- the encrypted value itself
@return a basic ASN.1 object representation.
OptionalValidity ::= SEQUENCE {
notBefore [0] Time OPTIONAL,
notAfter [1] Time OPTIONAL } --at least one MUST be present
@return a basic ASN.1 object representation.
PkiArchiveOptions ::= CHOICE {
encryptedPrivKey [0] EncryptedKey,
-- the actual value of the private key
keyGenParameters [1] KeyGenParameters,
-- parameters which allow the private key to be re-generated
archiveRemGenPrivKey [2] BOOLEAN }
-- set to TRUE if sender wishes receiver to archive the private
-- key of a key pair that the receiver generates in response to
-- this request; set to FALSE if no archival is desired.
PKIPublicationInfo ::= SEQUENCE {
action INTEGER {
dontPublish (0),
pleasePublish (1) },
pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
-- pubInfos MUST NOT be present if action is "dontPublish"
-- (if action is "pleasePublish" and pubInfos is omitted,
-- "dontCare" is assumed)
Constructor with a single pubInfo, assumes pleasePublish as the action.
@param pubInfo the pubInfo to be published (can be null if don't care is required).
Constructor with multiple pubInfo, assumes pleasePublish as the action.
@param pubInfos the pubInfos to be published (can be null if don't care is required).
PkiPublicationInfo ::= SEQUENCE {
action INTEGER {
dontPublish (0),
pleasePublish (1) },
pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
-- pubInfos MUST NOT be present if action is "dontPublish"
-- (if action is "pleasePublish" and pubInfos is omitted,
-- "dontCare" is assumed)
@return a basic ASN.1 object representation.
Password-based MAC value for use with POPOSigningKeyInput.
Creates a new PKMACValue.
@param params parameters for password-based MAC
@param value MAC of the DER-encoded SubjectPublicKeyInfo
Creates a new PKMACValue.
@param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter
@param value MAC of the DER-encoded SubjectPublicKeyInfo
PKMACValue ::= SEQUENCE {
algId AlgorithmIdentifier,
-- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
-- parameter value is PBMParameter
value BIT STRING }
@return a basic ASN.1 object representation.
PopoPrivKey ::= CHOICE {
thisMessage [0] BIT STRING, -- Deprecated
-- possession is proven in this message (which contains the private
-- key itself (encrypted for the CA))
subsequentMessage [1] SubsequentMessage,
-- possession will be proven in a subsequent message
dhMAC [2] BIT STRING, -- Deprecated
agreeMAC [3] PKMACValue,
encryptedKey [4] EnvelopedData }
Creates a new Proof of Possession object for a signing key.
@param poposkIn the PopoSigningKeyInput structure, or null if the
CertTemplate includes both subject and publicKey values.
@param aid the AlgorithmIdentifier used to sign the proof of possession.
@param signature a signature over the DER-encoded value of poposkIn,
or the DER-encoded value of certReq if poposkIn is null.
PopoSigningKey ::= SEQUENCE {
poposkInput [0] PopoSigningKeyInput OPTIONAL,
algorithmIdentifier AlgorithmIdentifier,
signature BIT STRING }
-- The signature (using "algorithmIdentifier") is on the
-- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
-- certReq CertTemplate contains the subject and publicKey values,
-- then poposkInput MUST be omitted and the signature MUST be
-- computed on the DER-encoded value of CertReqMsg certReq. If
-- the CertReqMsg certReq CertTemplate does not contain the public
-- key and subject values, then poposkInput MUST be present and
-- MUST be signed. This strategy ensures that the public key is
-- not present in both the poposkInput and CertReqMsg certReq
-- CertTemplate fields.
@return a basic ASN.1 object representation.
Creates a new PopoSigningKeyInput with sender name as authInfo.
Creates a new PopoSigningKeyInput using password-based MAC.
Returns the sender field, or null if authInfo is publicKeyMac
Returns the publicKeyMac field, or null if authInfo is sender
PopoSigningKeyInput ::= SEQUENCE {
authInfo CHOICE {
sender [0] GeneralName,
-- used only if an authenticated identity has been
-- established for the sender (e.g., a DN from a
-- previously-issued and currently-valid certificate
publicKeyMac PKMacValue },
-- used if no authenticated GeneralName currently exists for
-- the sender; publicKeyMac contains a password-based MAC
-- on the DER-encoded value of publicKey
publicKey SubjectPublicKeyInfo } -- from CertTemplate
@return a basic ASN.1 object representation.
Creates a ProofOfPossession with type raVerified.
Creates a ProofOfPossession for a signing key.
Creates a ProofOfPossession for key encipherment or agreement.
@param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT
ProofOfPossession ::= CHOICE {
raVerified [0] NULL,
-- used if the RA has already verified that the requester is in
-- possession of the private key
signature [1] PopoSigningKey,
keyEncipherment [2] PopoPrivKey,
keyAgreement [3] PopoPrivKey }
@return a basic ASN.1 object representation.
SinglePubInfo ::= SEQUENCE {
pubMethod INTEGER {
dontCare (0),
x500 (1),
web (2),
ldap (3) },
pubLocation GeneralName OPTIONAL }
@return a basic ASN.1 object representation.
Elliptic curve registry for GOST 3410-2001 / 2012.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
Gost28147-89-Parameters ::=
SEQUENCE {
iv Gost28147-89-IV,
encryptionParamSet OBJECT IDENTIFIER
}
Gost28147-89-IV ::= OCTET STRING (SIZE (8))
Registry of available named parameters for GOST 3410-94.
Look up the for the parameter set with the given name.
The name of the parameter set.
Look up the for the parameter set with the given
OID.
The OID for the parameter set.
Look up the OID of the parameter set with the given name.
The name of the parameter set.
Enumerate the available parameter set names in this registry.
return a Bit string from the passed in object
@exception ArgumentException if the object cannot be converted.
return a Bit string from a tagged object.
@param obj the tagged object holding the object we want
@param explicitly true if the object is meant to be explicitly
tagged false otherwise.
@exception ArgumentException if the tagged object cannot
be converted.
@param data the octets making up the bit string.
@param padBits the number of extra bits at the end of the string.
Return the octets contained in this BIT STRING, checking that this BIT STRING really
does represent an octet aligned string. Only use this method when the standard you are
following dictates that the BIT STRING will be octet aligned.
@return a copy of the octet aligned data.
@return the value of the bit string as an int (truncating if necessary)
Der BMPString object.
return a BMP string from the given object.
@param obj the object we want converted.
@exception ArgumentException if the object cannot be converted.
return a BMP string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
basic constructor
return a bool from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a Boolean from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
return an integer from the passed in object
@exception ArgumentException if the object cannot be converted.
return an Enumerated from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
Class representing the DER-type External
Creates a new instance of DerExternal
See X.690 for more informations about the meaning of these parameters
@param directReference The direct reference or null
if not set.
@param indirectReference The indirect reference or null
if not set.
@param dataValueDescriptor The data value descriptor or null
if not set.
@param externalData The external data in its encoded form.
Creates a new instance of DerExternal.
See X.690 for more informations about the meaning of these parameters
@param directReference The direct reference or null
if not set.
@param indirectReference The indirect reference or null
if not set.
@param dataValueDescriptor The data value descriptor or null
if not set.
@param encoding The encoding to be used for the external data
@param externalData The external data
The encoding of the content. Valid values are
0
single-ASN1-type
1
OCTET STRING
2
BIT STRING
return a Graphic String from the passed in object
@param obj a DerGraphicString or an object that can be converted into one.
@exception IllegalArgumentException if the object cannot be converted.
@return a DerGraphicString instance, or null.
return a Graphic String from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception IllegalArgumentException if the tagged object cannot be converted.
@return a DerGraphicString instance, or null.
IA5String object - this is an Ascii string.
return an IA5 string from the passed in object
@exception ArgumentException if the object cannot be converted.
return an IA5 string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
Constructor with optional validation.
@param string the base string to wrap.
@param validate whether or not to check the string.
@throws ArgumentException if validate is true and the string
contains characters that should not be in an IA5String.
return true if the passed in String can be represented without
loss as an IA5String, false otherwise.
@return true if in printable set, false otherwise.
return an integer from the passed in object
@exception ArgumentException if the object cannot be converted.
return an Integer from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
in some cases positive values Get crammed into a space,
that's not quite big enough...
Apply the correct validation for an INTEGER primitive following the BER rules.
@param bytes The raw encoding of the integer.
@return true if the (in)put fails this validation.
A Null object.
Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }.
return a numeric string from the passed in object
@exception ArgumentException if the object cannot be converted.
return a numeric string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
Constructor with optional validation.
@param string the base string to wrap.
@param validate whether or not to check the string.
@throws ArgumentException if validate is true and the string
contains characters that should not be in a NumericString.
Return true if the string can be represented as a NumericString ('0'..'9', ' ')
@param str string to validate.
@return true if numeric, fale otherwise.
return an OID from the passed in object
@exception ArgumentException if the object cannot be converted.
Return true if this oid is an extension of the passed in branch, stem.
@param stem the arc or branch that is a possible parent.
@return true if the branch is on the passed in stem, false otherwise.
The octets making up the octet string.
Der PrintableString object.
return a printable string from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a printable string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
Constructor with optional validation.
@param string the base string to wrap.
@param validate whether or not to check the string.
@throws ArgumentException if validate is true and the string
contains characters that should not be in a PrintableString.
return true if the passed in String can be represented without
loss as a PrintableString, false otherwise.
@return true if in printable set, false otherwise.
create an empty sequence
create a sequence containing one object
create a sequence containing two objects
create a sequence containing a vector of objects.
A Der encoded set object
create an empty set
@param obj - a single object that makes up the set.
@param v - a vector of objects making up the set.
Der T61String (also the teletex string) - 8-bit characters
return a T61 string from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a T61 string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
DER TaggedObject - in ASN.1 notation this is any object preceded by
a [n] where n is some number - these are assumed to follow the construction
rules (as with sequences).
@param isExplicit true if an explicitly tagged object.
@param tagNo the tag number for this object.
@param obj the tagged object.
UniversalString object.
return a universal string from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a universal string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
Der UTF8String object.
return an UTF8 string from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a UTF8 string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
return a videotex string from the passed in object
@param obj a DERVideotexString or an object that can be converted into one.
@exception IllegalArgumentException if the object cannot be converted.
@return a DERVideotexString instance, or null.
return a videotex string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception IllegalArgumentException if the tagged object cannot be converted.
@return a DERVideotexString instance, or null.
VisibleString object.
return a visible string from the passed in object.
@exception ArgumentException if the object cannot be converted.
return a visible string from a tagged object.
@param taggedObject the tagged object holding the object we want
@param declaredExplicit true if the object is meant to be explicitly tagged false otherwise.
@exception ArgumentException if the tagged object cannot be converted.
A Definite length BIT STRING
Parser for a DL encoded BIT STRING.
create an empty sequence
create a sequence containing one object
create a sequence containing two objects
create a sequence containing a vector of objects.
create an empty set
create a set containing one object
create a set containing a vector of objects.
Parser for definite-length tagged objects.
Edwards Elliptic Curve Object Identifiers (RFC 8410)
RFC 3126: 4.3.1 Certificate Values Attribute Definition
CertificateValues ::= SEQUENCE OF Certificate
CommitmentTypeIndication ::= SEQUENCE {
commitmentTypeId CommitmentTypeIdentifier,
commitmentTypeQualifier SEQUENCE SIZE (1..MAX) OF
CommitmentTypeQualifier OPTIONAL }
Commitment type qualifiers, used in the Commitment-Type-Indication attribute (RFC3126).
CommitmentTypeQualifier ::= SEQUENCE {
commitmentTypeIdentifier CommitmentTypeIdentifier,
qualifier ANY DEFINED BY commitmentTypeIdentifier OPTIONAL }
Creates a new CommitmentTypeQualifier
instance.
@param commitmentTypeIdentifier a CommitmentTypeIdentifier
value
Creates a new CommitmentTypeQualifier
instance.
@param commitmentTypeIdentifier a CommitmentTypeIdentifier
value
@param qualifier the qualifier, defined by the above field.
Creates a new CommitmentTypeQualifier
instance.
@param as CommitmentTypeQualifier
structure
encoded as an Asn1Sequence.
Returns a DER-encodable representation of this instance.
@return a Asn1Object
value
RFC 3126: 4.2.1 Complete Certificate Refs Attribute Definition
CompleteCertificateRefs ::= SEQUENCE OF OtherCertID
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
CompleteRevocationRefs ::= SEQUENCE OF CrlOcspRef
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
CrlIdentifier ::= SEQUENCE
{
crlissuer Name,
crlIssuedTime UTCTime,
crlNumber INTEGER OPTIONAL
}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
CRLListID ::= SEQUENCE
{
crls SEQUENCE OF CrlValidatedID
}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
CrlOcspRef ::= SEQUENCE {
crlids [0] CRLListID OPTIONAL,
ocspids [1] OcspListID OPTIONAL,
otherRev [2] OtherRevRefs OPTIONAL
}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
CrlValidatedID ::= SEQUENCE {
crlHash OtherHash,
crlIdentifier CrlIdentifier OPTIONAL}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
OcspIdentifier ::= SEQUENCE {
ocspResponderID ResponderID,
-- As in OCSP response data
producedAt GeneralizedTime
-- As in OCSP response data
}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
OcspListID ::= SEQUENCE {
ocspResponses SEQUENCE OF OcspResponsesID
}
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
OcspResponsesID ::= SEQUENCE {
ocspIdentifier OcspIdentifier,
ocspRepHash OtherHash OPTIONAL
}
OtherCertID ::= SEQUENCE {
otherCertHash OtherHash,
issuerSerial IssuerSerial OPTIONAL
}
OtherHash ::= CHOICE {
sha1Hash OtherHashValue, -- This contains a SHA-1 hash
otherHash OtherHashAlgAndValue
}
OtherHashValue ::= OCTET STRING
Summary description for OtherHashAlgAndValue.
OtherHashAlgAndValue ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
hashValue OtherHashValue
}
OtherHashValue ::= OCTET STRING
RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition
OtherRevRefs ::= SEQUENCE
{
otherRevRefType OtherRevRefType,
otherRevRefs ANY DEFINED BY otherRevRefType
}
OtherRevRefType ::= OBJECT IDENTIFIER
RFC 3126: 4.3.2 Revocation Values Attribute Definition
OtherRevVals ::= SEQUENCE
{
otherRevValType OtherRevValType,
otherRevVals ANY DEFINED BY otherRevValType
}
OtherRevValType ::= OBJECT IDENTIFIER
OtherSigningCertificate ::= SEQUENCE {
certs SEQUENCE OF OtherCertID,
policies SEQUENCE OF PolicyInformation OPTIONAL
}
RFC 5126: 6.3.4. revocation-values Attribute Definition
RevocationValues ::= SEQUENCE {
crlVals [0] SEQUENCE OF CertificateList OPTIONAL,
ocspVals [1] SEQUENCE OF BasicOCSPResponse OPTIONAL,
otherRevVals [2] OtherRevVals OPTIONAL
}
SignaturePolicyId ::= SEQUENCE {
sigPolicyIdentifier SigPolicyId,
sigPolicyHash SigPolicyHash,
sigPolicyQualifiers SEQUENCE SIZE (1..MAX) OF SigPolicyQualifierInfo OPTIONAL
}
SigPolicyId ::= OBJECT IDENTIFIER
SigPolicyHash ::= OtherHashAlgAndValue
SignaturePolicyIdentifier ::= CHOICE {
SignaturePolicyId SignaturePolicyId,
SignaturePolicyImplied SignaturePolicyImplied
}
SignaturePolicyImplied ::= NULL
SignerAttribute ::= SEQUENCE OF CHOICE {
claimedAttributes [0] ClaimedAttributes,
certifiedAttributes [1] CertifiedAttributes }
ClaimedAttributes ::= SEQUENCE OF Attribute
CertifiedAttributes ::= AttributeCertificate -- as defined in RFC 3281: see clause 4.1.
Signer-Location attribute (RFC3126).
SignerLocation ::= SEQUENCE {
countryName [0] DirectoryString OPTIONAL,
localityName [1] DirectoryString OPTIONAL,
postalAddress [2] PostalAddress OPTIONAL }
PostalAddress ::= SEQUENCE SIZE(1..6) OF DirectoryString
SignerLocation ::= SEQUENCE {
countryName [0] DirectoryString OPTIONAL,
localityName [1] DirectoryString OPTIONAL,
postalAddress [2] PostalAddress OPTIONAL }
PostalAddress ::= SEQUENCE SIZE(1..6) OF DirectoryString
DirectoryString ::= CHOICE {
teletexString TeletexString (SIZE (1..MAX)),
printableString PrintableString (SIZE (1..MAX)),
universalString UniversalString (SIZE (1..MAX)),
utf8String UTF8String (SIZE (1.. MAX)),
bmpString BMPString (SIZE (1..MAX)) }
SigPolicyQualifierInfo ::= SEQUENCE {
sigPolicyQualifierId SigPolicyQualifierId,
sigQualifier ANY DEFINED BY sigPolicyQualifierId
}
SigPolicyQualifierId ::= OBJECT IDENTIFIER
constructor
ContentHints ::= SEQUENCE {
contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
contentType ContentType }
Create from OCTET STRING whose octets represent the identifier.
Create from byte array representing the identifier.
The definition of ContentIdentifier is
ContentIdentifier ::= OCTET STRING
id-aa-contentIdentifier OBJECT IDENTIFIER ::= { iso(1)
member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
smime(16) id-aa(2) 7 }
constructor
EssCertID ::= SEQUENCE {
certHash Hash,
issuerSerial IssuerSerial OPTIONAL }
EssCertIDv2 ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier
DEFAULT {algorithm id-sha256},
certHash Hash,
issuerSerial IssuerSerial OPTIONAL
}
Hash ::= OCTET STRING
IssuerSerial ::= SEQUENCE {
issuer GeneralNames,
serialNumber CertificateSerialNumber
}
constructors
The definition of SigningCertificate is
SigningCertificate ::= SEQUENCE {
certs SEQUENCE OF EssCertID,
policies SEQUENCE OF PolicyInformation OPTIONAL
}
id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
smime(16) id-aa(2) 12 }
The definition of SigningCertificateV2 is
SigningCertificateV2 ::= SEQUENCE {
certs SEQUENCE OF EssCertIDv2,
policies SEQUENCE OF PolicyInformation OPTIONAL
}
id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1)
member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
smime(16) id-aa(2) 47 }
Elliptic curve registry for GM.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
1.3.6.1.4.1.11591.15 - ellipticCurve
Marker interface for CHOICE objects - if you implement this in a roll-your-own
object, any attempt to tag the object implicitly will convert the tag to an
explicit one as the encoding rules require.
If you use this interface your class should also implement the getInstance
pattern which takes a tag object and the tagging mode used.
basic interface for Der string objects.
The CscaMasterList object. This object can be wrapped in a
CMSSignedData to be published in LDAP.
CscaMasterList ::= SEQUENCE {
version CscaMasterListVersion,
certList SET OF Certificate }
CscaMasterListVersion :: INTEGER {v0(0)}
The DataGroupHash object.
DataGroupHash ::= SEQUENCE {
dataGroupNumber DataGroupNumber,
dataGroupHashValue OCTET STRING }
DataGroupNumber ::= INTEGER {
dataGroup1 (1),
dataGroup1 (2),
dataGroup1 (3),
dataGroup1 (4),
dataGroup1 (5),
dataGroup1 (6),
dataGroup1 (7),
dataGroup1 (8),
dataGroup1 (9),
dataGroup1 (10),
dataGroup1 (11),
dataGroup1 (12),
dataGroup1 (13),
dataGroup1 (14),
dataGroup1 (15),
dataGroup1 (16) }
The LDSSecurityObject object (V1.8).
LDSSecurityObject ::= SEQUENCE {
version LDSSecurityObjectVersion,
hashAlgorithm DigestAlgorithmIdentifier,
dataGroupHashValues SEQUENCE SIZE (2..ub-DataGroups) OF DataHashGroup,
ldsVersionInfo LDSVersionInfo OPTIONAL
-- if present, version MUST be v1 }
DigestAlgorithmIdentifier ::= AlgorithmIdentifier,
LDSSecurityObjectVersion :: INTEGER {V0(0)}
LDSVersionInfo ::= SEQUENCE {
ldsVersion PRINTABLE STRING
unicodeVersion PRINTABLE STRING
}
@return
The id-isismtt-cp-accredited OID indicates that the certificate is a
qualified certificate according to Directive 1999/93/EC of the European
Parliament and of the Council of 13 December 1999 on a Community
Framework for Electronic Signatures, which additionally conforms the
special requirements of the SigG and has been issued by an accredited CA.
Certificate extensionDate of certificate generation
DateOfCertGenSyntax ::= GeneralizedTime
Attribute to indicate that the certificate holder may sign in the name of
a third person. May also be used as extension in a certificate.
Attribute to indicate admissions to certain professions. May be used as
attribute in attribute certificate or as extension in a certificate
Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST
be used in new certificates in place of the extension/attribute
MonetaryLimit since January 1, 2004. For the sake of backward
compatibility with certificates already in use, SigG conforming
components MUST support MonetaryLimit (as well as QcEuLimitValue).
A declaration of majority. May be used as attribute in attribute
certificate or as extension in a certificate
Serial number of the smart card containing the corresponding private key
ICCSNSyntax ::= OCTET STRING (SIZE(8..20))
Reference for a file of a smartcard that stores the public key of this
certificate and that is used as �security anchor�.
PKReferenceSyntax ::= OCTET STRING (SIZE(20))
Some other restriction regarding the usage of this certificate. May be
used as attribute in attribute certificate or as extension in a
certificate.
RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction
(Single)Request extension: Clients may include this extension in a
(single) Request to request the responder to send the certificate in the
response message along with the status information. Besides the LDAP
service, this extension provides another mechanism for the distribution
of certificates, which MAY optionally be provided by certificate
repositories.
RetrieveIfAllowed ::= BOOLEAN
SingleOCSPResponse extension: The certificate requested by the client by
inserting the RetrieveIfAllowed extension in the request, will be
returned in this extension.
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate
Base ObjectIdentifier for naming authorities
SingleOCSPResponse extension: Date, when certificate has been published
in the directory and status information has become available. Currently,
accrediting authorities enforce that SigG-conforming OCSP servers include
this extension in the responses.
CertInDirSince ::= GeneralizedTime
Hash of a certificate in OCSP.
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash
NameAtBirth ::= DirectoryString(SIZE(1..64)
Used in
{@link Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes}
Some other information of non-restrictive nature regarding the usage of
this certificate. May be used as attribute in atribute certificate or as
extension in a certificate.
AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax
Indicates that an attribute certificate exists, which limits the
usability of this public key certificate. Whenever verifying a signature
with the help of this certificate, the content of the corresponding
attribute certificate should be concerned. This extension MUST be
included in a PKC, if a corresponding attribute certificate (having the
PKC as base certificate) contains some attribute that restricts the
usability of the PKC too. Attribute certificates with restricting content
MUST always be included in the signed document.
LiabilityLimitationFlagSyntax ::= BOOLEAN
ISIS-MTT PROFILE: The responder may include this extension in a response to
send the hash of the requested certificate to the responder. This hash is
cryptographically bound to the certificate and serves as evidence that the
certificate is known to the responder (i.e. it has been issued and is present
in the directory). Hence, this extension is a means to provide a positive
statement of availability as described in T8.[8]. As explained in T13.[1],
clients may rely on this information to be able to validate signatures after
the expiry of the corresponding certificate. Hence, clients MUST support this
extension. If a positive statement of availability is to be delivered, this
extension syntax and OID MUST be used.
CertHash ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
certificateHash OCTET STRING
}
Constructor from Asn1Sequence.
The sequence is of type CertHash:
CertHash ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
certificateHash OCTET STRING
}
@param seq The ASN.1 sequence.
Constructor from a given details.
@param hashAlgorithm The hash algorithm identifier.
@param certificateHash The hash of the whole DER encoding of the certificate.
Produce an object suitable for an Asn1OutputStream.
Returns:
CertHash ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
certificateHash OCTET STRING
}
@return an Asn1Object
ISIS-MTT-Optional: The certificate requested by the client by inserting the
RetrieveIfAllowed extension in the request, will be returned in this
extension.
ISIS-MTT-SigG: The signature act allows publishing certificates only then,
when the certificate owner gives his isExplicit permission. Accordingly, there
may be �nondownloadable� certificates, about which the responder must provide
status information, but MUST NOT include them in the response. Clients may
get therefore the following three kind of answers on a single request
including the RetrieveIfAllowed extension:
- a) the responder supports the extension and is allowed to publish the
certificate: RequestedCertificate returned including the requested
certificate
- b) the responder supports the extension but is NOT allowed to publish
the certificate: RequestedCertificate returned including an empty OCTET
STRING
- c) the responder does not support the extension: RequestedCertificate is
not included in the response
Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If
any of the OCTET STRING options is used, it MUST contain the DER encoding of
the requested certificate.
RequestedCertificate ::= CHOICE {
Certificate Certificate,
publicKeyCertificate [0] EXPLICIT OCTET STRING,
attributeCertificate [1] EXPLICIT OCTET STRING
}
Constructor from a given details.
Only one parameter can be given. All other must be null
.
@param certificate Given as Certificate
Produce an object suitable for an Asn1OutputStream.
Returns:
RequestedCertificate ::= CHOICE {
Certificate Certificate,
publicKeyCertificate [0] EXPLICIT OCTET STRING,
attributeCertificate [1] EXPLICIT OCTET STRING
}
@return an Asn1Object
Some other information of non-restrictive nature regarding the usage of this
certificate.
AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
Constructor from a given details.
@param information The describtion of the information.
Produce an object suitable for an Asn1OutputStream.
Returns:
AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
@return an Asn1Object
An Admissions structure.
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority
Constructor from Asn1Sequence.
The sequence is of type ProcurationSyntax:
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
@param seq The ASN.1 sequence.
Constructor from a given details.
Parameter professionInfos
is mandatory.
@param admissionAuthority The admission authority.
@param namingAuthority The naming authority.
@param professionInfos The profession infos.
Produce an object suitable for an Asn1OutputStream.
Returns:
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
@return an Asn1Object
Attribute to indicate admissions to certain professions.
AdmissionSyntax ::= SEQUENCE
{
admissionAuthority GeneralName OPTIONAL,
contentsOfAdmissions SEQUENCE OF Admissions
}
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
NamingAuthority ::= SEQUENCE
{
namingAuthorityId OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax
supports the following concepts and requirements:
- External institutions (e.g. professional associations, chambers, unions,
administrative bodies, companies, etc.), which are responsible for granting
and verifying professional admissions, are indicated by means of the data
field admissionAuthority. An admission authority is indicated by a
GeneralName object. Here an X.501 directory name (distinguished name) can be
indicated in the field directoryName, a URL address can be indicated in the
field uniformResourceIdentifier, and an object identifier can be indicated in
the field registeredId.
- The names of authorities which are responsible for the administration of
title registers are indicated in the data field namingAuthority. The name of
the authority can be identified by an object identifier in the field
namingAuthorityId, by means of a text string in the field
namingAuthorityText, by means of a URL address in the field
namingAuthorityUrl, or by a combination of them. For example, the text string
can contain the name of the authority, the country and the name of the title
register. The URL-option refers to a web page which contains lists with
officially registered professions (text and possibly OID) as well as
further information on these professions. Object identifiers for the
component namingAuthorityId are grouped under the OID-branch
id-isis-at-namingAuthorities and must be applied for.
- See http://www.teletrust.de/anwend.asp?Id=30200&Sprache=E_&HomePG=0
for an application form and http://www.teletrust.de/links.asp?id=30220,11
for an overview of registered naming authorities.
- By means of the data type ProfessionInfo certain professions,
specializations, disciplines, fields of activity, etc. are identified. A
profession is represented by one or more text strings, resp. profession OIDs
in the fields professionItems and professionOIDs and by a registration number
in the field registrationNumber. An indication in text form must always be
present, whereas the other indications are optional. The component
addProfessionInfo may contain additional applicationspecific information in
DER-encoded form.
By means of different namingAuthority-OIDs or profession OIDs hierarchies of
professions, specializations, disciplines, fields of activity, etc. can be
expressed. The issuing admission authority should always be indicated (field
admissionAuthority), whenever a registration number is presented. Still,
information on admissions can be given without indicating an admission or a
naming authority by the exclusive use of the component professionItems. In
this case the certification authority is responsible for the verification of
the admission information.
This attribute is single-valued. Still, several admissions can be captured in
the sequence structure of the component contentsOfAdmissions of
AdmissionSyntax or in the component professionInfos of Admissions. The
component admissionAuthority of AdmissionSyntax serves as default value for
the component admissionAuthority of Admissions. Within the latter component
the default value can be overwritten, in case that another authority is
responsible. The component namingAuthority of Admissions serves as a default
value for the component namingAuthority of ProfessionInfo. Within the latter
component the default value can be overwritten, in case that another naming
authority needs to be recorded.
The length of the string objects is limited to 128 characters. It is
recommended to indicate a namingAuthorityURL in all issued attribute
certificates. If a namingAuthorityURL is indicated, the field professionItems
of ProfessionInfo should contain only registered titles. If the field
professionOIDs exists, it has to contain the OIDs of the professions listed
in professionItems in the same order. In general, the field professionInfos
should contain only one entry, unless the admissions that are to be listed
are logically connected (e.g. they have been issued under the same admission
number).
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority
Constructor from Asn1Sequence.
The sequence is of type ProcurationSyntax:
AdmissionSyntax ::= SEQUENCE
{
admissionAuthority GeneralName OPTIONAL,
contentsOfAdmissions SEQUENCE OF Admissions
}
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
NamingAuthority ::= SEQUENCE
{
namingAuthorityId OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
@param seq The ASN.1 sequence.
Constructor from given details.
@param admissionAuthority The admission authority.
@param contentsOfAdmissions The admissions.
Produce an object suitable for an Asn1OutputStream.
Returns:
AdmissionSyntax ::= SEQUENCE
{
admissionAuthority GeneralName OPTIONAL,
contentsOfAdmissions SEQUENCE OF Admissions
}
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
NamingAuthority ::= SEQUENCE
{
namingAuthorityId OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
@return an Asn1Object
@return Returns the admissionAuthority if present, null otherwise.
@return Returns the contentsOfAdmissions.
A declaration of majority.
DeclarationOfMajoritySyntax ::= CHOICE
{
notYoungerThan [0] IMPLICIT INTEGER,
fullAgeAtCountry [1] IMPLICIT SEQUENCE
{
fullAge BOOLEAN DEFAULT TRUE,
country PrintableString (SIZE(2))
}
dateOfBirth [2] IMPLICIT GeneralizedTime
}
fullAgeAtCountry indicates the majority of the owner with respect to the laws
of a specific country.
Produce an object suitable for an Asn1OutputStream.
Returns:
DeclarationOfMajoritySyntax ::= CHOICE
{
notYoungerThan [0] IMPLICIT INTEGER,
fullAgeAtCountry [1] IMPLICIT SEQUENCE
{
fullAge BOOLEAN DEFAULT TRUE,
country PrintableString (SIZE(2))
}
dateOfBirth [2] IMPLICIT GeneralizedTime
}
@return an Asn1Object
@return notYoungerThan if that's what we are, -1 otherwise
Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST be
used in new certificates in place of the extension/attribute MonetaryLimit
since January 1, 2004. For the sake of backward compatibility with
certificates already in use, components SHOULD support MonetaryLimit (as well
as QcEuLimitValue).
Indicates a monetary limit within which the certificate holder is authorized
to act. (This value DOES NOT express a limit on the liability of the
certification authority).
MonetaryLimitSyntax ::= SEQUENCE
{
currency PrintableString (SIZE(3)),
amount INTEGER,
exponent INTEGER
}
currency must be the ISO code.
value = amount�10*exponent
Constructor from a given details.
value = amount�10^exponent
@param currency The currency. Must be the ISO code.
@param amount The amount
@param exponent The exponent
Produce an object suitable for an Asn1OutputStream.
Returns:
MonetaryLimitSyntax ::= SEQUENCE
{
currency PrintableString (SIZE(3)),
amount INTEGER,
exponent INTEGER
}
@return an Asn1Object
Names of authorities which are responsible for the administration of title
registers.
NamingAuthority ::= SEQUENCE
{
namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax
Profession OIDs should always be defined under the OID branch of the
responsible naming authority. At the time of this writing, the work group
�Recht, Wirtschaft, Steuern� (�Law, Economy, Taxes�) is registered as the
first naming authority under the OID id-isismtt-at-namingAuthorities.
Constructor from Asn1Sequence.
NamingAuthority ::= SEQUENCE
{
namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
@param seq The ASN.1 sequence.
@return Returns the namingAuthorityID.
@return Returns the namingAuthorityText.
@return Returns the namingAuthorityUrl.
Constructor from given details.
All parameters can be combined.
@param namingAuthorityID ObjectIdentifier for naming authority.
@param namingAuthorityUrl URL for naming authority.
@param namingAuthorityText Textual representation of naming authority.
Produce an object suitable for an Asn1OutputStream.
Returns:
NamingAuthority ::= SEQUENCE
{
namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
@return an Asn1Object
Attribute to indicate that the certificate holder may sign in the name of a
third person.
ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
name of the person who is represented (subcomponent thirdPerson) or a
reference to his/her base certificate (in the component signingFor,
subcomponent certRef), furthermore the optional components country and
typeSubstitution to indicate the country whose laws apply, and respectively
the type of procuration (e.g. manager, procuration, custody).
ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
surname, givenName, serialNumber, organizationName, organizationalUnitName,
stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
countryOfResidence and NameAtBirth).
ProcurationSyntax ::= SEQUENCE {
country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
signingFor [3] EXPLICIT SigningFor
}
SigningFor ::= CHOICE
{
thirdPerson GeneralName,
certRef IssuerSerial
}
Constructor from Asn1Sequence.
The sequence is of type ProcurationSyntax:
ProcurationSyntax ::= SEQUENCE {
country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
signingFor [3] EXPLICIT SigningFor
}
SigningFor ::= CHOICE
{
thirdPerson GeneralName,
certRef IssuerSerial
}
@param seq The ASN.1 sequence.
Constructor from a given details.
Either generalName
or certRef
MUST be
null
.
@param country The country code whose laws apply.
@param typeOfSubstitution The type of procuration.
@param certRef Reference to certificate of the person who is represented.
Constructor from a given details.
Either generalName
or certRef
MUST be
null
.
@param country The country code whose laws apply.
@param typeOfSubstitution The type of procuration.
@param thirdPerson The GeneralName of the person who is represented.
Produce an object suitable for an Asn1OutputStream.
Returns:
ProcurationSyntax ::= SEQUENCE {
country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
signingFor [3] EXPLICIT SigningFor
}
SigningFor ::= CHOICE
{
thirdPerson GeneralName,
certRef IssuerSerial
}
@return an Asn1Object
Professions, specializations, disciplines, fields of activity, etc.
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
@see Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax
Rechtsanw�ltin
Rechtsanwalt
Rechtsbeistand
Steuerberaterin
Steuerberater
Steuerbevollm�chtigte
Steuerbevollm�chtigter
Notarin
Notar
Notarvertreterin
Notarvertreter
Notariatsverwalterin
Notariatsverwalter
Wirtschaftspr�ferin
Wirtschaftspr�fer
Vereidigte Buchpr�ferin
Vereidigter Buchpr�fer
Patentanw�ltin
Patentanwalt
Constructor from Asn1Sequence.
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
@param seq The ASN.1 sequence.
Constructor from given details.
professionItems
is mandatory, all other parameters are
optional.
@param namingAuthority The naming authority.
@param professionItems Directory strings of the profession.
@param professionOids DERObjectIdentfier objects for the
profession.
@param registrationNumber Registration number.
@param addProfessionInfo Additional infos in encoded form.
Produce an object suitable for an Asn1OutputStream.
Returns:
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
@return an Asn1Object
@return Returns the addProfessionInfo.
@return Returns the namingAuthority.
@return Returns the professionItems.
@return Returns the professionOids.
@return Returns the registrationNumber.
Some other restriction regarding the usage of this certificate.
RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
Constructor from DirectoryString.
The DirectoryString is of type RestrictionSyntax:
RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
@param restriction A IAsn1String.
Constructor from a given details.
@param restriction The description of the restriction.
Produce an object suitable for an Asn1OutputStream.
Returns:
RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
@return an Asn1Object
Produce an object suitable for an Asn1OutputStream.
cast5CBCParameters ::= Sequence {
iv OCTET STRING DEFAULT 0,
-- Initialization vector
keyLength Integer
-- Key length, in bits
}
Produce an object suitable for an Asn1OutputStream.
IDEA-CBCPar ::= Sequence {
iv OCTET STRING OPTIONAL -- exactly 8 octets
}
The NetscapeCertType object.
NetscapeCertType ::= BIT STRING {
SSLClient (0),
SSLServer (1),
S/MIME (2),
Object Signing (3),
Reserved (4),
SSL CA (5),
S/MIME CA (6),
Object Signing CA (7) }
Basic constructor.
@param usage - the bitwise OR of the Key Usage flags giving the
allowed uses for the key.
e.g. (X509NetscapeCertType.sslCA | X509NetscapeCertType.smimeCA)
This is designed to parse
the PublicKeyAndChallenge created by the KEYGEN tag included by
Mozilla based browsers.
PublicKeyAndChallenge ::= SEQUENCE {
spki SubjectPublicKeyInfo,
challenge IA5STRING
}
KMACwithSHAKE128-params ::= SEQUENCE {
kMACOutputLength INTEGER DEFAULT 256, -- Output length in bits
customizationString OCTET STRING DEFAULT ''H
}
KMACwithSHAKE256-params ::= SEQUENCE {
kMACOutputLength INTEGER DEFAULT 512, -- Output length in bits
customizationString OCTET STRING DEFAULT ''H
}
Elliptic curve registry for NIST curves.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of
the full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of
the full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
2.16.840.1.101.3.4.3.5
2.16.840.1.101.3.4.3.6
2.16.840.1.101.3.4.3.7
2.16.840.1.101.3.4.3.8
2.16.840.1.101.3.4.3.9
2.16.840.1.101.3.4.3.10
2.16.840.1.101.3.4.3.11
2.16.840.1.101.3.4.3.12
2.16.840.1.101.3.4.3.9
2.16.840.1.101.3.4.3.10
2.16.840.1.101.3.4.3.11
2.16.840.1.101.3.4.3.12
From RFC 3657
Produce an object suitable for an Asn1OutputStream.
BasicOcspResponse ::= Sequence {
tbsResponseData ResponseData,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING,
certs [0] EXPLICIT Sequence OF Certificate OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
CertID ::= Sequence {
hashAlgorithm AlgorithmIdentifier,
issuerNameHash OCTET STRING, -- Hash of Issuer's DN
issuerKeyHash OCTET STRING, -- Hash of Issuers public key
serialNumber CertificateSerialNumber }
create a CertStatus object with a tag of zero.
Produce an object suitable for an Asn1OutputStream.
CertStatus ::= CHOICE {
good [0] IMPLICIT Null,
revoked [1] IMPLICIT RevokedInfo,
unknown [2] IMPLICIT UnknownInfo }
Produce an object suitable for an Asn1OutputStream.
CrlID ::= Sequence {
crlUrl [0] EXPLICIT IA5String OPTIONAL,
crlNum [1] EXPLICIT Integer OPTIONAL,
crlTime [2] EXPLICIT GeneralizedTime OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
OcspRequest ::= Sequence {
tbsRequest TBSRequest,
optionalSignature [0] EXPLICIT Signature OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
OcspResponse ::= Sequence {
responseStatus OcspResponseStatus,
responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
The OcspResponseStatus enumeration.
OcspResponseStatus ::= Enumerated {
successful (0), --Response has valid confirmations
malformedRequest (1), --Illegal confirmation request
internalError (2), --Internal error in issuer
tryLater (3), --Try again later
--(4) is not used
sigRequired (5), --Must sign the request
unauthorized (6) --Request unauthorized
}
Produce an object suitable for an Asn1OutputStream.
Request ::= Sequence {
reqCert CertID,
singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
ResponderID ::= CHOICE {
byName [1] Name,
byKey [2] KeyHash }
Produce an object suitable for an Asn1OutputStream.
ResponseBytes ::= Sequence {
responseType OBJECT IDENTIFIER,
response OCTET STRING }
Produce an object suitable for an Asn1OutputStream.
ResponseData ::= Sequence {
version [0] EXPLICIT Version DEFAULT v1,
responderID ResponderID,
producedAt GeneralizedTime,
responses Sequence OF SingleResponse,
responseExtensions [1] EXPLICIT Extensions OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
RevokedInfo ::= Sequence {
revocationTime GeneralizedTime,
revocationReason [0] EXPLICIT CRLReason OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
ServiceLocator ::= Sequence {
issuer Name,
locator AuthorityInfoAccessSyntax OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
Signature ::= Sequence {
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING,
certs [0] EXPLICIT Sequence OF Certificate OPTIONAL}
Produce an object suitable for an Asn1OutputStream.
SingleResponse ::= Sequence {
certID CertID,
certStatus CertStatus,
thisUpdate GeneralizedTime,
nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
singleExtensions [1] EXPLICIT Extensions OPTIONAL }
Produce an object suitable for an Asn1OutputStream.
TBSRequest ::= Sequence {
version [0] EXPLICIT Version DEFAULT v1,
requestorName [1] EXPLICIT GeneralName OPTIONAL,
requestList Sequence OF Request,
requestExtensions [2] EXPLICIT Extensions OPTIONAL }
class for breaking up an Oid into it's component tokens, ala
java.util.StringTokenizer. We need this class as some of the
lightweight Java environment don't support classes like
StringTokenizer.
return an Attribute object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
Attr ::= Sequence {
attrType OBJECT IDENTIFIER,
attrValues Set OF AttributeValue
}
Pkcs10 Certfication request object.
CertificationRequest ::= Sequence {
certificationRequestInfo CertificationRequestInfo,
signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
signature BIT STRING
}
Pkcs10 CertificationRequestInfo object.
CertificationRequestInfo ::= Sequence {
version Integer { v1(0) } (v1,...),
subject Name,
subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
attributes [0] Attributes{{ CRIAttributes }}
}
Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
Attr { ATTRIBUTE:IOSet } ::= Sequence {
type ATTRIBUTE.&id({IOSet}),
values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
}
Produce an object suitable for an Asn1OutputStream.
ContentInfo ::= Sequence {
contentType ContentType,
content
[0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
The EncryptedData object.
EncryptedData ::= Sequence {
version Version,
encryptedContentInfo EncryptedContentInfo
}
EncryptedContentInfo ::= Sequence {
contentType ContentType,
contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
}
EncryptedContent ::= OCTET STRING
Produce an object suitable for an Asn1OutputStream.
EncryptedPrivateKeyInfo ::= Sequence {
encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
encryptedData EncryptedData
}
EncryptedData ::= OCTET STRING
KeyEncryptionAlgorithms ALGORITHM-IDENTIFIER ::= {
... -- For local profiles
}
MacData ::= SEQUENCE {
mac DigestInfo,
macSalt OCTET STRING,
iterations INTEGER DEFAULT 1
-- Note: The default is for historic reasons and its use is deprecated. A
-- higher value, like 1024 is recommended.
@return the basic DERObject construction.
the infamous Pfx from Pkcs12
PKCS#1: 1.2.840.113549.1.1.15
PKCS#1: 1.2.840.113549.1.1.16
id-alg-AEADChaCha20Poly1305 OBJECT IDENTIFIER ::=
{ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
pkcs9(9) smime(16) alg(3) 18 }
AEADChaCha20Poly1305Nonce ::= OCTET STRING (SIZE(12))
id-alg-hss-lms-hashsig OBJECT IDENTIFIER ::= { iso(1)
member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
smime(16) alg(3) 17 }
PKCS#9: 1.2.840.113549.1.9.16.2.37 - RFC 4108
PKCS#9: 1.2.840.113549.1.9.16.2.38 - RFC 4108
PKCS#9: 1.2.840.113549.1.9.16.2.54 RFC7030
PKCS#9: 1.2.840.113549.1.9.16.2.43 RFC7030
PKCS#9: 1.2.840.113549.1.9.16.2.40 RFC7030
RFC 5958
[IMPLICIT TAGS]
OneAsymmetricKey ::= SEQUENCE {
version Version,
privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
privateKey PrivateKey,
attributes [0] Attributes OPTIONAL,
...,
[[2: publicKey [1] PublicKey OPTIONAL ]],
...
}
PrivateKeyInfo ::= OneAsymmetricKey
Version ::= INTEGER { v1(0), v2(1) } (v1, ..., v2)
PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
{ PUBLIC-KEY,
{ PrivateKeyAlgorithms } }
PrivateKey ::= OCTET STRING
-- Content varies based on type of key. The
-- algorithm identifier dictates the format of
-- the key.
PublicKey ::= BIT STRING
-- Content varies based on type of key. The
-- algorithm identifier dictates the format of
-- the key.
Attributes ::= SET OF Attribute { { OneAsymmetricKeyAttributes } }
Return true if a public key is present, false otherwise.
For when the public key is an ASN.1 encoding.
Return the public key as a raw bit string.
The default version
RSAES-OAEP-params ::= SEQUENCE {
hashAlgorithm [0] OAEP-PSSDigestAlgorithms DEFAULT sha1,
maskGenAlgorithm [1] PKCS1MGFAlgorithms DEFAULT mgf1SHA1,
pSourceAlgorithm [2] PKCS1PSourceAlgorithms DEFAULT pSpecifiedEmpty
}
OAEP-PSSDigestAlgorithms ALGORITHM-IDENTIFIER ::= {
{ OID id-sha1 PARAMETERS NULL }|
{ OID id-sha256 PARAMETERS NULL }|
{ OID id-sha384 PARAMETERS NULL }|
{ OID id-sha512 PARAMETERS NULL },
... -- Allows for future expansion --
}
PKCS1MGFAlgorithms ALGORITHM-IDENTIFIER ::= {
{ OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
... -- Allows for future expansion --
}
PKCS1PSourceAlgorithms ALGORITHM-IDENTIFIER ::= {
{ OID id-pSpecified PARAMETERS OCTET STRING },
... -- Allows for future expansion --
}
@return the asn1 primitive representing the parameters.
This outputs the key in Pkcs1v2 format.
RsaPrivateKey ::= Sequence {
version Version,
modulus Integer, -- n
publicExponent Integer, -- e
privateExponent Integer, -- d
prime1 Integer, -- p
prime2 Integer, -- q
exponent1 Integer, -- d mod (p-1)
exponent2 Integer, -- d mod (q-1)
coefficient Integer -- (inverse of q) mod p
}
Version ::= Integer
This routine is written to output Pkcs1 version 0, private keys.
The default version
RSASSA-PSS-params ::= SEQUENCE {
hashAlgorithm [0] OAEP-PSSDigestAlgorithms DEFAULT sha1,
maskGenAlgorithm [1] PKCS1MGFAlgorithms DEFAULT mgf1SHA1,
saltLength [2] INTEGER DEFAULT 20,
trailerField [3] TrailerField DEFAULT trailerFieldBC
}
OAEP-PSSDigestAlgorithms ALGORITHM-IDENTIFIER ::= {
{ OID id-sha1 PARAMETERS NULL }|
{ OID id-sha256 PARAMETERS NULL }|
{ OID id-sha384 PARAMETERS NULL }|
{ OID id-sha512 PARAMETERS NULL },
... -- Allows for future expansion --
}
PKCS1MGFAlgorithms ALGORITHM-IDENTIFIER ::= {
{ OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
... -- Allows for future expansion --
}
TrailerField ::= INTEGER { trailerFieldBC(1) }
@return the asn1 primitive representing the parameters.
a Pkcs#7 signed data object.
Produce an object suitable for an Asn1OutputStream.
SignedData ::= Sequence {
version Version,
digestAlgorithms DigestAlgorithmIdentifiers,
contentInfo ContentInfo,
certificates
[0] IMPLICIT ExtendedCertificatesAndCertificates
OPTIONAL,
crls
[1] IMPLICIT CertificateRevocationLists OPTIONAL,
signerInfos SignerInfos }
a Pkcs#7 signer info object.
Produce an object suitable for an Asn1OutputStream.
SignerInfo ::= Sequence {
version Version,
issuerAndSerialNumber IssuerAndSerialNumber,
digestAlgorithm DigestAlgorithmIdentifier,
authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
encryptedDigest EncryptedDigest,
unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
}
EncryptedDigest ::= OCTET STRING
DigestAlgorithmIdentifier ::= AlgorithmIdentifier
DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
the elliptic curve private key object from SEC 1
ECPrivateKey ::= SEQUENCE {
version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
privateKey OCTET STRING,
parameters [0] Parameters OPTIONAL,
publicKey [1] BIT STRING OPTIONAL }
Elliptic curve registry for the SEC standard.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
EllipticCurve OBJECT IDENTIFIER ::= {
iso(1) identified-organization(3) certicom(132) curve(0)
}
Handler class for dealing with S/MIME Capabilities
general preferences
encryption algorithms preferences
return an Attr object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
returns an ArrayList with 0 or more objects of all the capabilities
matching the passed in capability Oid. If the Oid passed is null the
entire set is returned.
Produce an object suitable for an Asn1OutputStream.
SMIMECapabilities ::= Sequence OF SMIMECapability
general preferences
encryption algorithms preferences
Produce an object suitable for an Asn1OutputStream.
SMIMECapability ::= Sequence {
capabilityID OBJECT IDENTIFIER,
parameters ANY DEFINED BY capabilityID OPTIONAL
}
Handler for creating a vector S/MIME Capabilities
The SmimeEncryptionKeyPreference object.
SmimeEncryptionKeyPreference ::= CHOICE {
issuerAndSerialNumber [0] IssuerAndSerialNumber,
receipentKeyId [1] RecipientKeyIdentifier,
subjectAltKeyIdentifier [2] SubjectKeyIdentifier
}
@param sKeyId the subjectKeyIdentifier value (normally the X.509 one)
Elliptic curve registry for curves defined in "ECC Brainpool Standard Curves and Curve Generation"
http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt .
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
Accuracy ::= SEQUENCE {
seconds INTEGER OPTIONAL,
millis [0] INTEGER (1..999) OPTIONAL,
micros [1] INTEGER (1..999) OPTIONAL
}
MessageImprint ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
hashedMessage OCTET STRING }
TimeStampReq ::= SEQUENCE {
version INTEGER { v1(1) },
messageImprint MessageImprint,
--a hash algorithm OID and the hash value of the data to be
--time-stamped
reqPolicy TSAPolicyId OPTIONAL,
nonce INTEGER OPTIONAL,
certReq BOOLEAN DEFAULT FALSE,
extensions [0] IMPLICIT Extensions OPTIONAL
}
TimeStampResp ::= SEQUENCE {
status PkiStatusInfo,
timeStampToken TimeStampToken OPTIONAL }
TstInfo ::= SEQUENCE {
version INTEGER { v1(1) },
policy TSAPolicyId,
messageImprint MessageImprint,
-- MUST have the same value as the similar field in
-- TimeStampReq
serialNumber INTEGER,
-- Time-Stamping users MUST be ready to accommodate integers
-- up to 160 bits.
genTime GeneralizedTime,
accuracy Accuracy OPTIONAL,
ordering BOOLEAN DEFAULT FALSE,
nonce INTEGER OPTIONAL,
-- MUST be present if the similar field was present
-- in TimeStampReq. In that case it MUST have the same value.
tsa [0] GeneralName OPTIONAL,
extensions [1] IMPLICIT Extensions OPTIONAL }
Ukrainian object identifiers
{iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)}
{ ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)}
DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian
Base OID: 1.2.804.2.1.1.1
DSTU4145 Little Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1
DSTU4145 Big Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1.1
DSTU7564 256-bit digest presentation.
DSTU7564 384-bit digest presentation.
DSTU7564 512-bit digest presentation.
DSTU7564 256-bit mac presentation.
DSTU7564 384-bit mac presentation.
DSTU7564 512-bit mac presentation.
DSTU7624 in ECB mode with 128 bit block/key presentation
DSTU7624 in ECB mode with 256 bit block/key presentation
DSTU7624 in ECB mode with 512 bit block/key presentation
DSTU7624 in CTR mode with 128 bit block/key presentation
DSTU7624 in CTR mode with 256 bit block/key presentation
DSTU7624 in CTR mode with 512 bit block/key presentation
DSTU7624 in CFB mode with 128 bit block/key presentation
DSTU7624 in CFB mode with 256 bit block/key presentation
DSTU7624 in CFB mode with 512 bit block/key presentation
DSTU7624 in MAC mode with 128 bit block/key presentation
DSTU7624 in MAC mode with 256 bit block/key presentation
DSTU7624 in MAC mode with 512 bit block/key presentation
DSTU7624 in CBC mode with 128 bit block/key presentation
DSTU7624 in CBC mode with 256 bit block/key presentation
DSTU7624 in CBC mode with 512 bit block/key presentation
DSTU7624 in OFB mode with 128 bit block/key presentation
DSTU7624 in OFB mode with 256 bit block/key presentation
DSTU7624 in OFB mode with 512 bit block/key presentation
DSTU7624 in GMAC (GCM witout encryption) mode with 128 bit block/key presentation
DSTU7624 in GMAC (GCM witout encryption) mode with 256 bit block/key presentation
DSTU7624 in GMAC (GCM witout encryption) mode with 512 bit block/key presentation
DSTU7624 in CCM mode with 128 bit block/key presentation
DSTU7624 in CCM mode with 256 bit block/key presentation
DSTU7624 in CCM mode with 512 bit block/key presentation
DSTU7624 in XTS mode with 128 bit block/key presentation
DSTU7624 in XTS mode with 256 bit block/key presentation
DSTU7624 in XTS mode with 512 bit block/key presentation
DSTU7624 in key wrap (KW) mode with 128 bit block/key presentation
DSTU7624 in key wrap (KW) mode with 256 bit block/key presentation
DSTU7624 in key wrap (KW) mode with 512 bit block/key presentation
dump a Der object as a formatted string with indentation
@param obj the Asn1Object to be dumped out.
Parse ASN.1 objects from input , and write them to the output.
dump out a DER object as a formatted string, in non-verbose mode
@param obj the Asn1Encodable to be dumped out.
@return the resulting string.
Dump out the object as a string
@param obj the Asn1Encodable to be dumped out.
@param verbose if true, dump out the contents of octet and bit strings.
@return the resulting string.
Holding class for the AttributeTypeAndValue structures that make up an RDN.
AttributeTypeAndValue ::= SEQUENCE {
type OBJECT IDENTIFIER,
value ANY DEFINED BY type }
@return a basic ASN.1 object representation.
DirectoryString ::= CHOICE {
teletexString TeletexString (SIZE (1..MAX)),
printableString PrintableString (SIZE (1..MAX)),
universalString UniversalString (SIZE (1..MAX)),
utf8String UTF8String (SIZE (1..MAX)),
bmpString BMPString (SIZE (1..MAX)) }
Holding class for a single Relative Distinguished Name (RDN).
Create a single valued RDN.
@param oid RDN type.
@param value RDN value.
Create a multi-valued RDN.
@param aAndVs attribute type/value pairs making up the RDN
Return the number of AttributeTypeAndValue objects in this RDN,
@return size of RDN, greater than 1 if multi-valued.
*
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* @return this object as its ASN1Primitive type
The AccessDescription object.
AccessDescription ::= SEQUENCE {
accessMethod OBJECT IDENTIFIER,
accessLocation GeneralName }
create an AccessDescription with the oid and location provided.
@return the access method.
@return the access location
Return the OID in the Algorithm entry of this identifier.
Return the parameters structure in the Parameters entry of this identifier.
Produce an object suitable for an Asn1OutputStream.
AlgorithmIdentifier ::= Sequence {
algorithm OBJECT IDENTIFIER,
parameters ANY DEFINED BY algorithm OPTIONAL }
Don't use this one if you are trying to be RFC 3281 compliant.
Use it for v1 attribute certificates only.
Our GeneralNames structure
Produce an object suitable for an Asn1OutputStream.
AttCertIssuer ::= CHOICE {
v1Form GeneralNames, -- MUST NOT be used in this
-- profile
v2Form [0] V2Form -- v2 only
}
Produce an object suitable for an Asn1OutputStream.
AttCertValidityPeriod ::= Sequence {
notBeforeTime GeneralizedTime,
notAfterTime GeneralizedTime
}
return an Attr object from the given object.
@param o the object we want converted.
@exception ArgumentException if the object cannot be converted.
Produce an object suitable for an Asn1OutputStream.
Attr ::= Sequence {
attrType OBJECT IDENTIFIER,
attrValues Set OF AttributeValue
}
@param obj
@return
Produce an object suitable for an Asn1OutputStream.
AttributeCertificate ::= Sequence {
acinfo AttributeCertificateInfo,
signatureAlgorithm AlgorithmIdentifier,
signatureValue BIT STRING
}
Produce an object suitable for an Asn1OutputStream.
AttributeCertificateInfo ::= Sequence {
version AttCertVersion -- version is v2,
holder Holder,
issuer AttCertIssuer,
signature AlgorithmIdentifier,
serialNumber CertificateSerialNumber,
attrCertValidityPeriod AttCertValidityPeriod,
attributes Sequence OF Attr,
issuerUniqueID UniqueIdentifier OPTIONAL,
extensions Extensions OPTIONAL
}
AttCertVersion ::= Integer { v2(1) }
The AuthorityInformationAccess object.
id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
AuthorityInfoAccessSyntax ::=
Sequence SIZE (1..MAX) OF AccessDescription
AccessDescription ::= Sequence {
accessMethod OBJECT IDENTIFIER,
accessLocation GeneralName }
id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 }
id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 }
create an AuthorityInformationAccess with the oid and location provided.
The AuthorityKeyIdentifier object.
id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 }
AuthorityKeyIdentifier ::= Sequence {
keyIdentifier [0] IMPLICIT KeyIdentifier OPTIONAL,
authorityCertIssuer [1] IMPLICIT GeneralNames OPTIONAL,
authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL }
KeyIdentifier ::= OCTET STRING
*
* Calulates the keyidentifier using a SHA1 hash over the BIT STRING
* from SubjectPublicKeyInfo as defined in RFC2459.
*
* Example of making a AuthorityKeyIdentifier:
*
* SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(
* publicKey.getEncoded()).readObject());
* AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
*
*
*
create an AuthorityKeyIdentifier with the GeneralNames tag and
the serial number provided as well.
create an AuthorityKeyIdentifier with the GeneralNames tag and
the serial number provided.
create an AuthorityKeyIdentifier with a precomputed key identifier
create an AuthorityKeyIdentifier with a precomupted key identifier
and the GeneralNames tag and the serial number provided as well.
Produce an object suitable for an Asn1OutputStream.
create a cA=true object for the given path length constraint.
@param pathLenConstraint
Produce an object suitable for an Asn1OutputStream.
BasicConstraints := Sequence {
cA Boolean DEFAULT FALSE,
pathLenConstraint Integer (0..MAX) OPTIONAL
}
PKIX RFC-2459
The X.509 v2 CRL syntax is as follows. For signature calculation,
the data that is to be signed is ASN.1 Der encoded.
CertificateList ::= Sequence {
tbsCertList TbsCertList,
signatureAlgorithm AlgorithmIdentifier,
signatureValue BIT STRING }
This class helps to support crossCerfificatePairs in a LDAP directory
according RFC 2587
crossCertificatePairATTRIBUTE::={
WITH SYNTAX CertificatePair
EQUALITY MATCHING RULE certificatePairExactMatch
ID joint-iso-ccitt(2) ds(5) attributeType(4) crossCertificatePair(40)}
The forward elements of the crossCertificatePair attribute of a
CA's directory entry shall be used to store all, except self-issued
certificates issued to this CA. Optionally, the reverse elements of the
crossCertificatePair attribute, of a CA's directory entry may contain a
subset of certificates issued by this CA to other CAs. When both the forward
and the reverse elements are present in a single attribute value, issuer name
in one certificate shall match the subject name in the other and vice versa,
and the subject public key in one certificate shall be capable of verifying
the digital signature on the other certificate and vice versa.
When a reverse element is present, the forward element value and the reverse
element value need not be stored in the same attribute value; in other words,
they can be stored in either a single attribute value or two attribute
values.
CertificatePair ::= SEQUENCE {
forward [0] Certificate OPTIONAL,
reverse [1] Certificate OPTIONAL,
-- at least one of the pair shall be present -- }
Constructor from Asn1Sequence.
The sequence is of type CertificatePair:
CertificatePair ::= SEQUENCE {
forward [0] Certificate OPTIONAL,
reverse [1] Certificate OPTIONAL,
-- at least one of the pair shall be present -- }
@param seq The ASN.1 sequence.
Constructor from a given details.
@param forward Certificates issued to this CA.
@param reverse Certificates issued by this CA to other CAs.
Produce an object suitable for an Asn1OutputStream.
Returns:
CertificatePair ::= SEQUENCE {
forward [0] Certificate OPTIONAL,
reverse [1] Certificate OPTIONAL,
-- at least one of the pair shall be present -- }
@return a DERObject
@return Returns the forward.
@return Returns the reverse.
Construct a CertificatePolicies object containing one PolicyInformation.
@param name the name to be contained.
Produce an object suitable for an ASN1OutputStream.
CertificatePolicies ::= SEQUENCE SIZE {1..MAX} OF PolicyInformation
CertPolicyId, used in the CertificatePolicies and PolicyMappings
X509V3 Extensions.
CertPolicyId ::= OBJECT IDENTIFIER
Return the distribution points making up the sequence.
@return DistributionPoint[]
Produce an object suitable for an Asn1OutputStream.
CrlDistPoint ::= Sequence SIZE {1..MAX} OF DistributionPoint
The CRLNumber object.
CRLNumber::= Integer(0..MAX)
The CRLReason enumeration.
CRLReason ::= Enumerated {
unspecified (0),
keyCompromise (1),
cACompromise (2),
affiliationChanged (3),
superseded (4),
cessationOfOperation (5),
certificateHold (6),
removeFromCRL (8),
privilegeWithdrawn (9),
aACompromise (10)
}
The DigestInfo object.
DigestInfo::=Sequence{
digestAlgorithm AlgorithmIdentifier,
digest OCTET STRING }
DisplayText
class, used in
CertificatePolicies
X509 V3 extensions (in policy qualifiers).
It stores a string in a chosen encoding.
DisplayText ::= CHOICE {
ia5String IA5String (SIZE (1..200)),
visibleString VisibleString (SIZE (1..200)),
bmpString BMPString (SIZE (1..200)),
utf8String UTF8String (SIZE (1..200)) }
@see PolicyQualifierInfo
@see PolicyInformation
Constant corresponding to ia5String encoding.
Constant corresponding to bmpString encoding.
Constant corresponding to utf8String encoding.
Constant corresponding to visibleString encoding.
Describe constant DisplayTextMaximumSize
here.
Creates a new DisplayText
instance.
@param type the desired encoding type for the text.
@param text the text to store. Strings longer than 200
characters are truncated.
Creates a new DisplayText
instance.
@param text the text to encapsulate. Strings longer than 200
characters are truncated.
Creates a new DisplayText
instance.
Useful when reading back a DisplayText
class
from it's Asn1Encodable form.
@param contents an Asn1Encodable
instance.
Returns the stored string
object.
@return the stored text as a string
.
The DistributionPoint object.
DistributionPoint ::= Sequence {
distributionPoint [0] DistributionPointName OPTIONAL,
reasons [1] ReasonFlags OPTIONAL,
cRLIssuer [2] GeneralNames OPTIONAL
}
The DistributionPointName object.
DistributionPointName ::= CHOICE {
fullName [0] GeneralNames,
nameRelativeToCRLIssuer [1] RDN
}
The extendedKeyUsage object.
extendedKeyUsage ::= Sequence SIZE (1..MAX) OF KeyPurposeId
Returns all extended key usages.
The returned ArrayList contains DerObjectIdentifier instances.
@return An ArrayList with all key purposes.
The GeneralName object.
GeneralName ::= CHOICE {
otherName [0] OtherName,
rfc822Name [1] IA5String,
dNSName [2] IA5String,
x400Address [3] ORAddress,
directoryName [4] Name,
ediPartyName [5] EDIPartyName,
uniformResourceIdentifier [6] IA5String,
iPAddress [7] OCTET STRING,
registeredID [8] OBJECT IDENTIFIER}
OtherName ::= Sequence {
type-id OBJECT IDENTIFIER,
value [0] EXPLICIT ANY DEFINED BY type-id }
EDIPartyName ::= Sequence {
nameAssigner [0] DirectoryString OPTIONAL,
partyName [1] DirectoryString }
When the subjectAltName extension contains an Internet mail address,
the address MUST be included as an rfc822Name. The format of an
rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
When the subjectAltName extension contains a domain name service
label, the domain name MUST be stored in the dNSName (an IA5String).
The name MUST be in the "preferred name syntax," as specified by RFC
1034 [RFC 1034].
When the subjectAltName extension contains a URI, the name MUST be
stored in the uniformResourceIdentifier (an IA5String). The name MUST
be a non-relative URL, and MUST follow the URL syntax and encoding
rules specified in [RFC 1738]. The name must include both a scheme
(e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
specific-part must include a fully qualified domain name or IP
address as the host.
When the subjectAltName extension contains a iPAddress, the address
MUST be stored in the octet string in "network byte order," as
specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
each octet is the LSB of the corresponding byte in the network
address. For IP Version 4, as specified in RFC 791, the octet string
MUST contain exactly four octets. For IP Version 6, as specified in
RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
1883].
Create a GeneralName for the given tag from the passed in string.
This constructor can handle:
- rfc822Name
- iPAddress
- directoryName
- dNSName
- uniformResourceIdentifier
- registeredID
For x400Address, otherName and ediPartyName there is no common string
format defined.
Note: A directory name can be encoded in different ways into a byte
representation. Be aware of this if the byte representation is used for
comparing results.
@param tag tag number
@param name string representation of name
@throws ArgumentException if the string encoding is not correct or
not supported.
Construct a GeneralNames object containing one GeneralName.
The name to be contained.
Produce an object suitable for an Asn1OutputStream.
GeneralNames ::= Sequence SIZE {1..MAX} OF GeneralName
Class for containing a restriction object subtrees in NameConstraints. See
RFC 3280.
GeneralSubtree ::= SEQUENCE
{
baseName GeneralName,
minimum [0] BaseDistance DEFAULT 0,
maximum [1] BaseDistance OPTIONAL
}
@see org.bouncycastle.asn1.x509.NameConstraints
Constructor from a given details.
According RFC 3280, the minimum and maximum fields are not used with any
name forms, thus minimum MUST be zero, and maximum MUST be absent.
If minimum is null
, zero is assumed, if
maximum is null
, maximum is absent.
@param baseName
A restriction.
@param minimum
Minimum
@param maximum
Maximum
Produce an object suitable for an Asn1OutputStream.
Returns:
GeneralSubtree ::= SEQUENCE
{
baseName GeneralName,
minimum [0] BaseDistance DEFAULT 0,
maximum [1] BaseDistance OPTIONAL
}
@return a DERObject
The Holder object.
For an v2 attribute certificate this is:
Holder ::= SEQUENCE {
baseCertificateID [0] IssuerSerial OPTIONAL,
-- the issuer and serial number of
-- the holder's Public Key Certificate
entityName [1] GeneralNames OPTIONAL,
-- the name of the claimant or role
objectDigestInfo [2] ObjectDigestInfo OPTIONAL
-- used to directly authenticate the holder,
-- for example, an executable
}
For an v1 attribute certificate this is:
subject CHOICE {
baseCertificateID [0] EXPLICIT IssuerSerial,
-- associated with a Public Key Certificate
subjectName [1] EXPLICIT GeneralNames },
-- associated with a name
Constructor for a holder for an v1 attribute certificate.
@param tagObj The ASN.1 tagged holder object.
Constructor for a holder for an v2 attribute certificate. *
@param seq The ASN.1 sequence.
Constructs a holder from a IssuerSerial.
@param baseCertificateID The IssuerSerial.
@param version The version of the attribute certificate.
Returns 1 for v2 attribute certificates or 0 for v1 attribute
certificates.
@return The version of the attribute certificate.
Constructs a holder with an entityName for v2 attribute certificates or
with a subjectName for v1 attribute certificates.
@param entityName The entity or subject name.
Constructs a holder with an entityName for v2 attribute certificates or
with a subjectName for v1 attribute certificates.
@param entityName The entity or subject name.
@param version The version of the attribute certificate.
Constructs a holder from an object digest info.
@param objectDigestInfo The object digest info object.
Returns the entityName for an v2 attribute certificate or the subjectName
for an v1 attribute certificate.
@return The entityname or subjectname.
The Holder object.
Holder ::= Sequence {
baseCertificateID [0] IssuerSerial OPTIONAL,
-- the issuer and serial number of
-- the holder's Public Key Certificate
entityName [1] GeneralNames OPTIONAL,
-- the name of the claimant or role
objectDigestInfo [2] ObjectDigestInfo OPTIONAL
-- used to directly authenticate the holder,
-- for example, an executable
}
Implementation of IetfAttrSyntax
as specified by RFC3281.
IetfAttrSyntax ::= Sequence {
policyAuthority [0] GeneralNames OPTIONAL,
values Sequence OF CHOICE {
octets OCTET STRING,
oid OBJECT IDENTIFIER,
string UTF8String
}
}
Produce an object suitable for an Asn1OutputStream.
IssuerSerial ::= Sequence {
issuer GeneralNames,
serial CertificateSerialNumber,
issuerUid UniqueIdentifier OPTIONAL
}
IssuingDistributionPoint ::= SEQUENCE {
distributionPoint [0] DistributionPointName OPTIONAL,
onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE,
onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
onlySomeReasons [3] ReasonFlags OPTIONAL,
indirectCRL [4] BOOLEAN DEFAULT FALSE,
onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE }
Constructor from given details.
@param distributionPoint
May contain an URI as pointer to most current CRL.
@param onlyContainsUserCerts Covers revocation information for end certificates.
@param onlyContainsCACerts Covers revocation information for CA certificates.
@param onlySomeReasons
Which revocation reasons does this point cover.
@param indirectCRL
If true
then the CRL contains revocation
information about certificates ssued by other CAs.
@param onlyContainsAttributeCerts Covers revocation information for attribute certificates.
Constructor from Asn1Sequence
@return Returns the distributionPoint.
@return Returns the onlySomeReasons.
The KeyPurposeID object.
KeyPurposeID ::= OBJECT IDENTIFIER
Microsoft Server Gated Crypto (msSGC).
see https://www.alvestrand.no/objectid/1.3.6.1.4.1.311.10.3.3.html
Netscape Server Gated Crypto (nsSGC).
see https://www.alvestrand.no/objectid/2.16.840.1.113730.4.1.html
The KeyUsage object.
id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
KeyUsage ::= BIT STRING {
digitalSignature (0),
nonRepudiation (1),
keyEncipherment (2),
dataEncipherment (3),
keyAgreement (4),
keyCertSign (5),
cRLSign (6),
encipherOnly (7),
decipherOnly (8) }
Basic constructor.
@param usage - the bitwise OR of the Key Usage flags giving the
allowed uses for the key.
e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)
Constructor from a given details.
permitted and excluded are Vectors of GeneralSubtree objects.
@param permitted Permitted subtrees
@param excluded Excluded subtrees
NoticeReference
class, used in
CertificatePolicies
X509 V3 extensions
(in policy qualifiers).
NoticeReference ::= Sequence {
organization DisplayText,
noticeNumbers Sequence OF Integer }
@see PolicyQualifierInfo
@see PolicyInformation
Creates a new NoticeReference
instance.
@param organization a String
value
@param numbers a Vector
value
Creates a new NoticeReference
instance.
@param organization a String
value
@param noticeNumbers an ASN1EncodableVector
value
Creates a new NoticeReference
instance.
@param organization displayText
@param noticeNumbers an ASN1EncodableVector
value
Creates a new NoticeReference
instance.
Useful for reconstructing a NoticeReference
instance from its encodable/encoded form.
@param as an Asn1Sequence
value obtained from either
calling @{link ToAsn1Object()} for a NoticeReference
instance or from parsing it from a Der-encoded stream.
Describe ToAsn1Object
method here.
@return a Asn1Object
value
ObjectDigestInfo ASN.1 structure used in v2 attribute certificates.
ObjectDigestInfo ::= SEQUENCE {
digestedObjectType ENUMERATED {
publicKey (0),
publicKeyCert (1),
otherObjectTypes (2) },
-- otherObjectTypes MUST NOT
-- be used in this profile
otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
digestAlgorithm AlgorithmIdentifier,
objectDigest BIT STRING
}
The public key is hashed.
The public key certificate is hashed.
An other object is hashed.
Constructor from given details.
If digestedObjectType
is not {@link #publicKeyCert} or
{@link #publicKey} otherObjectTypeID
must be given,
otherwise it is ignored.
@param digestedObjectType The digest object type.
@param otherObjectTypeID The object type ID for
otherObjectDigest
.
@param digestAlgorithm The algorithm identifier for the hash.
@param objectDigest The hash value.
Produce an object suitable for an Asn1OutputStream.
ObjectDigestInfo ::= SEQUENCE {
digestedObjectType ENUMERATED {
publicKey (0),
publicKeyCert (1),
otherObjectTypes (2) },
-- otherObjectTypes MUST NOT
-- be used in this profile
otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
digestAlgorithm AlgorithmIdentifier,
objectDigest BIT STRING
}
The OtherName object.
OtherName ::= SEQUENCE {
type-id OBJECT IDENTIFIER,
value [0] EXPLICIT ANY DEFINED BY type-id }
OtherName factory method.
@param obj the object used to construct an instance of
OtherName
. It must be an instance of OtherName
or ASN1Sequence
.
@return the instance of OtherName
built from the
supplied object.
@throws java.lang.IllegalArgumentException if the object passed
to the factory is not an instance of OtherName
or something that
can be converted into an appropriate ASN1Sequence
.
Base constructor.
@param typeID the type of the other name.
@param value the ANY object that represents the value.
PolicyMappings V3 extension, described in RFC3280.
PolicyMappings ::= Sequence SIZE (1..MAX) OF Sequence {
issuerDomainPolicy CertPolicyId,
subjectDomainPolicy CertPolicyId }
@see RFC 3280, section 4.2.1.6
Creates a new PolicyMappings
instance.
@param seq an Asn1Sequence
constructed as specified
in RFC 3280
Creates a new PolicyMappings
instance.
@param mappings a HashMap
value that maps
string
oids
to other string
oids.
PolicyQualifierId, used in the CertificatePolicies
X509V3 extension.
id-qt OBJECT IDENTIFIER ::= { id-pkix 2 }
id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 }
id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 }
PolicyQualifierId ::=
OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
Policy qualifiers, used in the X509V3 CertificatePolicies
extension.
PolicyQualifierInfo ::= Sequence {
policyQualifierId PolicyQualifierId,
qualifier ANY DEFINED BY policyQualifierId }
Creates a new PolicyQualifierInfo
instance.
@param policyQualifierId a PolicyQualifierId
value
@param qualifier the qualifier, defined by the above field.
Creates a new PolicyQualifierInfo
containing a
cPSuri qualifier.
@param cps the CPS (certification practice statement) uri as a
string
.
Creates a new PolicyQualifierInfo
instance.
@param as PolicyQualifierInfo
X509 structure
encoded as an Asn1Sequence.
Returns a Der-encodable representation of this instance.
@return a Asn1Object
value
PrivateKeyUsagePeriod ::= SEQUENCE
{
notBefore [0] GeneralizedTime OPTIONAL,
notAfter [1] GeneralizedTime OPTIONAL }
The BiometricData object.
BiometricData ::= SEQUENCE {
typeOfBiometricData TypeOfBiometricData,
hashAlgorithm AlgorithmIdentifier,
biometricDataHash OCTET STRING,
sourceDataUri IA5String OPTIONAL }
The Iso4217CurrencyCode object.
Iso4217CurrencyCode ::= CHOICE {
alphabetic PrintableString (SIZE 3), --Recommended
numeric INTEGER (1..999) }
-- Alphabetic or numeric currency code as defined in ISO 4217
-- It is recommended that the Alphabetic form is used
The MonetaryValue object.
MonetaryValue ::= SEQUENCE {
currency Iso4217CurrencyCode,
amount INTEGER,
exponent INTEGER }
-- value = amount * 10^exponent
The QCStatement object.
QCStatement ::= SEQUENCE {
statementId OBJECT IDENTIFIER,
statementInfo ANY DEFINED BY statementId OPTIONAL}
The SemanticsInformation object.
SemanticsInformation ::= SEQUENCE {
semanticsIdentifier OBJECT IDENTIFIER OPTIONAL,
nameRegistrationAuthorities NameRegistrationAuthorities
OPTIONAL }
(WITH COMPONENTS {..., semanticsIdentifier PRESENT}|
WITH COMPONENTS {..., nameRegistrationAuthorities PRESENT})
NameRegistrationAuthorities ::= SEQUENCE SIZE (1..MAX) OF
GeneralName
The TypeOfBiometricData object.
TypeOfBiometricData ::= CHOICE {
predefinedBiometricType PredefinedBiometricType,
biometricDataOid OBJECT IDENTIFIER }
PredefinedBiometricType ::= INTEGER {
picture(0),handwritten-signature(1)}
(picture|handwritten-signature)
The ReasonFlags object.
ReasonFlags ::= BIT STRING {
unused(0),
keyCompromise(1),
cACompromise(2),
affiliationChanged(3),
superseded(4),
cessationOfOperation(5),
certficateHold(6)
}
@param reasons - the bitwise OR of the Key Reason flags giving the
allowed uses for the key.
Implementation of the RoleSyntax object as specified by the RFC3281.
RoleSyntax ::= SEQUENCE {
roleAuthority [0] GeneralNames OPTIONAL,
roleName [1] GeneralName
}
RoleSyntax factory method.
@param obj the object used to construct an instance of
RoleSyntax
. It must be an instance of RoleSyntax
or Asn1Sequence
.
@return the instance of RoleSyntax
built from the
supplied object.
@throws java.lang.ArgumentException if the object passed
to the factory is not an instance of RoleSyntax
or
Asn1Sequence
.
Constructor.
@param roleAuthority the role authority of this RoleSyntax.
@param roleName the role name of this RoleSyntax.
Constructor. Invoking this constructor is the same as invoking
new RoleSyntax(null, roleName)
.
@param roleName the role name of this RoleSyntax.
Utility constructor. Takes a string
argument representing
the role name, builds a GeneralName
to hold the role name
and calls the constructor that takes a GeneralName
.
@param roleName
Constructor that builds an instance of RoleSyntax
by
extracting the encoded elements from the Asn1Sequence
object supplied.
@param seq an instance of Asn1Sequence
that holds
the encoded elements used to build this RoleSyntax
.
Gets the role authority of this RoleSyntax.
@return an instance of GeneralNames
holding the
role authority of this RoleSyntax.
Gets the role name of this RoleSyntax.
@return an instance of GeneralName
holding the
role name of this RoleSyntax.
Gets the role name as a java.lang.string
object.
@return the role name of this RoleSyntax represented as a
string
object.
Gets the role authority as a string[]
object.
@return the role authority of this RoleSyntax represented as a
string[]
array.
Implementation of the method ToAsn1Object
as
required by the superclass ASN1Encodable
.
RoleSyntax ::= SEQUENCE {
roleAuthority [0] GeneralNames OPTIONAL,
roleName [1] GeneralName
}
This outputs the key in Pkcs1v2 format.
RSAPublicKey ::= Sequence {
modulus Integer, -- n
publicExponent Integer, -- e
}
Structure for a name or pseudonym.
NameOrPseudonym ::= CHOICE {
surAndGivenName SEQUENCE {
surName DirectoryString,
givenName SEQUENCE OF DirectoryString
},
pseudonym DirectoryString
}
@see org.bouncycastle.asn1.x509.sigi.PersonalData
Constructor from DERString.
The sequence is of type NameOrPseudonym:
NameOrPseudonym ::= CHOICE {
surAndGivenName SEQUENCE {
surName DirectoryString,
givenName SEQUENCE OF DirectoryString
},
pseudonym DirectoryString
}
@param pseudonym pseudonym value to use.
Constructor from Asn1Sequence.
The sequence is of type NameOrPseudonym:
NameOrPseudonym ::= CHOICE {
surAndGivenName SEQUENCE {
surName DirectoryString,
givenName SEQUENCE OF DirectoryString
},
pseudonym DirectoryString
}
@param seq The ASN.1 sequence.
Constructor from a given details.
@param pseudonym The pseudonym.
Constructor from a given details.
@param surname The surname.
@param givenName A sequence of directory strings making up the givenName
Produce an object suitable for an Asn1OutputStream.
Returns:
NameOrPseudonym ::= CHOICE {
surAndGivenName SEQUENCE {
surName DirectoryString,
givenName SEQUENCE OF DirectoryString
},
pseudonym DirectoryString
}
@return an Asn1Object
Contains personal data for the otherName field in the subjectAltNames
extension.
PersonalData ::= SEQUENCE {
nameOrPseudonym NameOrPseudonym,
nameDistinguisher [0] INTEGER OPTIONAL,
dateOfBirth [1] GeneralizedTime OPTIONAL,
placeOfBirth [2] DirectoryString OPTIONAL,
gender [3] PrintableString OPTIONAL,
postalAddress [4] DirectoryString OPTIONAL
}
@see org.bouncycastle.asn1.x509.sigi.NameOrPseudonym
@see org.bouncycastle.asn1.x509.sigi.SigIObjectIdentifiers
Constructor from Asn1Sequence.
The sequence is of type NameOrPseudonym:
PersonalData ::= SEQUENCE {
nameOrPseudonym NameOrPseudonym,
nameDistinguisher [0] INTEGER OPTIONAL,
dateOfBirth [1] GeneralizedTime OPTIONAL,
placeOfBirth [2] DirectoryString OPTIONAL,
gender [3] PrintableString OPTIONAL,
postalAddress [4] DirectoryString OPTIONAL
}
@param seq The ASN.1 sequence.
Constructor from a given details.
@param nameOrPseudonym Name or pseudonym.
@param nameDistinguisher Name distinguisher.
@param dateOfBirth Date of birth.
@param placeOfBirth Place of birth.
@param gender Gender.
@param postalAddress Postal Address.
Produce an object suitable for an Asn1OutputStream.
Returns:
PersonalData ::= SEQUENCE {
nameOrPseudonym NameOrPseudonym,
nameDistinguisher [0] INTEGER OPTIONAL,
dateOfBirth [1] GeneralizedTime OPTIONAL,
placeOfBirth [2] DirectoryString OPTIONAL,
gender [3] PrintableString OPTIONAL,
postalAddress [4] DirectoryString OPTIONAL
}
@return an Asn1Object
Object Identifiers of SigI specifciation (German Signature Law
Interoperability specification).
Key purpose IDs for German SigI (Signature Interoperability
Specification)
Certificate policy IDs for German SigI (Signature Interoperability
Specification)
Other Name IDs for German SigI (Signature Interoperability Specification)
To be used for for the generation of directory service certificates.
ID for PersonalData
Certificate is conform to german signature law.
This extension may contain further X.500 attributes of the subject. See also
RFC 3039.
SubjectDirectoryAttributes ::= Attributes
Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
Attribute ::= SEQUENCE
{
type AttributeType
values SET OF AttributeValue
}
AttributeType ::= OBJECT IDENTIFIER
AttributeValue ::= ANY DEFINED BY AttributeType
@see org.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers.
Constructor from Asn1Sequence.
The sequence is of type SubjectDirectoryAttributes:
SubjectDirectoryAttributes ::= Attributes
Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
Attribute ::= SEQUENCE
{
type AttributeType
values SET OF AttributeValue
}
AttributeType ::= OBJECT IDENTIFIER
AttributeValue ::= ANY DEFINED BY AttributeType
@param seq
The ASN.1 sequence.
Constructor from an ArrayList of attributes.
The ArrayList consists of attributes of type {@link Attribute Attribute}
@param attributes The attributes.
Produce an object suitable for an Asn1OutputStream.
Returns:
SubjectDirectoryAttributes ::= Attributes
Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
Attribute ::= SEQUENCE
{
type AttributeType
values SET OF AttributeValue
}
AttributeType ::= OBJECT IDENTIFIER
AttributeValue ::= ANY DEFINED BY AttributeType
@return a DERObject
@return Returns the attributes.
The SubjectKeyIdentifier object.
SubjectKeyIdentifier::= OCTET STRING
Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
from SubjectPublicKeyInfo as defined in RFC3280.
@param spki the subject public key info.
Return a RFC 3280 type 1 key identifier. As in:
(1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
value of the BIT STRING subjectPublicKey (excluding the tag,
length, and number of unused bits).
@param keyInfo the key info object containing the subjectPublicKey field.
@return the key identifier.
Return a RFC 3280 type 2 key identifier. As in:
(2) The keyIdentifier is composed of a four bit type field with
the value 0100 followed by the least significant 60 bits of the
SHA-1 hash of the value of the BIT STRING subjectPublicKey.
@param keyInfo the key info object containing the subjectPublicKey field.
@return the key identifier.
The object that contains the public key stored in a certficate.
The GetEncoded() method in the public keys in the JCE produces a DER
encoded one of these.
for when the public key is an encoded object - if the bitstring
can't be decoded this routine raises an IOException.
@exception IOException - if the bit string doesn't represent a Der
encoded object.
for when the public key is raw bits...
Produce an object suitable for an Asn1OutputStream.
SubjectPublicKeyInfo ::= Sequence {
algorithm AlgorithmIdentifier,
publicKey BIT STRING }
Target structure used in target information extension for attribute
certificates from RFC 3281.
Target ::= CHOICE {
targetName [0] GeneralName,
targetGroup [1] GeneralName,
targetCert [2] TargetCert
}
The targetCert field is currently not supported and must not be used
according to RFC 3281.
Creates an instance of a Target from the given object.
obj
can be a Target or a {@link Asn1TaggedObject}
@param obj The object.
@return A Target instance.
@throws ArgumentException if the given object cannot be
interpreted as Target.
Constructor from Asn1TaggedObject.
@param tagObj The tagged object.
@throws ArgumentException if the encoding is wrong.
Constructor from given details.
Exactly one of the parameters must be not null
.
@param type the choice type to apply to the name.
@param name the general name.
@throws ArgumentException if type is invalid.
@return Returns the targetGroup.
@return Returns the targetName.
Produce an object suitable for an Asn1OutputStream.
Returns:
Target ::= CHOICE {
targetName [0] GeneralName,
targetGroup [1] GeneralName,
targetCert [2] TargetCert
}
@return an Asn1Object
Target information extension for attributes certificates according to RFC
3281.
SEQUENCE OF Targets
Creates an instance of a TargetInformation from the given object.
obj
can be a TargetInformation or a {@link Asn1Sequence}
@param obj The object.
@return A TargetInformation instance.
@throws ArgumentException if the given object cannot be interpreted as TargetInformation.
Constructor from a Asn1Sequence.
@param seq The Asn1Sequence.
@throws ArgumentException if the sequence does not contain
correctly encoded Targets elements.
Returns the targets in this target information extension.
The ArrayList is cloned before it is returned.
@return Returns the targets.
Constructs a target information from a single targets element.
According to RFC 3281 only one targets element must be produced.
@param targets A Targets instance.
According to RFC 3281 only one targets element must be produced. If
multiple targets are given they must be merged in
into one targets element.
@param targets An array with {@link Targets}.
Produce an object suitable for an Asn1OutputStream.
Returns:
SEQUENCE OF Targets
According to RFC 3281 only one targets element must be produced. If
multiple targets are given in the constructor they are merged into one
targets element. If this was produced from a
{@link Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.
@return an Asn1Object
Targets structure used in target information extension for attribute
certificates from RFC 3281.
Targets ::= SEQUENCE OF Target
Target ::= CHOICE {
targetName [0] GeneralName,
targetGroup [1] GeneralName,
targetCert [2] TargetCert
}
TargetCert ::= SEQUENCE {
targetCertificate IssuerSerial,
targetName GeneralName OPTIONAL,
certDigestInfo ObjectDigestInfo OPTIONAL
}
@see org.bouncycastle.asn1.x509.Target
@see org.bouncycastle.asn1.x509.TargetInformation
Creates an instance of a Targets from the given object.
obj
can be a Targets or a {@link Asn1Sequence}
@param obj The object.
@return A Targets instance.
@throws ArgumentException if the given object cannot be interpreted as Target.
Constructor from Asn1Sequence.
@param targets The ASN.1 SEQUENCE.
@throws ArgumentException if the contents of the sequence are
invalid.
Constructor from given targets.
The ArrayList is copied.
@param targets An ArrayList
of {@link Target}s.
@see Target
@throws ArgumentException if the ArrayList contains not only Targets.
Returns the targets in an ArrayList
.
The ArrayList is cloned before it is returned.
@return Returns the targets.
Produce an object suitable for an Asn1OutputStream.
Returns:
Targets ::= SEQUENCE OF Target
@return an Asn1Object
The TbsCertificate object.
TbsCertificate ::= Sequence {
version [ 0 ] Version DEFAULT v1(0),
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name,
validity Validity,
subject Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
issuerUniqueID [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
subjectUniqueID [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
extensions [ 3 ] Extensions OPTIONAL
}
Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
will parse them, but you really shouldn't be creating new ones.
PKIX RFC-2459 - TbsCertList object.
TbsCertList ::= Sequence {
version Version OPTIONAL,
-- if present, shall be v2
signature AlgorithmIdentifier,
issuer Name,
thisUpdate Time,
nextUpdate Time OPTIONAL,
revokedCertificates Sequence OF Sequence {
userCertificate CertificateSerialNumber,
revocationDate Time,
crlEntryExtensions Extensions OPTIONAL
-- if present, shall be v2
} OPTIONAL,
crlExtensions [0] EXPLICIT Extensions OPTIONAL
-- if present, shall be v2
}
creates a time object from a given date - if the date is between 1950
and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
is used.
Return our time as DateTime.
A date time.
Produce an object suitable for an Asn1OutputStream.
Time ::= CHOICE {
utcTime UTCTime,
generalTime GeneralizedTime }
UserNotice
class, used in
CertificatePolicies
X509 extensions (in policy
qualifiers).
UserNotice ::= Sequence {
noticeRef NoticeReference OPTIONAL,
explicitText DisplayText OPTIONAL}
@see PolicyQualifierId
@see PolicyInformation
Creates a new UserNotice
instance.
@param noticeRef a NoticeReference
value
@param explicitText a DisplayText
value
Creates a new UserNotice
instance.
@param noticeRef a NoticeReference
value
@param str the explicitText field as a string.
Generator for Version 1 TbsCertificateStructures.
TbsCertificate ::= Sequence {
version [ 0 ] Version DEFAULT v1(0),
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name,
validity Validity,
subject Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
}
Generator for Version 2 AttributeCertificateInfo
AttributeCertificateInfo ::= Sequence {
version AttCertVersion -- version is v2,
holder Holder,
issuer AttCertIssuer,
signature AlgorithmIdentifier,
serialNumber CertificateSerialNumber,
attrCertValidityPeriod AttCertValidityPeriod,
attributes Sequence OF Attr,
issuerUniqueID UniqueIdentifier OPTIONAL,
extensions Extensions OPTIONAL
}
@param attribute
Produce an object suitable for an Asn1OutputStream.
V2Form ::= Sequence {
issuerName GeneralNames OPTIONAL,
baseCertificateID [0] IssuerSerial OPTIONAL,
objectDigestInfo [1] ObjectDigestInfo OPTIONAL
-- issuerName MUST be present in this profile
-- baseCertificateID and objectDigestInfo MUST NOT
-- be present in this profile
}
Generator for Version 2 TbsCertList structures.
TbsCertList ::= Sequence {
version Version OPTIONAL,
-- if present, shall be v2
signature AlgorithmIdentifier,
issuer Name,
thisUpdate Time,
nextUpdate Time OPTIONAL,
revokedCertificates Sequence OF Sequence {
userCertificate CertificateSerialNumber,
revocationDate Time,
crlEntryExtensions Extensions OPTIONAL
-- if present, shall be v2
} OPTIONAL,
crlExtensions [0] EXPLICIT Extensions OPTIONAL
-- if present, shall be v2
}
Note: This class may be subject to change
Generator for Version 3 TbsCertificateStructures.
TbsCertificate ::= Sequence {
version [ 0 ] Version DEFAULT v1(0),
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name,
validity Validity,
subject Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
issuerUniqueID [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
subjectUniqueID [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
extensions [ 3 ] Extensions OPTIONAL
}
an X509Certificate structure.
Certificate ::= Sequence {
tbsCertificate TbsCertificate,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING
}
The default converter for X509 DN entries when going from their
string value to ASN.1 strings.
Apply default conversion for the given value depending on the oid
and the character range of the value.
@param oid the object identifier for the DN entry
@param value the value associated with it
@return the ASN.1 equivalent for the string value.
an object for the elements in the X.509 V3 extension block.
Convert the value of the passed in extension to an object.
The extension to parse.
The object the value string contains.
If conversion is not possible.
Subject Directory Attributes
Subject Key Identifier
Key Usage
Private Key Usage Period
Subject Alternative Name
Issuer Alternative Name
Basic Constraints
CRL Number
Reason code
Hold Instruction Code
Invalidity Date
Delta CRL indicator
Issuing Distribution Point
Certificate Issuer
Name Constraints
CRL Distribution Points
Certificate Policies
Policy Mappings
Authority Key Identifier
Policy Constraints
Extended Key Usage
Freshest CRL
Inhibit Any Policy
Authority Info Access
Subject Info Access
Logo Type
BiometricInfo
QCStatements
Audit identity extension in attribute certificates.
NoRevAvail extension in attribute certificates.
TargetInformation extension in attribute certificates.
Expired Certificates on CRL extension
Constructor from Asn1Sequence.
the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
constructor from a table of extensions.
it's is assumed the table contains Oid/string pairs.
Constructor from a table of extensions with ordering.
It's is assumed the table contains Oid/string pairs.
Constructor from two vectors
@param objectIDs an ArrayList of the object identifiers.
@param values an ArrayList of the extension values.
return an Enumeration of the extension field's object ids.
return the extension represented by the object identifier
passed in.
@return the extension if it's present, null otherwise.
return the parsed value of the extension represented by the object identifier
passed in.
@return the parsed value of the extension if it's present, null otherwise.
Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
Extension ::= SEQUENCE {
extnId EXTENSION.&id ({ExtensionSet}),
critical BOOLEAN DEFAULT FALSE,
extnValue OCTET STRING }
Generator for X.509 extensions
Reset the generator
Add an extension with the given oid and the passed in value to be included
in the OCTET STRING associated with the extension.
OID for the extension.
True if critical, false otherwise.
The ASN.1 object to be included in the extension.
Add an extension with the given oid and the passed in byte array to be wrapped
in the OCTET STRING associated with the extension.
OID for the extension.
True if critical, false otherwise.
The byte array to be wrapped.
Return true if there are no extension present in this generator.
True if empty, false otherwise
Generate an X509Extensions object based on the current state of the generator.
An X509Extensions object
RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
AttributeTypeAndValue ::= SEQUENCE {
type OBJECT IDENTIFIER,
value ANY }
country code - StringType(SIZE(2))
organization - StringType(SIZE(1..64))
organizational unit name - StringType(SIZE(1..64))
Title
common name - StringType(SIZE(1..64))
street - StringType(SIZE(1..64))
device serial number name - StringType(SIZE(1..64))
locality name - StringType(SIZE(1..64))
state, or province name - StringType(SIZE(1..64))
Naming attributes of type X520name
businessCategory - DirectoryString(SIZE(1..128)
postalCode - DirectoryString(SIZE(1..40)
dnQualifier - DirectoryString(SIZE(1..64)
RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
codes only
RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
codes only
ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
DirectoryString(SIZE(1..30))
RFC 2256 dmdName
id-at-telephoneNumber
id-at-organizationIdentifier
id-at-name
Email address (RSA PKCS#9 extension) - IA5String.
Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.
more from PKCS#9
email address in Verisign certificates
LDAP User id.
determines whether or not strings should be processed and printed
from back to front.
default look up table translating OID values into their common symbols following
the convention in RFC 2253 with a few extras
look up table translating OID values into their common symbols following the convention in RFC 2253
look up table translating OID values into their common symbols following the convention in RFC 1779
look up table translating common symbols into their OIDS.
Return a X509Name based on the passed in tagged object.
@param obj tag object holding name.
@param explicitly true if explicitly tagged false otherwise.
@return the X509Name
Constructor from Asn1Sequence
the principal will be a list of constructed sets, each containing an (OID, string) pair.
Constructor from a table of attributes with ordering.
it's is assumed the table contains OID/string pairs, and the contents
of the table are copied into an internal table as part of the
construction process. The ordering ArrayList should contain the OIDs
in the order they are meant to be encoded or printed in ToString.
Constructor from a table of attributes with ordering.
it's is assumed the table contains OID/string pairs, and the contents
of the table are copied into an internal table as part of the
construction process. The ordering ArrayList should contain the OIDs
in the order they are meant to be encoded or printed in ToString.
The passed in converter will be used to convert the strings into their
ASN.1 counterparts.
Takes two vectors one of the oids and the other of the values.
Takes two vectors one of the oids and the other of the values.
The passed in converter will be used to convert the strings into their
ASN.1 counterparts.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes with each
string value being converted to its associated ASN.1 type using the passed
in converter.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes. If reverse
is true, create the encoded version of the sequence starting from the
last element in the string.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes with each
string value being converted to its associated ASN.1 type using the passed
in converter. If reverse is true the ASN.1 sequence representing the DN will
be built by starting at the end of the string, rather than the start.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes. lookUp
should provide a table of lookups, indexed by lowercase only strings and
yielding a DerObjectIdentifier, other than that OID. and numeric oids
will be processed automatically.
If reverse is true, create the encoded version of the sequence
starting from the last element in the string.
@param reverse true if we should start scanning from the end (RFC 2553).
@param lookUp table of names and their oids.
@param dirName the X.500 string to be parsed.
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
some such, converting it into an ordered set of name attributes. lookUp
should provide a table of lookups, indexed by lowercase only strings and
yielding a DerObjectIdentifier, other than that OID. and numeric oids
will be processed automatically. The passed in converter is used to convert the
string values to the right of each equals sign to their ASN.1 counterparts.
@param reverse true if we should start scanning from the end, false otherwise.
@param lookUp table of names and oids.
@param dirName the string dirName
@param converter the converter to convert string values into their ASN.1 equivalents
return an IList of the oids in the name, in the order they were found.
return an IList of the values found in the name, in the order they
were found.
return an IList of the values found in the name, in the order they
were found, with the DN label corresponding to passed in oid.
The X509Name object to test equivalency against.
If true, the order of elements must be the same,
as well as the values associated with each element.
test for equivalence - note: case is ignored.
convert the structure to a string - if reverse is true the
oids and values are listed out starting with the last element
in the sequence (ala RFC 2253), otherwise the string will begin
with the first element of the structure. If no string definition
for the oid is found in oidSymbols the string value of the oid is
added. Two standard symbol tables are provided DefaultSymbols, and
RFC2253Symbols as part of this class.
@param reverse if true start at the end of the sequence and work back.
@param oidSymbols look up table strings for oids.
* It turns out that the number of standard ways the fields in a DN should be
* encoded into their ASN.1 counterparts is rapidly approaching the
* number of machines on the internet. By default the X509Name class
* will produce UTF8Strings in line with the current recommendations (RFC 3280).
*
* An example of an encoder look like below:
*
* public class X509DirEntryConverter
* : X509NameEntryConverter
* {
* public Asn1Object GetConvertedValue(
* DerObjectIdentifier oid,
* string value)
* {
* if (str.Length() != 0 && str.charAt(0) == '#')
* {
* return ConvertHexEncoded(str, 1);
* }
* if (oid.Equals(EmailAddress))
* {
* return new DerIA5String(str);
* }
* else if (CanBePrintable(str))
* {
* return new DerPrintableString(str);
* }
* else if (CanBeUTF8(str))
* {
* return new DerUtf8String(str);
* }
* else
* {
* return new DerBmpString(str);
* }
* }
* }
*
*
Convert an inline encoded hex string rendition of an ASN.1
object back into its corresponding ASN.1 object.
@param str the hex encoded object
@param off the index at which the encoding starts
@return the decoded object
return true if the passed in string can be represented without
loss as a PrintableString, false otherwise.
Convert the passed in string value into the appropriate ASN.1
encoded object.
@param oid the oid associated with the value in the DN.
@param value the value of the particular DN component.
@return the ASN.1 equivalent for the value.
class for breaking up an X500 Name into it's component tokens, ala
java.util.StringTokenizer. We need this class as some of the
lightweight Java environment don't support classes like
StringTokenizer.
A unified elliptic curve registry of the various standard-specific registries.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of
the full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of
the full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in all the registries.
ASN.1 def for Diffie-Hellman key exchange KeySpecificInfo structure. See
RFC 2631, or X9.42, for further details.
Produce an object suitable for an Asn1OutputStream.
KeySpecificInfo ::= Sequence {
algorithm OBJECT IDENTIFIER,
counter OCTET STRING SIZE (4..4)
}
ANS.1 def for Diffie-Hellman key exchange OtherInfo structure. See
RFC 2631, or X9.42, for further details.
Produce an object suitable for an Asn1OutputStream.
OtherInfo ::= Sequence {
keyInfo KeySpecificInfo,
partyAInfo [0] OCTET STRING OPTIONAL,
suppPubInfo [2] OCTET STRING
}
Elliptic curve registry for the curves defined in X.962 EC-DSA.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
Produce an object suitable for an Asn1OutputStream.
Parameters ::= CHOICE {
ecParameters ECParameters,
namedCurve CURVES.&id({CurveNames}),
implicitlyCA Null
}
ASN.1 def for Elliptic-Curve Curve structure. See
X9.62, for further details.
Produce an object suitable for an Asn1OutputStream.
Curve ::= Sequence {
a FieldElement,
b FieldElement,
seed BIT STRING OPTIONAL
}
ASN.1 def for Elliptic-Curve ECParameters structure. See
X9.62, for further details.
Return the ASN.1 entry representing the Curve.
@return the X9Curve for the curve in these parameters.
Return the ASN.1 entry representing the FieldID.
@return the X9FieldID for the FieldID in these parameters.
Return the ASN.1 entry representing the base point G.
@return the X9ECPoint for the base point in these parameters.
Produce an object suitable for an Asn1OutputStream.
ECParameters ::= Sequence {
version Integer { ecpVer1(1) } (ecpVer1),
fieldID FieldID {{FieldTypes}},
curve X9Curve,
base X9ECPoint,
order Integer,
cofactor Integer OPTIONAL
}
class for describing an ECPoint as a Der object.
Produce an object suitable for an Asn1OutputStream.
ECPoint ::= OCTET STRING
Octet string produced using ECPoint.GetEncoded().
Class for processing an ECFieldElement as a DER object.
Produce an object suitable for an Asn1OutputStream.
FieldElement ::= OCTET STRING
- if q is an odd prime then the field element is
processed as an Integer and converted to an octet string
according to x 9.62 4.3.1.
- if q is 2m then the bit string
contained in the field element is converted into an octet
string with the same ordering padded at the front if necessary.
ASN.1 def for Elliptic-Curve Field ID structure. See
X9.62, for further details.
Constructor for elliptic curves over prime fields
F2
.
@param primeP The prime p
defining the prime field.
Constructor for elliptic curves over binary fields
F2m
.
@param m The exponent m
of
F2m
.
@param k1 The integer k1
where xm +
xk1 + 1
represents the reduction polynomial f(z)
.
Constructor for elliptic curves over binary fields
F2m
.
@param m The exponent m
of
F2m
.
@param k1 The integer k1
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k2 The integer k2
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k3 The integer k3
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
..
Produce a Der encoding of the following structure.
FieldID ::= Sequence {
fieldType FIELD-ID.&id({IOSet}),
parameters FIELD-ID.&Type({IOSet}{@fieldType})
}
id-dsa-with-sha1 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
us(840) x9-57 (10040) x9cm(4) 3 }
X9.63
X9.42
reader for Base64 armored objects - read the headers and then start returning
bytes when the data is reached. An IOException is thrown if the CRC check
is detected and fails.
By default a missing CRC will not cause an exception. To force CRC detection use:
ArmoredInputStream aIn = ...
aIn.setDetectMissingCRC(true);
decode the base 64 encoded input data.
@return the offset the data starts in out.
Create a stream for reading a PGP armoured message, parsing up to a header
and then reading the data that follows.
@param input
Create an armoured input stream which will assume the data starts
straight away, or parse for headers first depending on the value of
hasHeaders.
@param input
@param hasHeaders true if headers are to be looked for, false otherwise.
@return true if we are inside the clear text section of a PGP
signed message.
@return true if the stream is actually at end of file.
Return the armor header line (if there is one)
@return the armor header line, null if none present.
Return the armor headers (the lines after the armor header line),
@return an array of armor headers, null if there aren't any.
Change how the stream should react if it encounters missing CRC checksum.
The default value is false (ignore missing CRC checksums). If the behavior is set to true,
an {@link IOException} will be thrown if a missing CRC checksum is encountered.
@param detectMissing ignore missing CRC sums
Basic output stream.
encode the input data producing a base 64 encoded byte array.
Set an additional header entry. Any current value(s) under the same name will be
replaced by the new one. A null value will clear the entry for name. *
@param name the name of the header entry.
@param v the value of the header entry.
Set an additional header entry. The current value(s) will continue to exist together
with the new one. Adding a null value has no effect.
@param name the name of the header entry.
@param value the value of the header entry.
Reset the headers to only contain a Version string (if one is present).
Start a clear text signed message.
@param hashAlgorithm
Note: Close() does not close the underlying stream. So it is possible to write
multiple objects using armoring to a single stream.
Basic type for a image attribute packet.
Reader for PGP objects.
Returns the next packet tag in the stream.
A stream that overlays our input stream, allowing the user to only read a segment of it.
NB: dataLength will be negative if the segment length is in the upper range above 2**31.
Base class for a PGP object.
Basic output stream.
Create a stream representing a general packet.
Output stream to write to.
Create a stream representing an old style partial object.
Output stream to write to.
The packet tag for the object.
Create a stream representing a general packet.
Output stream to write to.
Packet tag.
Size of chunks making up the packet.
If true, the header is written out in old format.
Create a new style partial input stream buffered into chunks.
Output stream to write to.
Packet tag.
Size of chunks making up the packet.
Create a new style partial input stream buffered into chunks.
Output stream to write to.
Packet tag.
Buffer to use for collecting chunks.
Flush the underlying stream.
Finish writing out the current packet without closing the underlying stream.
Generic compressed data object.
The algorithm tag value.
Basic tags for compression algorithms.
Basic type for a PGP packet.
Base class for a DSA public key.
The stream to read the packet from.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Base class for a DSA secret key.
@param in
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
@return x
Base class for an ECDH Public Key.
The stream to read the packet from.
Base class for an ECDSA Public Key.
The stream to read the packet from.
Base class for an EC Public Key.
The stream to read the packet from.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Base class for an EC Secret Key.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Base class for an ElGamal public key.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Base class for an ElGamal secret key.
@param in
@param x
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Basic packet for an experimental packet.
Basic tags for hash algorithms.
Base interface for a PGP key.
The base format for this key - in the case of the symmetric keys it will generally
be raw indicating that the key is just a straight byte representation, for an asymmetric
key the format will be PGP, indicating the key is a string of MPIs encoded in PGP format.
"RAW" or "PGP".
Note: you can only read from this once...
Generic literal data packet.
The format tag value.
The modification time of the file in milli-seconds (since Jan 1, 1970 UTC)
Basic type for a marker packet.
Basic packet for a modification detection code packet.
A multiple precision integer
Generic signature object
The encryption algorithm tag.
The hash algorithm tag.
Basic PGP packet tag types.
Public Key Algorithm tag numbers.
Basic packet for a PGP public key.
Basic packet for a PGP public key.
Construct a version 4 public key packet.
Basic packet for a PGP public subkey
Construct a version 4 public subkey packet.
Base class for an RSA public key.
Construct an RSA public key from the passed in stream.
The modulus.
The public exponent.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
Base class for an RSA secret (or priate) key.
The format, as a string, always "PGP".
Return the standard PGP encoding of the key.
The string to key specifier class.
The hash algorithm.
The IV for the key generation algorithm.
The iteration count
The protection mode - only if GnuDummyS2K
Basic packet for a PGP secret key.
Basic packet for a PGP secret key.
Packet embedded signature
packet giving signature creation time.
packet giving signature expiration time.
Identifier for the Modification Detection (packets 18 and 19)
Identifier for the AEAD Encrypted Data Packet (packet 20) and version 5
Symmetric-Key Encrypted Session Key Packets (packet 3)
Identifier for the Version 5 Public-Key Packet format and corresponding new
fingerprint format
Returns if modification detection is supported.
Returns if a particular feature is supported.
packet giving signature creation time.
packet giving time after creation at which the key expires.
Return the number of seconds after creation time a key is valid for.
@return second count for key validity.
Packet holding the key flag values.
Return the flag values contained in the first 4 octets (note: at the moment
the standard only uses the first one).
Class provided a NotationData object according to
RFC2440, Chapter 5.2.3.15. Notation Data
packet giving signature creation time.
packet giving whether or not the signature is signed using the primary user ID for the key.
packet giving whether or not is revocable.
packet giving signature creation time.
packet giving signature expiration time.
return time in seconds before signature expires after creation time.
packet giving the User ID of the signer.
packet giving trust.
Represents revocation key OpenPGP signature sub packet.
Represents revocation reason OpenPGP signature sub packet.
Generic signature packet.
Generate a version 4 signature packet.
@param signatureType
@param keyAlgorithm
@param hashAlgorithm
@param hashedData
@param unhashedData
@param fingerprint
@param signature
Generate a version 2/3 signature packet.
@param signatureType
@param keyAlgorithm
@param hashAlgorithm
@param fingerprint
@param signature
return the keyId
@return the keyId that created the signature.
return the signature trailer that must be included with the data
to reconstruct the signature
@return byte[]
* return the signature as a set of integers - note this is normalised to be the
* ASN.1 encoding of what appears in the signature packet.
Return the byte encoding of the signature section.
@return uninterpreted signature bytes.
Return the creation time in milliseconds since 1 Jan., 1970 UTC.
Basic type for a PGP Signature sub-packet.
Return the generic data making up the packet.
reader for signature sub-packets
Basic PGP signature sub-packet tag types.
Basic type for a symmetric key encrypted packet.
Basic tags for symmetric key algorithms
Basic type for a symmetric encrypted session key packet
@return int
@return S2k
@return byte[]
@return int
Basic type for a trust packet.
Basic type for a user attribute packet.
Basic type for a user attribute sub-packet.
return the generic data making up the packet.
reader for user attribute sub-packets
Basic PGP user attribute sub-packet tag types.
Basic type for a user ID packet.
Wrap a PKIMessage ASN.1 structure.
PKI message.
Create a PKIMessage from the passed in bytes.
BER/DER encoding of the PKIMessage
Return true if this message has protection bits on it. A return value of true
indicates the message can be used to construct a ProtectedPKIMessage.
Wrapper for a PKIMessage with protection attached to it.
Wrap a general message.
If the general message does not have protection.
The General message
Wrap a PKI message.
If the PKI message does not have protection.
The PKI message
Message header
Message body
Return the underlying ASN.1 structure contained in this object.
PkiMessage structure
Determine whether the message is protected by a password based MAC. Use verify(PKMACBuilder, char[])
to verify the message if this method returns true.
true if protection MAC PBE based, false otherwise.
Return the extra certificates associated with this message.
an array of extra certificates, zero length if none present.
Verify a message with a public key based signature attached.
a factory of signature verifiers.
true if the provider is able to create a verifier that validates the signature, false otherwise.
Verify a message with password based MAC protection.
MAC builder that can be used to construct the appropriate MacCalculator
the MAC password
true if the passed in password and MAC builder verify the message, false otherwise.
if algorithm not MAC based, or an exception is thrown verifying the MAC.
The 'Signature' parameter is only available when generating unsigned attributes.
containing class for an CMS Authenticated Data object
return the object identifier for the content MAC algorithm.
return a store of the intended recipients for this message
return the ContentInfo
return a table of the digested attributes indexed by
the OID of the attribute.
return a table of the undigested attributes indexed by
the OID of the attribute.
return the ASN.1 encoded representation of this object.
General class for generating a CMS authenticated-data message.
A simple example of usage.
CMSAuthenticatedDataGenerator fact = new CMSAuthenticatedDataGenerator();
fact.addKeyTransRecipient(cert);
CMSAuthenticatedData data = fact.generate(content, algorithm, "BC");
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
generate an enveloped object that contains an CMS Enveloped Data
object using the given provider and the passed in key generator.
generate an authenticated object that contains an CMS Authenticated Data object
Parsing class for an CMS Authenticated Data object from an input stream.
Note: that because we are in a streaming mode only one recipient can be tried and it is important
that the methods on the parser are called in the appropriate order.
Example of use - assuming the first recipient matches the private key we have.
CMSAuthenticatedDataParser ad = new CMSAuthenticatedDataParser(inputStream);
RecipientInformationStore recipients = ad.getRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
CMSTypedStream recData = recipient.getContentStream(privateKey, "BC");
processDataStream(recData.getContentStream());
if (!Arrays.equals(ad.getMac(), recipient.getMac())
{
System.err.println("Data corrupted!!!!");
}
}
Note: this class does not introduce buffering - if you are processing large files you should create
the parser with:
CMSAuthenticatedDataParser ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize));
where bufSize is a suitably large buffer size.
return the object identifier for the mac algorithm.
return the ASN.1 encoded encryption algorithm parameters, or null if
there aren't any.
return a store of the intended recipients for this message
return a table of the unauthenticated attributes indexed by
the OID of the attribute.
@exception java.io.IOException
return a table of the unauthenticated attributes indexed by
the OID of the attribute.
@exception java.io.IOException
General class for generating a CMS authenticated-data message stream.
A simple example of usage.
CMSAuthenticatedDataStreamGenerator edGen = new CMSAuthenticatedDataStreamGenerator();
edGen.addKeyTransRecipient(cert);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
OutputStream out = edGen.open(
bOut, CMSAuthenticatedDataGenerator.AES128_CBC, "BC");*
out.write(data);
out.close();
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
Set the underlying string size for encapsulated data
@param bufferSize length of octet strings to buffer the data.
Use a BER Set to store the recipient information
generate an enveloped object that contains an CMS Enveloped Data
object using the given provider and the passed in key generator.
@throws java.io.IOException
generate an enveloped object that contains an CMS Enveloped Data object
generate an enveloped object that contains an CMS Enveloped Data object
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
containing class for an CMS AuthEnveloped Data object
containing class for an CMS Compressed Data object
Return the uncompressed content.
@return the uncompressed content
@throws CmsException if there is an exception uncompressing the data.
Return the uncompressed content, throwing an exception if the data size
is greater than the passed in limit. If the content is exceeded getCause()
on the CMSException will contain a StreamOverflowException
@param limit maximum number of bytes to read
@return the content read
@throws CMSException if there is an exception uncompressing the data.
return the ContentInfo
return the ASN.1 encoded representation of this object.
* General class for generating a compressed CMS message.
*
* A simple example of usage.
*
*
* CMSCompressedDataGenerator fact = new CMSCompressedDataGenerator();
* CMSCompressedData data = fact.Generate(content, algorithm);
*
*
Generate an object that contains an CMS Compressed Data
Class for reading a CMS Compressed Data stream.
CMSCompressedDataParser cp = new CMSCompressedDataParser(inputStream);
process(cp.GetContent().GetContentStream());
Note: this class does not introduce buffering - if you are processing large files you should create
the parser with:
CMSCompressedDataParser ep = new CMSCompressedDataParser(new BufferedInputStream(inputStream, bufSize));
where bufSize is a suitably large buffer size.
General class for generating a compressed CMS message stream.
A simple example of usage.
CMSCompressedDataStreamGenerator gen = new CMSCompressedDataStreamGenerator();
Stream cOut = gen.Open(outputStream, CMSCompressedDataStreamGenerator.ZLIB);
cOut.Write(data);
cOut.Close();
base constructor
Set the underlying string size for encapsulated data
@param bufferSize length of octet strings to buffer the data.
Close the underlying data stream.
@throws IOException if the close fails.
containing class for an CMS Enveloped Data object
return the object identifier for the content encryption algorithm.
return a store of the intended recipients for this message
return the ContentInfo
return a table of the unprotected attributes indexed by
the OID of the attribute.
return the ASN.1 encoded representation of this object.
General class for generating a CMS enveloped-data message.
A simple example of usage.
CmsEnvelopedDataGenerator fact = new CmsEnvelopedDataGenerator();
fact.AddKeyTransRecipient(cert);
CmsEnvelopedData data = fact.Generate(content, algorithm);
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
Generate an enveloped object that contains a CMS Enveloped Data
object using the passed in key generator.
Generate an enveloped object that contains an CMS Enveloped Data object.
Generate an enveloped object that contains an CMS Enveloped Data object.
Parsing class for an CMS Enveloped Data object from an input stream.
Note: that because we are in a streaming mode only one recipient can be tried and it is important
that the methods on the parser are called in the appropriate order.
Example of use - assuming the first recipient matches the private key we have.
CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(inputStream);
RecipientInformationStore recipients = ep.GetRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
CMSTypedStream recData = recipient.getContentStream(privateKey);
processDataStream(recData.getContentStream());
}
Note: this class does not introduce buffering - if you are processing large files you should create
the parser with:
CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(new BufferedInputStream(inputStream, bufSize));
where bufSize is a suitably large buffer size.
return the object identifier for the content encryption algorithm.
return the ASN.1 encoded encryption algorithm parameters, or null if
there aren't any.
return a store of the intended recipients for this message
return a table of the unprotected attributes indexed by
the OID of the attribute.
@throws IOException
General class for generating a CMS enveloped-data message stream.
A simple example of usage.
CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();
edGen.AddKeyTransRecipient(cert);
MemoryStream bOut = new MemoryStream();
Stream out = edGen.Open(
bOut, CMSEnvelopedDataGenerator.AES128_CBC);*
out.Write(data);
out.Close();
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
Set the underlying string size for encapsulated data.
Length of octet strings to buffer the data.
Use a BER Set to store the recipient information.
Generate an enveloped object that contains an CMS Enveloped Data
object using the passed in key generator.
generate an enveloped object that contains an CMS Enveloped Data object
@throws IOException
generate an enveloped object that contains an CMS Enveloped Data object
@throws IOException
General class for generating a CMS enveloped-data message.
A simple example of usage.
CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
fact.addKeyTransRecipient(cert);
CMSEnvelopedData data = fact.generate(content, algorithm, "BC");
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
add a recipient.
@param cert recipient's public key certificate
@exception ArgumentException if there is a problem with the certificate
add a recipient
@param key the public key used by the recipient
@param subKeyId the identifier for the recipient's public key
@exception ArgumentException if there is a problem with the key
add a KEK recipient.
@param key the secret key to use for wrapping
@param keyIdentifier the byte string that identifies the key
add a KEK recipient.
@param key the secret key to use for wrapping
@param keyIdentifier the byte string that identifies the key
Add a key agreement based recipient.
@param agreementAlgorithm key agreement algorithm to use.
@param senderPrivateKey private key to initialise sender side of agreement with.
@param senderPublicKey sender public key to include with message.
@param recipientCert recipient's public key certificate.
@param cekWrapAlgorithm OID for key wrapping algorithm to use.
@exception SecurityUtilityException if the algorithm requested cannot be found
@exception InvalidKeyException if the keys are inappropriate for the algorithm specified
Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
@param agreementAlgorithm key agreement algorithm to use.
@param senderPrivateKey private key to initialise sender side of agreement with.
@param senderPublicKey sender public key to include with message.
@param recipientCerts recipients' public key certificates.
@param cekWrapAlgorithm OID for key wrapping algorithm to use.
@exception SecurityUtilityException if the algorithm requested cannot be found
@exception InvalidKeyException if the keys are inappropriate for the algorithm specified
Add a generator to produce the recipient info required.
a generator of a recipient info object.
Generic routine to copy out the data we want processed.
This routine may be called multiple times.
a holding class for a byte array of data to be processed.
a holding class for a file of data to be processed.
general class for handling a pkcs7-signature message.
A simple example of usage - note, in the example below the validity of
the certificate isn't verified, just the fact that one of the certs
matches the given signer...
IX509Store certs = s.GetCertificates();
SignerInformationStore signers = s.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ArrayList certList = new ArrayList(certs.GetMatches(signer.SignerID));
X509Certificate cert = (X509Certificate) certList[0];
if (signer.Verify(cert.GetPublicKey()))
{
verified++;
}
}
Content with detached signature, digests precomputed
@param hashes a map of precomputed digests for content indexed by name of hash.
@param sigBlock the signature object.
base constructor - content with detached signature.
@param signedContent the content that was signed.
@param sigData the signature object.
base constructor - with encapsulated content
Return the version number for this object.
return the collection of signers that are associated with the
signatures for the message.
return a X509Store containing the attribute certificates, if any, contained
in this message.
@param type type of store to create
@return a store of attribute certificates
@exception NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
return a X509Store containing the public key certificates, if any, contained in this message.
@return a store of public key certificates
@exception NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
return a X509Store containing CRLs, if any, contained in this message.
@return a store of CRLs
@exception NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
Return the DerObjectIdentifier associated with the encapsulated
content info structure carried in the signed data.
return the ContentInfo
return the ASN.1 encoded representation of this object.
return the ASN.1 encoded representation of this object using the specified encoding.
@param encoding the ASN.1 encoding format to use ("BER" or "DER").
Replace the signerinformation store associated with this
CmsSignedData object with the new one passed in. You would
probably only want to do this if you wanted to change the unsigned
attributes associated with a signer, or perhaps delete one.
@param signedData the signed data object to be used as a base.
@param signerInformationStore the new signer information store to use.
@return a new signed data object.
Replace the certificate and CRL information associated with this
CmsSignedData object with the new one passed in.
@param signedData the signed data object to be used as a base.
@param x509Certs the new certificates to be used.
@param x509Crls the new CRLs to be used.
@return a new signed data object.
@exception CmsException if there is an error processing the stores
* general class for generating a pkcs7-signature message.
*
* A simple example of usage.
*
*
* IX509Store certs...
* IX509Store crls...
* CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
*
* gen.AddSigner(privKey, cert, CmsSignedGenerator.DigestSha1);
* gen.AddCertificates(certs);
* gen.AddCrls(crls);
*
* CmsSignedData data = gen.Generate(content);
*
*
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
* add a signer - no attributes other than the default ones will be
* provided here.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param digestOID digest algorithm OID
add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
provided here.
@param key signing key to use
@param cert certificate containing corresponding public key
@param encryptionOID digest encryption algorithm OID
@param digestOID digest algorithm OID
add a signer - no attributes other than the default ones will be
provided here.
add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
provided here.
* add a signer with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
@param key signing key to use
@param cert certificate containing corresponding public key
@param encryptionOID digest encryption algorithm OID
@param digestOID digest algorithm OID
@param signedAttr table of attributes to be included in signature
@param unsignedAttr table of attributes to be included as unsigned
* add a signer with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param subjectKeyID subjectKeyID of corresponding public key
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
@param key signing key to use
@param subjectKeyID subjectKeyID of corresponding public key
@param encryptionOID digest encryption algorithm OID
@param digestOID digest algorithm OID
@param signedAttr table of attributes to be included in signature
@param unsignedAttr table of attributes to be included as unsigned
add a signer with extra signed/unsigned attributes based on generators.
add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators.
add a signer with extra signed/unsigned attributes based on generators.
add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators.
generate a signed object that for a CMS Signed Data object
generate a signed object that for a CMS Signed Data
object - if encapsulate is true a copy
of the message will be included in the signature. The content type
is set according to the OID represented by the string signedContentType.
generate a signed object that for a CMS Signed Data
object - if encapsulate is true a copy
of the message will be included in the signature with the
default content type "data".
generate a set of one or more SignerInformation objects representing counter signatures on
the passed in SignerInformation object.
@param signer the signer to be countersigned
@param sigProvider the provider to be used for counter signing.
@return a store containing the signers.
Parsing class for an CMS Signed Data object from an input stream.
Note: that because we are in a streaming mode only one signer can be tried and it is important
that the methods on the parser are called in the appropriate order.
A simple example of usage for an encapsulated signature.
Two notes: first, in the example below the validity of
the certificate isn't verified, just the fact that one of the certs
matches the given signer, and, second, because we are in a streaming
mode the order of the operations is important.
CmsSignedDataParser sp = new CmsSignedDataParser(encapSigData);
sp.GetSignedContent().Drain();
IX509Store certs = sp.GetCertificates();
SignerInformationStore signers = sp.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ArrayList certList = new ArrayList(certs.GetMatches(signer.SignerID));
X509Certificate cert = (X509Certificate) certList[0];
Console.WriteLine("verify returns: " + signer.Verify(cert));
}
Note also: this class does not introduce buffering - if you are processing large files you should create
the parser with:
CmsSignedDataParser ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize));
where bufSize is a suitably large buffer size.
base constructor - with encapsulated content
base constructor
@param signedContent the content that was signed.
@param sigData the signature object.
Return the version number for the SignedData object
@return the version number
return the collection of signers that are associated with the
signatures for the message.
@throws CmsException
return a X509Store containing the attribute certificates, if any, contained
in this message.
@param type type of store to create
@return a store of attribute certificates
@exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
return a X509Store containing the public key certificates, if any, contained
in this message.
@param type type of store to create
@return a store of public key certificates
@exception NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
return a X509Store containing CRLs, if any, contained
in this message.
@param type type of store to create
@return a store of CRLs
@exception NoSuchStoreException if the store type isn't available.
@exception CmsException if a general exception prevents creation of the X509Store
Return the DerObjectIdentifier associated with the encapsulated
content info structure carried in the signed data.
Replace the signerinformation store associated with the passed
in message contained in the stream original with the new one passed in.
You would probably only want to do this if you wanted to change the unsigned
attributes associated with a signer, or perhaps delete one.
The output stream is returned unclosed.
@param original the signed data stream to be used as a base.
@param signerInformationStore the new signer information store to use.
@param out the stream to Write the new signed data object to.
@return out.
Replace the certificate and CRL information associated with this
CMSSignedData object with the new one passed in.
The output stream is returned unclosed.
@param original the signed data stream to be used as a base.
@param certsAndCrls the new certificates and CRLs to be used.
@param out the stream to Write the new signed data object to.
@return out.
@exception CmsException if there is an error processing the CertStore
General class for generating a pkcs7-signature message stream.
A simple example of usage.
IX509Store certs...
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(privateKey, cert, CmsSignedDataStreamGenerator.DIGEST_SHA1);
gen.AddCertificates(certs);
Stream sigOut = gen.Open(bOut);
sigOut.Write(Encoding.UTF8.GetBytes("Hello World!"));
sigOut.Close();
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
Set the underlying string size for encapsulated data
@param bufferSize length of octet strings to buffer the data.
add a signer - no attributes other than the default ones will be
provided here.
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be
provided here.
@throws NoSuchProviderException
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer with extra signed/unsigned attributes.
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer with extra signed/unsigned attributes - specifying digest
encryption algorithm.
@throws NoSuchProviderException
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer - no attributes other than the default ones will be
provided here.
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer - no attributes other than the default ones will be
provided here.
@throws NoSuchProviderException
@throws NoSuchAlgorithmException
@throws InvalidKeyException
add a signer with extra signed/unsigned attributes.
@throws NoSuchAlgorithmException
@throws InvalidKeyException
generate a signed object that for a CMS Signed Data object
generate a signed object that for a CMS Signed Data
object - if encapsulate is true a copy
of the message will be included in the signature with the
default content type "data".
generate a signed object that for a CMS Signed Data
object using the given provider - if encapsulate is true a copy
of the message will be included in the signature with the
default content type "data". If dataOutputStream is non null the data
being signed will be written to the stream as it is processed.
@param out stream the CMS object is to be written to.
@param encapsulate true if data should be encapsulated.
@param dataOutputStream output stream to copy the data being signed to.
generate a signed object that for a CMS Signed Data
object - if encapsulate is true a copy
of the message will be included in the signature. The content type
is set according to the OID represented by the string signedContentType.
generate a signed object that for a CMS Signed Data
object using the given provider - if encapsulate is true a copy
of the message will be included in the signature. The content type
is set according to the OID represented by the string signedContentType.
@param out stream the CMS object is to be written to.
@param signedContentType OID for data to be signed.
@param encapsulate true if data should be encapsulated.
@param dataOutputStream output stream to copy the data being signed to.
Default type for the signed data.
Constructor allowing specific source of randomness
Instance of SecureRandom to use.
Add a store of precalculated signers to the generator.
@param signerStore store of signers
Return a map of oids and byte arrays representing the digests calculated on the content during
the last generate.
@return a map of oids (as string objects) and byte[] representing digests.
Return the digest algorithm using one of the standard JCA string
representations rather than the algorithm identifier (if possible).
Return the digest encryption algorithm using one of the standard
JCA string representations rather than the algorithm identifier (if
possible).
Default authenticated attributes generator.
Initialise to use all defaults
Initialise with some extra attributes or overrides.
@param attributeTable initial attribute table to use.
Create a standard attribute table from the passed in parameters - this will
normally include contentType and messageDigest. If the constructor
using an AttributeTable was used, entries in it for contentType and
messageDigest will override the generated ones.
@param parameters source parameters for table generation.
@return a filled in IDictionary of attributes.
@param parameters source parameters
@return the populated attribute table
Default signed attributes generator.
Initialise to use all defaults
Initialise with some extra attributes or overrides.
@param attributeTable initial attribute table to use.
Create a standard attribute table from the passed in parameters - this will
normally include contentType, signingTime, and messageDigest. If the constructor
using an AttributeTable was used, entries in it for contentType, signingTime, and
messageDigest will override the generated ones.
@param parameters source parameters for table generation.
@return a filled in Dictionary of attributes.
@param parameters source parameters
@return the populated attribute table
the RecipientInfo class for a recipient who has been sent a message
encrypted using a secret key known to the other side.
decrypt the content and return an input stream.
the RecipientInfo class for a recipient who has been sent a message
encrypted using key agreement.
decrypt the content and return an input stream.
the KeyTransRecipientInformation class for a recipient who has been sent a secret
key encrypted using their public key that needs to be used to
extract the message.
decrypt the content and return it as a byte array.
a basic index for an originator.
Return the certificates stored in the underlying OriginatorInfo object.
@return a Store of X509CertificateHolder objects.
Return the CRLs stored in the underlying OriginatorInfo object.
@return a Store of X509CRLHolder objects.
Return the underlying ASN.1 object defining this SignerInformation object.
@return a OriginatorInfo.
the RecipientInfo class for a recipient who has been sent a message
encrypted using a password.
return the object identifier for the key derivation algorithm, or null
if there is none present.
@return OID for key derivation algorithm, if present.
decrypt the content and return an input stream.
PKCS5 scheme-2 - password converted to bytes assuming ASCII.
PKCS5 scheme-2 - password converted to bytes using UTF-8.
Generate a RecipientInfo object for the given key.
A
A
A
* return the object identifier for the key encryption algorithm.
*
* @return OID for key encryption algorithm.
* return the ASN.1 encoded key encryption algorithm parameters, or null if
* there aren't any.
*
* @return ASN.1 encoding of key encryption algorithm parameters.
Return the MAC calculated for the content stream. Note: this call is only meaningful once all
the content has been read.
@return byte array containing the mac.
Return the first RecipientInformation object that matches the
passed in selector. Null if there are no matches.
@param selector to identify a recipient
@return a single RecipientInformation object. Null if none matches.
Return the number of recipients in the collection.
@return number of recipients identified.
Return all recipients in the collection
@return a collection of recipients.
Return possible empty collection with recipients matching the passed in RecipientID
@param selector a recipient id to select against.
@return a collection of RecipientInformation objects.
a basic index for a signer.
If the passed in flag is true, the signer signature will be based on the data, not
a collection of signed attributes, and no signed attributes will be included.
@return the builder object
Provide a custom signed attribute generator.
@param signedGen a generator of signed attributes.
@return the builder object
Provide a generator of unsigned attributes.
@param unsignedGen a generator for signed attributes.
@return the builder object
Build a generator with the passed in X.509 certificate issuer and serial number as the signerIdentifier.
@param contentSigner operator for generating the final signature in the SignerInfo with.
@param certificate X.509 certificate related to the contentSigner.
@return a SignerInfoGenerator
@throws OperatorCreationException if the generator cannot be built.
Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used you should
try to follow the calculation described in RFC 5280 section 4.2.1.2.
@param signerFactory operator factory for generating the final signature in the SignerInfo with.
@param subjectKeyIdentifier key identifier to identify the public key for verifying the signature.
@return a SignerInfoGenerator
an expanded SignerInfo block from a CMS Signed message
Protected constructor. In some cases clients have their own idea about how to encode
the signed attributes and calculate the signature. This constructor is to allow developers
to deal with that by extending off the class and overriding e.g. SignedAttributes property.
@param baseInfo the SignerInformation to base this one on.
return the version number for this objects underlying SignerInfo structure.
return the object identifier for the signature.
return the signature parameters, or null if there aren't any.
return the content digest that was calculated during verification.
return the object identifier for the signature.
return the signature/encryption algorithm parameters, or null if
there aren't any.
return a table of the signed attributes - indexed by
the OID of the attribute.
return a table of the unsigned attributes indexed by
the OID of the attribute.
return the encoded signature
Return a SignerInformationStore containing the counter signatures attached to this
signer. If no counter signatures are present an empty store is returned.
return the DER encoding of the signed attributes.
@throws IOException if an encoding error occurs.
verify that the given public key successfully handles and confirms the
signature associated with this signer.
verify that the given certificate successfully handles and confirms
the signature associated with this signer and, if a signingTime
attribute is available, that the certificate was valid at the time the
signature was generated.
Return the base ASN.1 CMS structure that this object contains.
@return an object containing a CMS SignerInfo structure.
Return a signer information object with the passed in unsigned
attributes replacing the ones that are current associated with
the object passed in.
@param signerInformation the signerInfo to be used as the basis.
@param unsignedAttributes the unsigned attributes to add.
@return a copy of the original SignerInformationObject with the changed attributes.
Return a signer information object with passed in SignerInformationStore representing counter
signatures attached as an unsigned attribute.
@param signerInformation the signerInfo to be used as the basis.
@param counterSigners signer info objects carrying counter signature.
@return a copy of the original SignerInformationObject with the changed attributes.
Create a store containing a single SignerInformation object.
@param signerInfo the signer information to contain.
Create a store containing a collection of SignerInformation objects.
@param signerInfos a collection signer information objects to contain.
Return the first SignerInformation object that matches the
passed in selector. Null if there are no matches.
@param selector to identify a signer
@return a single SignerInformation object. Null if none matches.
The number of signers in the collection.
An ICollection of all signers in the collection
Return possible empty collection with signers matching the passed in SignerID
@param selector a signer id to select against.
@return a collection of SignerInformation objects.
Basic generator that just returns a preconstructed attribute table
Carrier for an authenticator control.
Basic constructor - build from a UTF-8 string representing the token.
UTF-8 string representing the token.
Basic constructor - build from a string representing the token.
string representing the token.
Return the type of this control.
Return the token associated with this control (a UTF8String).
Create a CertificateRequestMessage from the passed in bytes.
BER/DER encoding of the CertReqMsg structure.
Return the underlying ASN.1 object defining this CertificateRequestMessage object.
A CertReqMsg
Return the certificate template contained in this message.
a CertTemplate structure.
Return whether or not this request has control values associated with it.
true if there are control values present, false otherwise.
Return whether or not this request has a specific type of control value.
the type OID for the control value we are checking for.
true if a control value of type is present, false otherwise.
Return a control value of the specified type.
the type OID for the control value we are checking for.
the control value if present, null otherwise.
Return whether or not this request message has a proof-of-possession field in it.
true if proof-of-possession is present, false otherwise.
Return the type of the proof-of-possession this request message provides.
one of: popRaVerified, popSigningKey, popKeyEncipherment, popKeyAgreement
Return whether or not the proof-of-possession (POP) is of the type popSigningKey and
it has a public key MAC associated with it.
true if POP is popSigningKey and a PKMAC is present, false otherwise.
Return whether or not a signing key proof-of-possession (POP) is valid.
a provider that can produce content verifiers for the signature contained in this POP.
true if the POP is valid, false otherwise.
if there is a problem in verification or content verifier creation.
if POP not appropriate.
Return the ASN.1 encoding of the certReqMsg we wrap.
a byte array containing the binary encoding of the certReqMsg.
Create a builder that makes EncryptedValue structures.
wrapper a wrapper for key used to encrypt the actual data contained in the EncryptedValue.
encryptor an output encryptor to encrypt the actual data contained in the EncryptedValue.
Create a builder that makes EncryptedValue structures with fixed length blocks padded using the passed in padder.
a wrapper for key used to encrypt the actual data contained in the EncryptedValue.
encryptor an output encryptor to encrypt the actual data contained in the EncryptedValue.
padder a padder to ensure that the EncryptedValue created will always be a constant length.
Build an EncryptedValue structure containing the passed in pass phrase.
a revocation pass phrase.
an EncryptedValue containing the encrypted pass phrase.
Build an EncryptedValue structure containing the certificate contained in
the passed in holder.
a holder containing a certificate.
an EncryptedValue containing the encrypted certificate.
on a failure to encrypt the data, or wrap the symmetric key for this value.
Build an EncryptedValue structure containing the private key contained in
the passed info structure.
a PKCS#8 private key info structure.
an EncryptedValue containing an EncryptedPrivateKeyInfo structure.
on a failure to encrypt the data, or wrap the symmetric key for this value.
Generic interface for a CertificateRequestMessage control value.
Return the type of this control.
Return the value contained in this control object.
An encrypted value padder is used to make sure that prior to a value been
encrypted the data is padded to a standard length.
Return a byte array of padded data.
the data to be padded.
a padded byte array containing data.
Return a byte array of with padding removed.
the data to be padded.
an array containing the original unpadded data.
Basic constructor - build from an PKIArchiveOptions structure.
the ASN.1 structure that will underlie this control.
Return the type of this control.
CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions
Return the underlying ASN.1 object.
a PKIArchiveOptions structure.
Return the archive control type, one of: encryptedPrivKey,keyGenParameters,or archiveRemGenPrivKey.
the archive control type.
Return whether this control contains enveloped data.
true if the control contains enveloped data, false otherwise.
Return the enveloped data structure contained in this control.
a CMSEnvelopedData object.
Basic constructor - specify the contents of the PKIArchiveControl structure.
the private key to be archived.
the general name to be associated with the private key.
Add a recipient generator to this control.
recipient generator created for a specific recipient.
this builder object.
Build the PKIArchiveControl using the passed in encryptor to encrypt its contents.
a suitable content encryptor.
a PKIArchiveControl object.
Default, IterationCount = 1000, OIW=IdSha1, Mac=HmacSHA1
Defaults with IPKMacPrimitivesProvider
Create.
The Mac provider
Digest Algorithm Id
Mac Algorithm Id
Create a PKMAC builder enforcing a ceiling on the maximum iteration count.
supporting calculator
max allowable value for iteration count.
Set the salt length in octets.
@param saltLength length in octets of the salt to be generated.
@return the generator
Set the iteration count.
the iteration count.
this
if iteration count is less than 100
Set PbmParameters
The parameters.
this
The Secure random
The random.
this
Build an IMacFactory.
The password.
IMacFactory
Basic constructor - build from a UTF-8 string representing the token.
UTF-8 string representing the token.
Basic constructor - build from a string representing the token.
string representing the token.
Return the type of this control.
CRMFObjectIdentifiers.id_regCtrl_regToken
Return the token associated with this control (a UTF8String).
a UTF8String.
a Diffie-Hellman key exchange engine.
note: This uses MTI/A0 key agreement in order to make the key agreement
secure against passive attacks. If you're doing Diffie-Hellman and both
parties have long term public keys you should look at using this. For
further information have a look at RFC 2631.
It's possible to extend this to more than two parties as well, for the moment
that is left as an exercise for the reader.
calculate our initial message.
given a message from a given party and the corresponding public key
calculate the next message in the agreement sequence. In this case
this will represent the shared secret.
a Diffie-Hellman key agreement class.
note: This is only the basic algorithm, it doesn't take advantage of
long term public keys if they are available. See the DHAgreement class
for a "better" implementation.
given a short term public key from a given party calculate the next
message in the agreement sequence.
Standard Diffie-Hellman groups from various IETF specifications.
P1363 7.2.1 ECSVDP-DH
ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
and [Kob87]. This primitive derives a shared secret value from one
party's private key and another party's public key, where both have
the same set of EC domain parameters. If two parties correctly
execute this primitive, they will produce the same output. This
primitive can be invoked by a scheme to derive a shared secret key;
specifically, it may be used with the schemes ECKAS-DH1 and
DL/ECKAS-DH2. It assumes that the input keys are valid (see also
Section 7.2.2).
P1363 7.2.2 ECSVDP-DHC
ECSVDP-DHC is Elliptic Curve Secret Value Derivation Primitive,
Diffie-Hellman version with cofactor multiplication. It is based on
the work of [DH76], [Mil86], [Kob87], [LMQ98] and [Kal98a]. This
primitive derives a shared secret value from one party's private key
and another party's public key, where both have the same set of EC
domain parameters. If two parties correctly execute this primitive,
they will produce the same output. This primitive can be invoked by a
scheme to derive a shared secret key; specifically, it may be used
with the schemes ECKAS-DH1 and DL/ECKAS-DH2. It does not assume the
validity of the input public key (see also Section 7.2.1).
Note: As stated P1363 compatibility mode with ECDH can be preset, and
in this case the implementation doesn't have a ECDH compatibility mode
(if you want that just use ECDHBasicAgreement and note they both implement
BasicAgreement!).
A participant in a Password Authenticated Key Exchange by Juggling (J-PAKE) exchange.
The J-PAKE exchange is defined by Feng Hao and Peter Ryan in the paper
"Password Authenticated Key Exchange by Juggling, 2008."
The J-PAKE protocol is symmetric.
There is no notion of a client or server, but rather just two participants.
An instance of JPakeParticipant represents one participant, and
is the primary interface for executing the exchange.
To execute an exchange, construct a JPakeParticipant on each end,
and call the following 7 methods
(once and only once, in the given order, for each participant, sending messages between them as described):
CreateRound1PayloadToSend() - and send the payload to the other participant
ValidateRound1PayloadReceived(JPakeRound1Payload) - use the payload received from the other participant
CreateRound2PayloadToSend() - and send the payload to the other participant
ValidateRound2PayloadReceived(JPakeRound2Payload) - use the payload received from the other participant
CalculateKeyingMaterial()
CreateRound3PayloadToSend(BigInteger) - and send the payload to the other participant
ValidateRound3PayloadReceived(JPakeRound3Payload, BigInteger) - use the payload received from the other participant
Each side should derive a session key from the keying material returned by CalculateKeyingMaterial().
The caller is responsible for deriving the session key using a secure key derivation function (KDF).
Round 3 is an optional key confirmation process.
If you do not execute round 3, then there is no assurance that both participants are using the same key.
(i.e. if the participants used different passwords, then their session keys will differ.)
If the round 3 validation succeeds, then the keys are guaranteed to be the same on both sides.
The symmetric design can easily support the asymmetric cases when one party initiates the communication.
e.g. Sometimes the round1 payload and round2 payload may be sent in one pass.
Also, in some cases, the key confirmation payload can be sent together with the round2 payload.
These are the trivial techniques to optimize the communication.
The key confirmation process is implemented as specified in
NIST SP 800-56A Revision 1,
Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes.
This class is stateful and NOT threadsafe.
Each instance should only be used for ONE complete J-PAKE exchange
(i.e. a new JPakeParticipant should be constructed for each new J-PAKE exchange).
Convenience constructor for a new JPakeParticipant that uses
the JPakePrimeOrderGroups#NIST_3072 prime order group,
a SHA-256 digest, and a default SecureRandom implementation.
After construction, the State state will be STATE_INITIALIZED.
Throws NullReferenceException if any argument is null. Throws
ArgumentException if password is empty.
Unique identifier of this participant.
The two participants in the exchange must NOT share the same id.
Shared secret.
A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
Caller should clear the input password as soon as possible.
Convenience constructor for a new JPakeParticipant that uses
a SHA-256 digest, and a default SecureRandom implementation.
After construction, the State state will be STATE_INITIALIZED.
Throws NullReferenceException if any argument is null. Throws
ArgumentException if password is empty.
Unique identifier of this participant.
The two participants in the exchange must NOT share the same id.
Shared secret.
A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
Caller should clear the input password as soon as possible.
Prime order group. See JPakePrimeOrderGroups for standard groups.
Constructor for a new JPakeParticipant.
After construction, the State state will be STATE_INITIALIZED.
Throws NullReferenceException if any argument is null. Throws
ArgumentException if password is empty.
Unique identifier of this participant.
The two participants in the exchange must NOT share the same id.
Shared secret.
A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
Caller should clear the input password as soon as possible.
Prime order group. See JPakePrimeOrderGroups for standard groups.
Digest to use during zero knowledge proofs and key confirmation
(SHA-256 or stronger preferred).
Source of secure random data for x1 and x2, and for the zero knowledge proofs.
Gets the current state of this participant.
See the STATE_* constants for possible values.
Creates and returns the payload to send to the other participant during round 1.
After execution, the State state} will be STATE_ROUND_1_CREATED}.
Validates the payload received from the other participant during round 1.
Must be called prior to CreateRound2PayloadToSend().
After execution, the State state will be STATE_ROUND_1_VALIDATED.
Throws CryptoException if validation fails. Throws InvalidOperationException
if called multiple times.
Creates and returns the payload to send to the other participant during round 2.
ValidateRound1PayloadReceived(JPakeRound1Payload) must be called prior to this method.
After execution, the State state will be STATE_ROUND_2_CREATED.
Throws InvalidOperationException if called prior to ValidateRound1PayloadReceived(JPakeRound1Payload), or multiple times
Validates the payload received from the other participant during round 2.
Note that this DOES NOT detect a non-common password.
The only indication of a non-common password is through derivation
of different keys (which can be detected explicitly by executing round 3 and round 4)
Must be called prior to CalculateKeyingMaterial().
After execution, the State state will be STATE_ROUND_2_VALIDATED.
Throws CryptoException if validation fails. Throws
InvalidOperationException if called prior to ValidateRound1PayloadReceived(JPakeRound1Payload), or multiple times
Calculates and returns the key material.
A session key must be derived from this key material using a secure key derivation function (KDF).
The KDF used to derive the key is handled externally (i.e. not by JPakeParticipant).
The keying material will be identical for each participant if and only if
each participant's password is the same. i.e. If the participants do not
share the same password, then each participant will derive a different key.
Therefore, if you immediately start using a key derived from
the keying material, then you must handle detection of incorrect keys.
If you want to handle this detection explicitly, you can optionally perform
rounds 3 and 4. See JPakeParticipant for details on how to execute
rounds 3 and 4.
The keying material will be in the range [0, p-1].
ValidateRound2PayloadReceived(JPakeRound2Payload) must be called prior to this method.
As a side effect, the internal password array is cleared, since it is no longer needed.
After execution, the State state will be STATE_KEY_CALCULATED.
Throws InvalidOperationException if called prior to ValidateRound2PayloadReceived(JPakeRound2Payload),
or if called multiple times.
Creates and returns the payload to send to the other participant during round 3.
See JPakeParticipant for more details on round 3.
After execution, the State state} will be STATE_ROUND_3_CREATED.
Throws InvalidOperationException if called prior to CalculateKeyingMaterial, or multiple
times.
The keying material as returned from CalculateKeyingMaterial().
Validates the payload received from the other participant during round 3.
See JPakeParticipant for more details on round 3.
After execution, the State state will be STATE_ROUND_3_VALIDATED.
Throws CryptoException if validation fails. Throws InvalidOperationException if called prior to
CalculateKeyingMaterial or multiple times
The round 3 payload received from the other participant.
The keying material as returned from CalculateKeyingMaterial().
A pre-computed prime order group for use during a J-PAKE exchange.
Typically a Schnorr group is used. In general, J-PAKE can use any prime order group
that is suitable for public key cryptography, including elliptic curve cryptography.
See JPakePrimeOrderGroups for convenient standard groups.
NIST publishes
many groups that can be used for the desired level of security.
Constructs a new JPakePrimeOrderGroup.
In general, you should use one of the pre-approved groups from
JPakePrimeOrderGroups, rather than manually constructing one.
The following basic checks are performed:
p-1 must be evenly divisible by q
g must be in [2, p-1]
g^q mod p must equal 1
p must be prime (within reasonably certainty)
q must be prime (within reasonably certainty)
The prime checks are performed using BigInteger#isProbablePrime(int),
and are therefore subject to the same probability guarantees.
These checks prevent trivial mistakes.
However, due to the small uncertainties if p and q are not prime,
advanced attacks are not prevented.
Use it at your own risk.
Throws NullReferenceException if any argument is null. Throws
InvalidOperationException is any of the above validations fail.
Constructor used by the pre-approved groups in JPakePrimeOrderGroups.
These pre-approved groups can avoid the expensive checks.
User-specified groups should not use this constructor.
Standard pre-computed prime order groups for use by J-PAKE.
(J-PAKE can use pre-computed prime order groups, same as DSA and Diffie-Hellman.)
This class contains some convenient constants for use as input for
constructing {@link JPAKEParticipant}s.
The prime order groups below are taken from Sun's JDK JavaDoc (docs/guide/security/CryptoSpec.html#AppB),
and from the prime order groups
published by NIST.
From Sun's JDK JavaDoc (docs/guide/security/CryptoSpec.html#AppB)
1024-bit p, 160-bit q and 1024-bit g for 80-bit security.
From NIST.
2048-bit p, 224-bit q and 2048-bit g for 112-bit security.
From NIST.
3072-bit p, 256-bit q and 3072-bit g for 128-bit security.
The payload sent/received during the first round of a J-PAKE exchange.
Each JPAKEParticipant creates and sends an instance of this payload to
the other. The payload to send should be created via
JPAKEParticipant.CreateRound1PayloadToSend().
Each participant must also validate the payload received from the other.
The received payload should be validated via
JPAKEParticipant.ValidateRound1PayloadReceived(JPakeRound1Payload).
The id of the JPAKEParticipant who created/sent this payload.
The value of g^x1
The value of g^x2
The zero knowledge proof for x1.
This is a two element array, containing {g^v, r} for x1.
The zero knowledge proof for x2.
This is a two element array, containing {g^v, r} for x2.
The payload sent/received during the second round of a J-PAKE exchange.
Each JPAKEParticipant creates and sends an instance
of this payload to the other JPAKEParticipant.
The payload to send should be created via
JPAKEParticipant#createRound2PayloadToSend()
Each JPAKEParticipant must also validate the payload
received from the other JPAKEParticipant.
The received payload should be validated via
JPAKEParticipant#validateRound2PayloadReceived(JPakeRound2Payload)
The id of the JPAKEParticipant who created/sent this payload.
The value of A, as computed during round 2.
The zero knowledge proof for x2 * s.
This is a two element array, containing {g^v, r} for x2 * s.
The payload sent/received during the optional third round of a J-PAKE exchange,
which is for explicit key confirmation.
Each JPAKEParticipant creates and sends an instance
of this payload to the other JPAKEParticipant.
The payload to send should be created via
JPAKEParticipant#createRound3PayloadToSend(BigInteger)
Eeach JPAKEParticipant must also validate the payload
received from the other JPAKEParticipant.
The received payload should be validated via
JPAKEParticipant#validateRound3PayloadReceived(JPakeRound3Payload, BigInteger)
The id of the {@link JPAKEParticipant} who created/sent this payload.
The value of MacTag, as computed by round 3.
See JPAKEUtil#calculateMacTag(string, string, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, org.bouncycastle.crypto.Digest)
Primitives needed for a J-PAKE exchange.
The recommended way to perform a J-PAKE exchange is by using
two JPAKEParticipants. Internally, those participants
call these primitive operations in JPakeUtilities.
The primitives, however, can be used without a JPAKEParticipant if needed.
Return a value that can be used as x1 or x3 during round 1.
The returned value is a random value in the range [0, q-1].
Return a value that can be used as x2 or x4 during round 1.
The returned value is a random value in the range [1, q-1].
Converts the given password to a BigInteger
for use in arithmetic calculations.
Calculate g^x mod p as done in round 1.
Calculate ga as done in round 2.
Calculate x2 * s as done in round 2.
Calculate A as done in round 2.
Calculate a zero knowledge proof of x using Schnorr's signature.
The returned array has two elements {g^v, r = v-x*h} for x.
Validates that g^x4 is not 1.
throws CryptoException if g^x4 is 1
Validates that ga is not 1.
As described by Feng Hao...
Alice could simply check ga != 1 to ensure it is a generator.
In fact, as we will explain in Section 3, (x1 + x3 + x4 ) is random over Zq even in the face of active attacks.
Hence, the probability for ga = 1 is extremely small - on the order of 2^160 for 160-bit q.
throws CryptoException if ga is 1
Validates the zero knowledge proof (generated by
calculateZeroKnowledgeProof(BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, string, Digest, SecureRandom)
is correct.
throws CryptoException if the zero knowledge proof is not correct
Calculates the keying material, which can be done after round 2 has completed.
A session key must be derived from this key material using a secure key derivation function (KDF).
The KDF used to derive the key is handled externally (i.e. not by JPAKEParticipant).
KeyingMaterial = (B/g^{x2*x4*s})^x2
Validates that the given participant ids are not equal.
(For the J-PAKE exchange, each participant must use a unique id.)
Throws CryptoException if the participantId strings are equal.
Validates that the given participant ids are equal.
This is used to ensure that the payloads received from
each round all come from the same participant.
Validates that the given object is not null.
throws NullReferenceException if the object is null.
object in question
name of the object (to be used in exception message)
Calculates the MacTag (to be used for key confirmation), as defined by
NIST SP 800-56A Revision 1,
Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes.
MacTag = HMAC(MacKey, MacLen, MacData)
MacKey = H(K || "JPAKE_KC")
MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4
Note that both participants use "KC_1_U" because the sender of the round 3 message
is always the initiator for key confirmation.
HMAC = {@link HMac} used with the given {@link Digest}
H = The given {@link Digest}
MacLen = length of MacTag
Calculates the MacKey (i.e. the key to use when calculating the MagTag for key confirmation).
MacKey = H(K || "JPAKE_KC")
Validates the MacTag received from the partner participant.
throws CryptoException if the participantId strings are equal.
Generator for Concatenation Key Derivation Function defined in NIST SP 800-56A, Sect 5.8.1
the digest to be used as the source of generated bytes
the underlying digest.
Fill len bytes of the output buffer with bytes generated from the derivation function.
RFC 2631 Diffie-hellman KEK derivation function.
X9.63 based key derivation function for ECDH CMS.
SM2 Key Exchange protocol - based on https://tools.ietf.org/html/draft-shen-sm2-ecdsa-02
Implements the client side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
"SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
Initialises the client to begin new authentication attempt
@param N The safe prime associated with the client's verifier
@param g The group parameter associated with the client's verifier
@param digest The digest algorithm associated with the client's verifier
@param random For key generation
Generates client's credentials given the client's salt, identity and password
@param salt The salt used in the client's verifier.
@param identity The user's identity (eg. username)
@param password The user's password
@return Client's public value to send to server
Generates client's verification message given the server's credentials
@param serverB The server's credentials
@return Client's verification message for the server
@throws CryptoException If server's credentials are invalid
Computes the client evidence message M1 using the previously received values.
To be called after calculating the secret S.
@return M1: the client side generated evidence message
@throws CryptoException
Authenticates the server evidence message M2 received and saves it only if correct.
@param M2: the server side generated evidence message
@return A boolean indicating if the server message M2 was the expected one.
@throws CryptoException
Computes the final session key as a result of the SRP successful mutual authentication
To be called after verifying the server evidence message M2.
@return Key: the mutually authenticated symmetric session key
@throws CryptoException
Implements the server side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
"SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
Initialises the server to accept a new client authentication attempt
@param N The safe prime associated with the client's verifier
@param g The group parameter associated with the client's verifier
@param v The client's verifier
@param digest The digest algorithm associated with the client's verifier
@param random For key generation
Generates the server's credentials that are to be sent to the client.
@return The server's public value to the client
Processes the client's credentials. If valid the shared secret is generated and returned.
@param clientA The client's credentials
@return A shared secret BigInteger
@throws CryptoException If client's credentials are invalid
Authenticates the received client evidence message M1 and saves it only if correct.
To be called after calculating the secret S.
@param M1: the client side generated evidence message
@return A boolean indicating if the client message M1 was the expected one.
@throws CryptoException
Computes the server evidence message M2 using the previously verified values.
To be called after successfully verifying the client evidence message M1.
@return M2: the server side generated evidence message
@throws CryptoException
Computes the final session key as a result of the SRP successful mutual authentication
To be called after calculating the server evidence message M2.
@return Key: the mutual authenticated symmetric session key
@throws CryptoException
Computes the client evidence message (M1) according to the standard routine:
M1 = H( A | B | S )
@param digest The Digest used as the hashing function H
@param N Modulus used to get the pad length
@param A The public client value
@param B The public server value
@param S The secret calculated by both sides
@return M1 The calculated client evidence message
Computes the server evidence message (M2) according to the standard routine:
M2 = H( A | M1 | S )
@param digest The Digest used as the hashing function H
@param N Modulus used to get the pad length
@param A The public client value
@param M1 The client evidence message
@param S The secret calculated by both sides
@return M2 The calculated server evidence message
Computes the final Key according to the standard routine: Key = H(S)
@param digest The Digest used as the hashing function H
@param N Modulus used to get the pad length
@param S The secret calculated by both sides
@return
Generates new SRP verifier for user
Initialises generator to create new verifiers
@param N The safe prime to use (see DHParametersGenerator)
@param g The group parameter to use (see DHParametersGenerator)
@param digest The digest to use. The same digest type will need to be used later for the actual authentication
attempt. Also note that the final session key size is dependent on the chosen digest.
Creates a new SRP verifier
@param salt The salt to use, generally should be large and random
@param identity The user's identifying information (eg. username)
@param password The user's password
@return A new verifier for use in future SRP authentication
a holding class for public/private parameter pairs.
basic constructor.
@param publicParam a public key parameters object.
@param privateParam the corresponding private key parameters.
return the public key parameters.
@return the public key parameters.
return the private key parameters.
@return the private key parameters.
The AEAD block ciphers already handle buffering internally, so this class
just takes care of implementing IBufferedCipher methods.
initialise the cipher.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the blocksize for the underlying cipher.
@return the blocksize for the underlying cipher.
return the size of the output buffer required for an update
an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update
with len bytes of input.
return the size of the output buffer required for an update plus a
doFinal with an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update and doFinal
with len bytes of input.
process a single byte, producing an output block if necessary.
@param in the input byte.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
process an array of bytes, producing output if necessary.
@param in the input byte array.
@param inOff the offset at which the input data starts.
@param len the number of bytes to be copied out of the input array.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
Process the last block in the buffer.
@param out the array the block currently being held is copied into.
@param outOff the offset at which the copying starts.
@return the number of output bytes copied to out.
@exception DataLengthException if there is insufficient space in out for
the output, or the input is not block size aligned and should be.
@exception InvalidOperationException if the underlying cipher is not
initialised.
@exception InvalidCipherTextException if padding is expected and not found.
@exception DataLengthException if the input is not block size
aligned.
Reset the buffer and cipher. After resetting the object is in the same
state as it was after the last init (if there was one).
The AEAD ciphers already handle buffering internally, so this class
just takes care of implementing IBufferedCipher methods.
initialise the cipher.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the blocksize for the underlying cipher.
@return the blocksize for the underlying cipher.
return the size of the output buffer required for an update
an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update
with len bytes of input.
return the size of the output buffer required for an update plus a
doFinal with an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update and doFinal
with len bytes of input.
process a single byte, producing an output block if necessary.
@param in the input byte.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
process an array of bytes, producing output if necessary.
@param in the input byte array.
@param inOff the offset at which the input data starts.
@param len the number of bytes to be copied out of the input array.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
Process the last block in the buffer.
@param out the array the block currently being held is copied into.
@param outOff the offset at which the copying starts.
@return the number of output bytes copied to out.
@exception DataLengthException if there is insufficient space in out for
the output, or the input is not block size aligned and should be.
@exception InvalidOperationException if the underlying cipher is not
initialised.
@exception InvalidCipherTextException if padding is expected and not found.
@exception DataLengthException if the input is not block size
aligned.
Reset the buffer and cipher. After resetting the object is in the same
state as it was after the last init (if there was one).
a buffer wrapper for an asymmetric block cipher, allowing input
to be accumulated in a piecemeal fashion until final processing.
base constructor.
@param cipher the cipher this buffering object wraps.
return the amount of data sitting in the buffer.
@return the amount of data sitting in the buffer.
initialise the buffer and the underlying cipher.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
process the contents of the buffer using the underlying
cipher.
@return the result of the encryption/decryption process on the
buffer.
@exception InvalidCipherTextException if we are given a garbage block.
Reset the buffer
A wrapper class that allows block ciphers to be used to process data in
a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
buffer is full and more data is being added, or on a doFinal.
Note: in the case where the underlying cipher is either a CFB cipher or an
OFB one the last block may not be a multiple of the block size.
constructor for subclasses
Create a buffered block cipher without padding.
@param cipher the underlying block cipher this buffering object wraps.
false otherwise.
initialise the cipher.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the blocksize for the underlying cipher.
@return the blocksize for the underlying cipher.
return the size of the output buffer required for an update
an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update
with len bytes of input.
return the size of the output buffer required for an update plus a
doFinal with an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update and doFinal
with len bytes of input.
process a single byte, producing an output block if necessary.
@param in the input byte.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
process an array of bytes, producing output if necessary.
@param in the input byte array.
@param inOff the offset at which the input data starts.
@param len the number of bytes to be copied out of the input array.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
Process the last block in the buffer.
@param out the array the block currently being held is copied into.
@param outOff the offset at which the copying starts.
@return the number of output bytes copied to out.
@exception DataLengthException if there is insufficient space in out for
the output, or the input is not block size aligned and should be.
@exception InvalidOperationException if the underlying cipher is not
initialised.
@exception InvalidCipherTextException if padding is expected and not found.
@exception DataLengthException if the input is not block size
aligned.
Reset the buffer and cipher. After resetting the object is in the same
state as it was after the last init (if there was one).
The base class for symmetric, or secret, cipher key generators.
initialise the key generator.
@param param the parameters to be used for key generation
Generate a secret key.
@return a byte array containing the key value.
This exception is thrown if a buffer that is meant to have output copied into it turns out to be too
short, or if we've been given insufficient input.
In general this exception will get thrown rather than an .
Implementation of the cryptographic hash function Blake2b.
Blake2b offers a built-in keying mechanism to be used directly
for authentication ("Prefix-MAC") rather than a HMAC construction.
Blake2b offers a built-in support for a salt for randomized hashing
and a personal string for defining a unique hash function for each application.
BLAKE2b is optimized for 64-bit platforms and produces digests of any size
between 1 and 64 bytes.
Basic sized constructor - size in bits.
@param digestSize size of the digest in bits
Blake2b for authentication ("Prefix-MAC mode").
After calling the doFinal() method, the key will
remain to be used for further computations of
this instance.
The key can be overwritten using the clearKey() method.
@param key A key up to 64 bytes or null
Blake2b with key, required digest length (in bytes), salt and personalization.
After calling the doFinal() method, the key, the salt and the personal string
will remain and might be used for further computations with this instance.
The key can be overwritten using the clearKey() method, the salt (pepper)
can be overwritten using the clearSalt() method.
@param key A key up to 64 bytes or null
@param digestLength from 1 up to 64 bytes
@param salt 16 bytes or null
@param personalization 16 bytes or null
update the message digest with a single byte.
@param b the input byte to be entered.
update the message digest with a block of bytes.
@param message the byte array containing the data.
@param offset the offset into the byte array where the data starts.
@param len the length of the data.
close the digest, producing the final digest value. The doFinal
call leaves the digest reset.
Key, salt and personal string remain.
@param out the array the digest is to be copied into.
@param outOffset the offset into the out array the digest is to start at.
Reset the digest back to it's initial state.
The key, the salt and the personal string will
remain for further computations.
return the algorithm name
@return the algorithm name
return the size, in bytes, of the digest produced by this message digest.
@return the size, in bytes, of the digest produced by this message digest.
Return the size in bytes of the internal buffer the digest applies it's compression
function to.
@return byte length of the digests internal buffer.
Overwrite the key
if it is no longer used (zeroization)
Overwrite the salt (pepper) if it
is secret and no longer used (zeroization)
Implementation of the cryptographic hash function BLAKE2s.
BLAKE2s offers a built-in keying mechanism to be used directly
for authentication ("Prefix-MAC") rather than a HMAC construction.
BLAKE2s offers a built-in support for a salt for randomized hashing
and a personal string for defining a unique hash function for each application.
BLAKE2s is optimized for 32-bit platforms and produces digests of any size
between 1 and 32 bytes.
BLAKE2s Initialization Vector
Message word permutations
Whenever this buffer overflows, it will be processed in the Compress()
function. For performance issues, long messages will not use this buffer.
Position of last inserted byte
Internal state, in the BLAKE2 paper it is called v
State vector, in the BLAKE2 paper it is called h
holds least significant bits of counter
holds most significant bits of counter
finalization flag, for last block: ~0
BLAKE2s-256 for hashing.
BLAKE2s for hashing.
@param digestBits the desired digest length in bits. Must be a multiple of 8 and less than 256.
BLAKE2s for authentication ("Prefix-MAC mode").
After calling the doFinal() method, the key will remain to be used for
further computations of this instance. The key can be overwritten using
the clearKey() method.
@param key a key up to 32 bytes or null
BLAKE2s with key, required digest length, salt and personalization.
After calling the doFinal() method, the key, the salt and the personal
string will remain and might be used for further computations with this
instance. The key can be overwritten using the clearKey() method, the
salt (pepper) can be overwritten using the clearSalt() method.
@param key a key up to 32 bytes or null
@param digestBytes from 1 up to 32 bytes
@param salt 8 bytes or null
@param personalization 8 bytes or null
Update the message digest with a single byte.
@param b the input byte to be entered.
Update the message digest with a block of bytes.
@param message the byte array containing the data.
@param offset the offset into the byte array where the data starts.
@param len the length of the data.
Close the digest, producing the final digest value. The doFinal() call
leaves the digest reset. Key, salt and personal string remain.
@param out the array the digest is to be copied into.
@param outOffset the offset into the out array the digest is to start at.
Reset the digest back to its initial state. The key, the salt and the
personal string will remain for further computations.
Return the algorithm name.
@return the algorithm name
Return the size in bytes of the digest produced by this message digest.
@return the size in bytes of the digest produced by this message digest.
Return the size in bytes of the internal buffer the digest applies its
compression function to.
@return byte length of the digest's internal buffer.
Overwrite the key if it is no longer used (zeroization).
Overwrite the salt (pepper) if it is secret and no longer used
(zeroization).
Implementation of the eXtendable Output Function (XOF) BLAKE2xs.
BLAKE2xs offers a built-in keying mechanism to be used directly
for authentication ("Prefix-MAC") rather than a HMAC construction.
BLAKE2xs offers a built-in support for a salt for randomized hashing
and a personal string for defining a unique hash function for each application.
BLAKE2xs is optimized for 32-bit platforms and produces digests of any size
between 1 and 2^16-2 bytes. The length can also be unknown and then the maximum
length will be 2^32 blocks of 32 bytes.
Magic number to indicate an unknown length of digest
Expected digest length for the xof. It can be unknown.
Root hash that will take the updates
Digest of the root hash
Digest of each round of the XOF
Current position for a round
Overall position of the digest. It is useful when the length is known
in advance to get last block length.
Keep track of the round number to detect the end of the digest after
2^32 blocks of 32 bytes.
Current node offset incremented by 1 every round.
BLAKE2xs for hashing with unknown digest length
BLAKE2xs for hashing
@param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1
BLAKE2xs with key
@param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1
@param key A key up to 32 bytes or null
BLAKE2xs with key, salt and personalization
@param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1
@param key A key up to 32 bytes or null
@param salt 8 bytes or null
@param personalization 8 bytes or null
Return the algorithm name.
@return the algorithm name
Return the size in bytes of the digest produced by this message digest.
@return the size in bytes of the digest produced by this message digest.
Return the size in bytes of the internal buffer the digest applies its
compression function to.
@return byte length of the digest's internal buffer.
Return the maximum size in bytes the digest can produce when the length
is unknown
@return byte length of the largest digest with unknown length
Update the message digest with a single byte.
@param in the input byte to be entered.
Update the message digest with a block of bytes.
@param in the byte array containing the data.
@param inOff the offset into the byte array where the data starts.
@param len the length of the data.
Reset the digest back to its initial state. The key, the salt and the
personal string will remain for further computations.
Close the digest, producing the final digest value. The doFinal() call
leaves the digest reset. Key, salt and personal string remain.
@param out the array the digest is to be copied into.
@param outOffset the offset into the out array the digest is to start at.
Close the digest, producing the final digest value. The doFinal() call
leaves the digest reset. Key, salt, personal string remain.
@param out output array to write the output bytes to.
@param outOff offset to start writing the bytes at.
@param outLen the number of output bytes requested.
Start outputting the results of the final calculation for this digest. Unlike doFinal, this method
will continue producing output until the Xof is explicitly reset, or signals otherwise.
@param out output array to write the output bytes to.
@param outOff offset to start writing the bytes at.
@param outLen the number of output bytes requested.
@return the number of bytes written
Already outputting error.
Number of Words.
Number of Rounds.
Buffer length.
Chunk length.
ChunkStart Flag.
ChunkEnd Flag.
Parent Flag.
Root Flag.
KeyedHash Flag.
DeriveContext Flag.
DeriveKey Flag.
Chaining0 State Locations.
Chaining1 State Location.
Chaining2 State Location.
Chaining3 State Location.
Chaining4 State Location.
Chaining5 State Location.
Chaining6 State Location.
Chaining7 State Location.
IV0 State Locations.
IV1 State Location.
IV2 State Location.
IV3 State Location.
Count0 State Location.
Count1 State Location.
DataLen State Location.
Flags State Location.
Message word permutations.
Blake3 Initialization Vector.
The byte input/output buffer.
The key.
The chaining value.
The state.
The message Buffer.
The indices.
The chainingStack.
The default digestLength.
Are we outputting?
How many more bytes can we output?
The current mode.
The output mode.
The output dataLen.
The block counter.
The # of bytes in the current block.
The position of the next byte in the buffer.
the default digest size (in bits)
Constructor.
@param pSource the source digest.
Initialise.
@param pParams the parameters.
Adjust the stack.
Compress final block.
@param pDataLen the data length
Process the stack.
Perform compression.
Perform a round.
Adjust Chaining after compression.
Mix function G.
@param msgIdx the message index
@param posA position A in V
@param posB position B in V
@param posC position C in V
@param posD poistion D in V
initialise the indices.
PermuteIndices.
Initialise null key.
Initialise key.
@param pKey the keyBytes
Initialise key from context.
Initialise chunk block.
@param pDataLen the dataLength
@param pFinal is this the final chunk?
Initialise parent block.
Initialise output block.
IncrementBlockCount.
ResetBlockCount.
Set root indication.
Customizable SHAKE function.
Base constructor
bit length of the underlying SHAKE function, 128 or 256.
the function name string, note this is reserved for use by NIST. Avoid using it if not required.
the customization string - available for local use.
implementation of Ukrainian DSTU 7564 hash function
base implementation of MD4 family style digest as outlined in
"Handbook of Applied Cryptography", pages 344 - 347.
implementation of GOST R 34.11-94
Standard constructor
Constructor to allow use of a particular sbox with GOST28147
@see GOST28147Engine#getSBox(String)
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
Implementation of Keccak based on following KeccakNISTInterface.c from http://keccak.noekeon.org/
Following the naming conventions used in the C source code to enable easy review of the implementation.
Return the size of block that the compression function is applied to in bytes.
@return internal byte length of a block.
Base class for SHA-384 and SHA-512.
Constructor for variable length word
Copy constructor. We are using copy constructors in place
of the object.Clone() interface as this interface is not
supported by J2ME.
adjust the byte counts so that byteCount2 represents the
upper long (less 3 bits) word of the byte count.
implementation of MD2
as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
return the algorithm name
@return the algorithm name
Close the digest, producing the final digest value. The doFinal
call leaves the digest reset.
@param out the array the digest is to be copied into.
@param outOff the offset into the out array the digest is to start at.
reset the digest back to it's initial state.
update the message digest with a single byte.
@param in the input byte to be entered.
update the message digest with a block of bytes.
@param in the byte array containing the data.
@param inOff the offset into the byte array where the data starts.
@param len the length of the data.
implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
Computer Science and RSA Data Security, Inc.
NOTE: This algorithm is only included for backwards compatibility
with legacy applications, it's not secure, don't use it for anything new!
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
Wrapper removes exposure to the IMemoable interface on an IDigest implementation.
Base constructor.
@param baseDigest underlying digest to use.
@exception IllegalArgumentException if baseDigest is null
ParallelHash - a hash designed to support the efficient hashing of very long strings, by taking advantage,
of the parallelism available in modern processors with an optional XOF mode.
From NIST Special Publication 800-185 - SHA-3 Derived Functions:cSHAKE, KMAC, TupleHash and ParallelHash
Base constructor.
@param bitLength bit length of the underlying SHAKE function, 128 or 256.
@param S the customization string - available for local use.
@param B the blocksize (in bytes) for hashing.
implementation of RipeMD128
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
implementation of RipeMD see,
http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
Implementation of RipeMD256.
Note: this algorithm offers the same level of security as RipeMD128.
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
Implementation of RipeMD 320.
Note: this algorithm offers the same level of security as RipeMD160.
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables to the IV values.
implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
is the "endianness" of the word processing!
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
SHA-224 as described in RFC 3874
block word digest
SHA-1 512 32 160
SHA-224 512 32 224
SHA-256 512 32 256
SHA-384 1024 64 384
SHA-512 1024 64 512
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
Draft FIPS 180-2 implementation of SHA-256. Note: As this is
based on a draft this implementation is subject to change.
block word digest
SHA-1 512 32 160
SHA-256 512 32 256
SHA-384 1024 64 384
SHA-512 1024 64 512
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
Draft FIPS 180-2 implementation of SHA-384. Note: As this is
based on a draft this implementation is subject to change.
block word digest
SHA-1 512 32 160
SHA-256 512 32 256
SHA-384 1024 64 384
SHA-512 1024 64 512
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
Implementation of SHA-3 based on following KeccakNISTInterface.c from http://keccak.noekeon.org/
Following the naming conventions used in the C source code to enable easy review of the implementation.
Draft FIPS 180-2 implementation of SHA-512. Note: As this is
based on a draft this implementation is subject to change.
block word digest
SHA-1 512 32 160
SHA-256 512 32 256
SHA-384 1024 64 384
SHA-512 1024 64 512
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
FIPS 180-4 implementation of SHA-512/t
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
Implementation of SHAKE based on following KeccakNISTInterface.c from http://keccak.noekeon.org/
Following the naming conventions used in the C source code to enable easy review of the implementation.
Wrapper class that reduces the output length of a particular digest to
only the first n bytes of the digest function.
Base constructor.
@param baseDigest underlying digest to use.
@param length length in bytes of the output of doFinal.
@exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize().
Implementation of the Skein parameterised hash function in 256, 512 and 1024 bit block sizes,
based on the Threefish tweakable block cipher.
This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3
competition in October 2010.
Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
256 bit block size - Skein-256
512 bit block size - Skein-512
1024 bit block size - Skein-1024
Constructs a Skein digest with an internal state size and output size.
the internal state size in bits - one of or
.
the output/digest size to produce in bits, which must be an integral number of
bytes.
Optionally initialises the Skein digest with the provided parameters.
See for details on the parameterisation of the Skein hash function.
the parameters to apply to this engine, or null
to use no parameters.
Implementation of the Skein family of parameterised hash functions in 256, 512 and 1024 bit block
sizes, based on the Threefish tweakable block cipher.
This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3
competition in October 2010.
Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
This implementation is the basis for and , implementing the
parameter based configuration system that allows Skein to be adapted to multiple applications.
Initialising the engine with allows standard and arbitrary parameters to
be applied during the Skein hash function.
Implemented:
- 256, 512 and 1024 bit internal states.
- Full 96 bit input length.
- Parameters defined in the Skein specification, and arbitrary other pre and post message
parameters.
- Arbitrary output size in 1 byte intervals.
Not implemented:
- Sub-byte length input (bit padding).
- Tree hashing.
256 bit block size - Skein-256
512 bit block size - Skein-512
1024 bit block size - Skein-1024
The parameter type for the Skein key.
The parameter type for the Skein configuration block.
The parameter type for the message.
The parameter type for the output transformation.
Precalculated UBI(CFG) states for common state/output combinations without key or other
pre-message params.
Point at which position might overflow long, so switch to add with carry logic
Bit 127 = final
Bit 126 = first
UBI uses a 128 bit tweak
Whether 64 bit position exceeded
Advances the position in the tweak by the specified value.
The Unique Block Iteration chaining mode.
Buffer for the current block of message data
Offset into the current message block
Buffer for message words for feedback into encrypted block
Underlying Threefish tweakable block cipher
Size of the digest output, in bytes
The current chaining/state value
The initial state value
The (optional) key parameter
Parameters to apply prior to the message
Parameters to apply after the message, but prior to output
The current UBI operation
Buffer for single byte update method
Constructs a Skein digest with an internal state size and output size.
the internal state size in bits - one of or
.
the output/digest size to produce in bits, which must be an integral number of
bytes.
Creates a SkeinEngine as an exact copy of an existing instance.
Initialises the Skein engine with the provided parameters. See for
details on the parameterisation of the Skein hash function.
the parameters to apply to this engine, or null
to use no parameters.
Calculate the initial (pre message block) chaining state.
Reset the engine to the initial state (with the key and any pre-message parameters , ready to
accept message input.
Implementation of Chinese SM3 digest as described at
http://tools.ietf.org/html/draft-shen-sm3-hash-00
and at .... ( Chinese PDF )
The specification says "process a bit stream",
but this is written to process bytes in blocks of 4,
meaning this will process 32-bit word groups.
But so do also most other digest specifications,
including the SHA-256 which was a origin for
this specification.
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
implementation of Tiger based on:
http://www.cs.technion.ac.il/~biham/Reports/Tiger
Standard constructor
Copy constructor. This will copy the state of the provided
message digest.
reset the chaining variables
TupleHash - a hash designed to simply hash a tuple of input strings, any or all of which may be empty strings,
in an unambiguous way with an optional XOF mode.
From NIST Special Publication 800-185 - SHA-3 Derived Functions:cSHAKE, KMAC, TupleHash and ParallelHash
Base constructor.
@param bitLength bit length of the underlying SHAKE function, 128 or 256.
@param S the customization string - available for local use.
Implementation of WhirlpoolDigest, based on Java source published by Barreto and Rijmen.
Copy constructor. This will copy the state of the provided message digest.
Reset the chaining variables
Elliptic curve registry for various customized curve implementations.
Look up the for the curve with the given name.
The name of the curve.
Look up an for the curve with the given name.
Allows accessing the curve without necessarily triggering the creation of the
full .
The name of the curve.
Look up the for the curve with the given
OID.
The OID for the curve.
Look up an for the curve with the given
OID.
Allows accessing the curve without necessarily triggering the creation of the
full .
The OID for the curve.
Look up the name of the curve with the given OID.
The OID for the curve.
Look up the OID of the curve with the given name.
The name of the curve.
Enumerate the available curve names in this registry.
ISO 9796-1 padding. Note in the light of recent results you should
only use this with RSA (rather than the "simpler" Rabin keys) and you
should never use it with anything other than a hash (ie. even if the
message is small don't sign the message, sign it's hash) or some "random"
value. See your favorite search engine for details.
return the input block size. The largest message we can process
is (key_size_in_bits + 3)/16, which in our world comes to
key_size_in_bytes / 2.
return the maximum possible size for the output.
set the number of bits in the next message to be treated as
pad bits.
retrieve the number of pad bits in the last decoded message.
@exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
Optimal Asymmetric Encryption Padding (OAEP) - see PKCS 1 V 2.
@exception InvalidCipherTextException if the decrypted block turns out to
be badly formatted.
mask generator function, as described in PKCS1v2.
this does your basic Pkcs 1 v1.5 padding - whether or not you should be using this
depends on your application - see Pkcs1 Version 2 for details.
some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to
work with one of these set the system property Best.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs1.Strict to false.
The same effect can be achieved by setting the static property directly
The static property is checked during construction of the encoding object, it is set to
true by default.
Basic constructor.
@param cipher
Constructor for decryption with a fixed plaintext length.
@param cipher The cipher to use for cryptographic operation.
@param pLen Length of the expected plaintext.
Constructor for decryption with a fixed plaintext length and a fallback
value that is returned, if the padding is incorrect.
@param cipher
The cipher to use for cryptographic operation.
@param fallback
The fallback value, we don't to a arraycopy here.
Checks if the argument is a correctly PKCS#1.5 encoded Plaintext
for encryption.
@param encoded The Plaintext.
@param pLen Expected length of the plaintext.
@return Either 0, if the encoding is correct, or -1, if it is incorrect.
Decode PKCS#1.5 encoding, and return a random value if the padding is not correct.
@param in The encrypted block.
@param inOff Offset in the encrypted block.
@param inLen Length of the encrypted block.
@param pLen Length of the desired output.
@return The plaintext without padding, or a random value if the padding was incorrect.
@throws InvalidCipherTextException
@exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
an implementation of the AES (Rijndael), from FIPS-197.
For further details see: http://csrc.nist.gov/encryption/aes/.
This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
http://fp.gladman.plus.com/cryptography_technology/rijndael/
There are three levels of tradeoff of speed vs memory
Because java has no preprocessor, they are written as three separate classes from which to choose
The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
and 4 for decryption.
The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
adding 12 rotate operations per round to compute the values contained in the other tables from
the contents of the first.
The slowest version uses no static tables at all and computes the values in each round.
This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
Calculate the necessary round keys
The number of calculations depends on key size and block size
AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
This code is written assuming those are the only possible values
default constructor - 128 bit block size.
initialise an AES cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
an implementation of the AES (Rijndael), from FIPS-197.
For further details see: http://csrc.nist.gov/encryption/aes/.
This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
http://fp.gladman.plus.com/cryptography_technology/rijndael/
There are three levels of tradeoff of speed vs memory
Because java has no preprocessor, they are written as three separate classes from which to choose
The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
and 4 for decryption.
The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
adding 12 rotate operations per round to compute the values contained in the other tables from
the contents of the first
The slowest version uses no static tables at all and computes the values
in each round.
This file contains the slowest performance version with no static tables
for round precomputation, but it has the smallest foot print.
Calculate the necessary round keys
The number of calculations depends on key size and block size
AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
This code is written assuming those are the only possible values
default constructor - 128 bit block size.
initialise an AES cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
An implementation of the AES Key Wrapper from the NIST Key Wrap Specification.
For further details see: http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
RFC 5794.
ARIA is a 128-bit block cipher with 128-, 192-, and 256-bit keys.
A class that provides Blowfish key encryption operations,
such as encoding data and generating keys.
All the algorithms herein are from Applied Cryptography
and implement a simplified cryptography interface.
initialise a Blowfish cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
apply the encryption cycle to each value pair in the table.
Camellia - based on RFC 3713.
Camellia - based on RFC 3713, smaller implementation, about half the size of CamelliaEngine.
An implementation of the Camellia key wrapper based on RFC 3657/RFC 3394.
For further details see: http://www.ietf.org/rfc/rfc3657.txt.
A class that provides CAST key encryption operations,
such as encoding data and generating keys.
All the algorithms herein are from the Internet RFC's
RFC2144 - Cast5 (64bit block, 40-128bit key)
RFC2612 - CAST6 (128bit block, 128-256bit key)
and implement a simplified cryptography interface.
initialise a CAST cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
The first of the three processing functions for the
encryption and decryption.
@param D the input to be processed
@param Kmi the mask to be used from Km[n]
@param Kri the rotation value to be used
The second of the three processing functions for the
encryption and decryption.
@param D the input to be processed
@param Kmi the mask to be used from Km[n]
@param Kri the rotation value to be used
The third of the three processing functions for the
encryption and decryption.
@param D the input to be processed
@param Kmi the mask to be used from Km[n]
@param Kri the rotation value to be used
Does the 16 rounds to encrypt the block.
@param L0 the LH-32bits of the plaintext block
@param R0 the RH-32bits of the plaintext block
A class that provides CAST6 key encryption operations,
such as encoding data and generating keys.
All the algorithms herein are from the Internet RFC
RFC2612 - CAST6 (128bit block, 128-256bit key)
and implement a simplified cryptography interface.
Does the 12 quad rounds rounds to encrypt the block.
@param A the 00-31 bits of the plaintext block
@param B the 32-63 bits of the plaintext block
@param C the 64-95 bits of the plaintext block
@param D the 96-127 bits of the plaintext block
@param result the resulting ciphertext
Does the 12 quad rounds rounds to decrypt the block.
@param A the 00-31 bits of the ciphertext block
@param B the 32-63 bits of the ciphertext block
@param C the 64-95 bits of the ciphertext block
@param D the 96-127 bits of the ciphertext block
@param result the resulting plaintext
Implementation of Daniel J. Bernstein's ChaCha stream cipher.
Creates a 20 rounds ChaCha engine.
Implementation of Daniel J. Bernstein's ChaCha stream cipher.
Creates a 20 rounds ChaCha engine.
Creates a ChaCha engine with a specific number of rounds.
the number of rounds (must be an even number).
A class that provides a basic DESede (or Triple DES) engine.
initialise a DESede cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
* Wrap keys according to
*
* draft-ietf-smime-key-wrap-01.txt.
*
* Note:
*
* - this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
* - if you are using this to wrap triple-des keys you need to set the
* parity bits on the key and, if it's a two-key triple-des key, pad it
* yourself.
*
*
Field engine
Field param
Field paramPlusIV
Field iv
Field forWrapping
Field IV2
Method init
@param forWrapping
@param param
Method GetAlgorithmName
@return
Method wrap
@param in
@param inOff
@param inLen
@return
Method unwrap
@param in
@param inOff
@param inLen
@return
@throws InvalidCipherTextException
Some key wrap algorithms make use of the Key Checksum defined
in CMS [CMS-Algorithms]. This is used to provide an integrity
check value for the key being wrapped. The algorithm is
- Compute the 20 octet SHA-1 hash on the key being wrapped.
- Use the first 8 octets of this hash as the checksum value.
@param key
@return
@throws Exception
@see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
@param key
@param checksum
@return
@see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
A class that provides a basic DES engine.
initialise a DES cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
what follows is mainly taken from "Applied Cryptography", by
Bruce Schneier, however it also bears great resemblance to Richard
Outerbridge's D3DES...
Generate an integer based working key based on our secret key
and what we processing we are planning to do.
Acknowledgements for this routine go to James Gillogly and Phil Karn.
(whoever, and wherever they are!).
implementation of DSTU 7624 (Kalyna)
this does your basic ElGamal algorithm.
initialise the ElGamal engine.
@param forEncryption true if we are encrypting, false otherwise.
@param param the necessary ElGamal key parameters.
Return the maximum size for an input block to this engine.
For ElGamal this is always one byte less than the size of P on
encryption, and twice the length as the size of P on decryption.
@return maximum size for an input block.
Return the maximum size for an output block to this engine.
For ElGamal this is always one byte less than the size of P on
decryption, and twice the length as the size of P on encryption.
@return maximum size for an output block.
Process a single block using the basic ElGamal algorithm.
@param in the input array.
@param inOff the offset into the input buffer where the data starts.
@param length the length of the data to be processed.
@return the result of the ElGamal process.
@exception DataLengthException the input block is too large.
implementation of GOST 28147-89
standard constructor.
initialise an Gost28147 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is inappropriate.
Return the S-Box associated with SBoxName
@param sBoxName name of the S-Box
@return byte array representing the S-Box
Constants
Variables to hold the state of the engine during encryption and
decryption
Initialize a Grain-128AEAD cipher.
@param forEncryption Whether or not we are for encryption.
@param param The parameters required to set up the cipher.
@throws ArgumentException If the params argument is inappropriate.
320 clocks initialization phase.
Get output from non-linear function g(x).
@return Output from NFSR.
Get output from linear function f(x).
@return Output from LFSR.
Get output from output function h(x).
@return y_t.
Shift array 1 bit and add val to index.Length - 1.
@param array The array to shift.
@param val The value to shift in.
@return The shifted array with val added to index.Length - 1.
Set keys, reset cipher.
@param keyBytes The key.
@param ivBytes The IV.
HC-128 is a software-efficient stream cipher created by Hongjun Wu. It
generates keystream from a 128-bit secret key and a 128-bit initialization
vector.
http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf
It is a third phase candidate in the eStream contest, and is patent-free.
No attacks are known as of today (April 2007). See
http://www.ecrypt.eu.org/stream/hcp3.html
Initialise a HC-128 cipher.
@param forEncryption whether or not we are for encryption. Irrelevant, as
encryption and decryption are the same.
@param params the parameters required to set up the cipher.
@throws ArgumentException if the params argument is
inappropriate (ie. the key is not 128 bit long).
HC-256 is a software-efficient stream cipher created by Hongjun Wu. It
generates keystream from a 256-bit secret key and a 256-bit initialization
vector.
http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf
Its brother, HC-128, is a third phase candidate in the eStream contest.
The algorithm is patent-free. No attacks are known as of today (April 2007).
See
http://www.ecrypt.eu.org/stream/hcp3.html
Initialise a HC-256 cipher.
@param forEncryption whether or not we are for encryption. Irrelevant, as
encryption and decryption are the same.
@param params the parameters required to set up the cipher.
@throws ArgumentException if the params argument is
inappropriate (ie. the key is not 256 bit long).
A class that provides a basic International Data Encryption Algorithm (IDEA) engine.
This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM"
implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (barring 1 typo at the
end of the MulInv function!).
It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/
Note: This algorithm was patented in the USA, Japan and Europe. These patents expired in 2011/2012.
standard constructor.
initialise an IDEA cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return x = x * y where the multiplication is done modulo
65537 (0x10001) (as defined in the IDEA specification) and
a zero input is taken to be 65536 (0x10000).
@param x the x value
@param y the y value
@return x = x * y
The following function is used to expand the user key to the encryption
subkey. The first 16 bytes are the user key, and the rest of the subkey
is calculated by rotating the previous 16 bytes by 25 bits to the left,
and so on until the subkey is completed.
This function computes multiplicative inverse using Euclid's Greatest
Common Divisor algorithm. Zero and one are self inverse.
i.e. x * MulInv(x) == 1 (modulo BASE)
Return the additive inverse of x.
i.e. x + AddInv(x) == 0
The function to invert the encryption subkey to the decryption subkey.
It also involves the multiplicative inverse and the additive inverse functions.
support class for constructing intergrated encryption ciphers
for doing basic message exchanges on top of key agreement ciphers
set up for use with stream mode, where the key derivation function
is used to provide a stream of bytes to xor with the message.
@param agree the key agreement used as the basis for the encryption
@param kdf the key derivation function used for byte generation
@param mac the message authentication code generator for the message
set up for use in conjunction with a block cipher to handle the
message.
@param agree the key agreement used as the basis for the encryption
@param kdf the key derivation function used for byte generation
@param mac the message authentication code generator for the message
@param cipher the cipher to used for encrypting the message
Initialise the encryptor.
@param forEncryption whether or not this is encryption/decryption.
@param privParam our private key parameters
@param pubParam the recipient's/sender's public key parameters
@param param encoding and derivation parameters.
Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
see: http://www.burtleburtle.net/bob/rand/isaacafa.html
initialise an ISAAC cipher.
@param forEncryption whether or not we are for encryption.
@param params the parameters required to set up the cipher.
@exception ArgumentException if the params argument is
inappropriate.
NaccacheStern Engine. For details on this cipher, please see
http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
Initializes this algorithm. Must be called before all other Functions.
@see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool,
org.bouncycastle.crypto.CipherParameters)
Returns the input block size of this algorithm.
@see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize()
Returns the output block size of this algorithm.
@see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize()
Process a single Block using the Naccache-Stern algorithm.
@see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[],
int, int)
Encrypts a BigInteger aka Plaintext with the public key.
@param plain
The BigInteger to encrypt
@return The byte[] representation of the encrypted BigInteger (i.e.
crypted.toByteArray())
Adds the contents of two encrypted blocks mod sigma
@param block1
the first encrypted block
@param block2
the second encrypted block
@return encrypt((block1 + block2) mod sigma)
@throws InvalidCipherTextException
Convenience Method for data exchange with the cipher.
Determines blocksize and splits data to blocksize.
@param data the data to be processed
@return the data after it went through the NaccacheSternEngine.
@throws InvalidCipherTextException
Computes the integer x that is expressed through the given primes and the
congruences with the chinese remainder theorem (CRT).
@param congruences
the congruences c_i
@param primes
the primes p_i
@return an integer x for that x % p_i == c_i
A Noekeon engine, using direct-key mode.
Create an instance of the Noekeon encryption algorithm
and set some defaults
initialise
@param forEncryption whether or not we are for encryption.
@param params the parameters required to set up the cipher.
@exception ArgumentException if the params argument is
inappropriate.
an implementation of RC2 as described in RFC 2268
"A Description of the RC2(r) Encryption Algorithm" R. Rivest.
initialise a RC2 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the result rotating the 16 bit number in x left by y
Wrap keys according to RFC 3217 - RC2 mechanism
Field engine
Field param
Field paramPlusIV
Field iv
Field forWrapping
Field IV2
Method init
@param forWrapping
@param param
Method GetAlgorithmName
@return
Method wrap
@param in
@param inOff
@param inLen
@return
Method unwrap
@param in
@param inOff
@param inLen
@return
@throws InvalidCipherTextException
Some key wrap algorithms make use of the Key Checksum defined
in CMS [CMS-Algorithms]. This is used to provide an integrity
check value for the key being wrapped. The algorithm is
- Compute the 20 octet SHA-1 hash on the key being wrapped.
- Use the first 8 octets of this hash as the checksum value.
@param key
@return
@throws Exception
@see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
@param key
@param checksum
@return
@see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
initialise a RC4 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
The specification for RC5 came from the RC5 Encryption Algorithm
publication in RSA CryptoBytes, Spring of 1995.
http://www.rsasecurity.com/rsalabs/cryptobytes.
This implementation has a word size of 32 bits.
Create an instance of the RC5 encryption algorithm
and set some defaults
initialise a RC5-32 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Re-key the cipher.
@param key the key to be used
The specification for RC5 came from the RC5 Encryption Algorithm
publication in RSA CryptoBytes, Spring of 1995.
http://www.rsasecurity.com/rsalabs/cryptobytes.
This implementation is set to work with a 64 bit word size.
Create an instance of the RC5 encryption algorithm
and set some defaults
initialise a RC5-64 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Re-key the cipher.
@param key the key to be used
An RC6 engine.
Create an instance of the RC6 encryption algorithm
and set some defaults
initialise a RC5-32 cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Re-key the cipher.
@param inKey the key to be used
an implementation of the RFC 3211 Key Wrap
Specification.
An implementation of the AES Key Wrapper from the NIST Key Wrap
Specification as described in RFC 3394.
For further details see: http://www.ietf.org/rfc/rfc3394.txt
and http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
an implementation of Rijndael, based on the documentation and reference implementation
by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
Note: this implementation is based on information prior to readonly NIST publication.
multiply two elements of GF(2^m)
needed for MixColumn and InvMixColumn
xor corresponding text input and round key input bytes
Row 0 remains unchanged
The other three rows are shifted a variable amount
Replace every byte of the input by the byte at that place
in the nonlinear S-box
Mix the bytes of every column in a linear way
Mix the bytes of every column in a linear way
This is the opposite operation of Mixcolumn
Calculate the necessary round keys
The number of calculations depends on keyBits and blockBits
default constructor - 128 bit block size.
basic constructor - set the cipher up for a given blocksize
@param blocksize the blocksize in bits, must be 128, 192, or 256.
initialise a Rijndael cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
this does your basic RSA algorithm with blinding
initialise the RSA engine.
@param forEncryption true if we are encrypting, false otherwise.
@param param the necessary RSA key parameters.
Return the maximum size for an input block to this engine.
For RSA this is always one byte less than the key size on
encryption, and the same length as the key size on decryption.
@return maximum size for an input block.
Return the maximum size for an output block to this engine.
For RSA this is always one byte less than the key size on
decryption, and the same length as the key size on encryption.
@return maximum size for an output block.
Process a single block using the basic RSA algorithm.
@param inBuf the input array.
@param inOff the offset into the input buffer where the data starts.
@param inLen the length of the data to be processed.
@return the result of the RSA process.
@exception DataLengthException the input block is too large.
This does your basic RSA Chaum's blinding and unblinding as outlined in
"Handbook of Applied Cryptography", page 475. You need to use this if you are
trying to get another party to generate signatures without them being aware
of the message they are signing.
Initialise the blinding engine.
@param forEncryption true if we are encrypting (blinding), false otherwise.
@param param the necessary RSA key parameters.
Return the maximum size for an input block to this engine.
For RSA this is always one byte less than the key size on
encryption, and the same length as the key size on decryption.
@return maximum size for an input block.
Return the maximum size for an output block to this engine.
For RSA this is always one byte less than the key size on
decryption, and the same length as the key size on encryption.
@return maximum size for an output block.
Process a single block using the RSA blinding algorithm.
@param in the input array.
@param inOff the offset into the input buffer where the data starts.
@param inLen the length of the data to be processed.
@return the result of the RSA process.
@throws DataLengthException the input block is too large.
this does your basic RSA algorithm.
initialise the RSA engine.
@param forEncryption true if we are encrypting, false otherwise.
@param param the necessary RSA key parameters.
Return the maximum size for an input block to this engine.
For RSA this is always one byte less than the key size on
encryption, and the same length as the key size on decryption.
@return maximum size for an input block.
Return the maximum size for an output block to this engine.
For RSA this is always one byte less than the key size on
decryption, and the same length as the key size on encryption.
@return maximum size for an output block.
this does your basic RSA algorithm.
initialise the RSA engine.
@param forEncryption true if we are encrypting, false otherwise.
@param param the necessary RSA key parameters.
Return the maximum size for an input block to this engine.
For RSA this is always one byte less than the key size on
encryption, and the same length as the key size on decryption.
@return maximum size for an input block.
Return the maximum size for an output block to this engine.
For RSA this is always one byte less than the key size on
decryption, and the same length as the key size on encryption.
@return maximum size for an output block.
Process a single block using the basic RSA algorithm.
@param inBuf the input array.
@param inOff the offset into the input buffer where the data starts.
@param inLen the length of the data to be processed.
@return the result of the RSA process.
@exception DataLengthException the input block is too large.
Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
Constants
Creates a 20 round Salsa20 engine.
Creates a Salsa20 engine with a specific number of rounds.
the number of rounds (must be an even number).
Implementation of the SEED algorithm as described in RFC 4009
An implementation of the SEED key wrapper based on RFC 4010/RFC 3394.
For further details see: http://www.ietf.org/rfc/rfc4010.txt.
* Serpent is a 128-bit 32-round block cipher with variable key lengths,
* including 128, 192 and 256 bit keys conjectured to be at least as
* secure as three-key triple-DES.
*
* Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
* candidate algorithm for the NIST AES Quest.
*
*
* For full details see The Serpent home page
*
Expand a user-supplied key material into a session key.
@param key The user-key bytes (multiples of 4) to use.
@exception ArgumentException
initialise a Serpent cipher.
@param encrypting whether or not we are for encryption.
@param params the parameters required to set up the cipher.
@throws IllegalArgumentException if the params argument is
inappropriate.
Process one block of input from the array in and write it to
the out array.
@param in the array containing the input data.
@param inOff offset into the in array the data starts at.
@param out the array the output data will be copied into.
@param outOff the offset into the out array the output will start at.
@return the number of bytes processed and produced.
@throws DataLengthException if there isn't enough data in in, or
space in out.
@throws IllegalStateException if the cipher isn't initialised.
InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
Apply the linear transformation to the register set.
Apply the inverse of the linear transformation to the register set.
a class that provides a basic SKIPJACK engine.
initialise a SKIPJACK cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
The G permutation
the inverse of the G permutation.
SM2 public key encryption engine - based on https://tools.ietf.org/html/draft-shen-sm2-ecdsa-02.
SM4 Block Cipher - SM4 is a 128 bit block cipher with a 128 bit key.
The implementation here is based on the document http://eprint.iacr.org/2008/329.pdf
by Whitfield Diffie and George Ledin, which is a translation of Prof. LU Shu-wang's original standard.
An TEA engine.
Create an instance of the TEA encryption algorithm
and set some defaults
initialise
@param forEncryption whether or not we are for encryption.
@param params the parameters required to set up the cipher.
@exception ArgumentException if the params argument is
inappropriate.
Re-key the cipher.
@param key the key to be used
Implementation of the Threefish tweakable large block cipher in 256, 512 and 1024 bit block
sizes.
This is the 1.3 version of Threefish defined in the Skein hash function submission to the NIST
SHA-3 competition in October 2010.
Threefish was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
This implementation inlines all round functions, unrolls 8 rounds, and uses 1.2k of static tables
to speed up key schedule injection.
2 x block size state is retained by each cipher instance.
256 bit block size - Threefish-256
512 bit block size - Threefish-512
1024 bit block size - Threefish-1024
Size of the tweak in bytes (always 128 bit/16 bytes)
Rounds in Threefish-256
Rounds in Threefish-512
Rounds in Threefish-1024
Max rounds of any of the variants
Key schedule parity constant
Block size in bytes
Block size in 64 bit words
Buffer for byte oriented processBytes to call internal word API
Tweak bytes (2 byte t1,t2, calculated t3 and repeat of t1,t2 for modulo free lookup
Key schedule words
The internal cipher implementation (varies by blocksize)
Constructs a new Threefish cipher, with a specified block size.
the block size in bits, one of , ,
.
Initialise the engine.
Initialise for encryption if true, for decryption if false.
an instance of or (to
use a 0 tweak)
Initialise the engine, specifying the key and tweak directly.
the cipher mode.
the words of the key, or null
to use the current key.
the 2 word (128 bit) tweak, or null
to use the current tweak.
Process a block of data represented as 64 bit words.
the number of 8 byte words processed (which will be the same as the block size).
a block sized buffer of words to process.
a block sized buffer of words to receive the output of the operation.
if either the input or output is not block sized
if this engine is not initialised
Rotate left + xor part of the mix operation.
Rotate xor + rotate right part of the unmix operation.
The extended + repeated tweak words
The extended + repeated key words
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Mix rotation constants defined in Skein 1.3 specification
Tnepres is a 128-bit 32-round block cipher with variable key lengths,
including 128, 192 and 256 bit keys conjectured to be at least as
secure as three-key triple-DES.
Tnepres is based on Serpent which was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
candidate algorithm for the NIST AES Quest. Unfortunately there was an endianness issue
with test vectors in the AES submission and the resulting confusion lead to the Tnepres cipher
as well, which is a byte swapped version of Serpent.
For full details see The Serpent home page
Expand a user-supplied key material into a session key.
@param key The user-key bytes (multiples of 4) to use.
@exception ArgumentException
A class that provides Twofish encryption operations.
This Java implementation is based on the Java reference
implementation provided by Bruce Schneier and developed
by Raif S. Naffah.
Define the fixed p0/p1 permutations used in keyed S-box lookup.
By changing the following constant definitions, the S-boxes will
automatically Get changed in the Twofish engine.
gSubKeys[] and gSBox[] are eventually used in the
encryption and decryption methods.
initialise a Twofish cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Encrypt the given input starting at the given offset and place
the result in the provided buffer starting at the given offset.
The input will be an exact multiple of our blocksize.
encryptBlock uses the pre-calculated gSBox[] and subKey[]
arrays.
Decrypt the given input starting at the given offset and place
the result in the provided buffer starting at the given offset.
The input will be an exact multiple of our blocksize.
Use (12, 8) Reed-Solomon code over GF(256) to produce
a key S-box 32-bit entity from 2 key material 32-bit
entities.
@param k0 first 32-bit entity
@param k1 second 32-bit entity
@return Remainder polynomial Generated using RS code
* Reed-Solomon code parameters: (12,8) reversible code:
*
*
* G(x) = x^4 + (a+1/a)x^3 + ax^2 + (a+1/a)x + 1
*
* where a = primitive root of field generator 0x14D
*
initialise a VMPC cipher.
@param forEncryption
whether or not we are for encryption.
@param params
the parameters required to set up the cipher.
@exception ArgumentException
if the params argument is inappropriate.
Implementation of Daniel J. Bernstein's XSalsa20 stream cipher - Salsa20 with an extended nonce.
XSalsa20 requires a 256 bit key, and a 192 bit nonce.
XSalsa20 key generation: process 256 bit input key and 128 bits of the input nonce
using a core Salsa20 function without input addition to produce 256 bit working key
and use that with the remaining 64 bits of nonce to initialize a standard Salsa20 engine state.
An XTEA engine.
Create an instance of the TEA encryption algorithm
and set some defaults
initialise
@param forEncryption whether or not we are for encryption.
@param params the parameters required to set up the cipher.
@exception ArgumentException if the params argument is
inappropriate.
Re-key the cipher.
@param key the key to be used
Base class for format-preserving encryption.
Process length bytes from inBuf, writing the output to outBuf.
number of bytes output.
input data.
offset in input data to start at.
number of bytes to process.
destination buffer.
offset to start writing at in destination buffer.
Initialize the FPE engine for encryption/decryption.
number of bytes output.
true if initialising for encryption, false otherwise.
the key and other parameters to use to set the engine up.
Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
This implementation is based on ISO 18033/P1363a.
Construct a KDF Parameters generator.
@param counterStart value of counter.
@param digest the digest to be used as the source of derived keys.
return the underlying digest.
fill len bytes of the output buffer with bytes generated from
the derivation function.
@throws ArgumentException if the size of the request will cause an overflow.
@throws DataLengthException if the out buffer is too small.
Core of password hashing scheme Bcrypt,
designed by Niels Provos and David Mazières,
corresponds to the C reference implementation.
This implementation does not correspondent to the 1999 published paper
"A Future-Adaptable Password Scheme" of Niels Provos and David Mazières,
see: https://www.usenix.org/legacy/events/usenix99/provos/provos_html/node1.html.
In contrast to the paper, the order of key setup and salt setup is reversed:
state <- ExpandKey(state, 0, key)
state %lt;- ExpandKey(state, 0, salt)
This corresponds to the OpenBSD reference implementation of Bcrypt.
Note:
There is no successful cryptanalysis (status 2015), but
the amount of memory and the band width of Bcrypt
may be insufficient to effectively prevent attacks
with custom hardware like FPGAs, ASICs
This implementation uses some parts of Bouncy Castle's BlowfishEngine.
Derives a raw 192 bit Bcrypt key
@param cost the cost factor, treated as an exponent of 2
@param salt a 16 byte salt
@param psw the password
@return a 192 bit key
Size of the salt parameter in bytes
Minimum value of cost parameter, equal to log2(bytes of salt)
Maximum value of cost parameter (31 == 2,147,483,648)
Maximum size of password == max (unrestricted) size of Blowfish key
Converts a character password to bytes incorporating the required trailing zero byte.
@param password the password to be encoded.
@return a byte representation of the password in UTF8 + trailing zero.
Calculates the bcrypt hash of a password.
This implements the raw bcrypt function as defined in the bcrypt specification, not
the crypt encoded version implemented in OpenBSD.
@param password the password bytes (up to 72 bytes) to use for this invocation.
@param salt the 128 bit salt to use for this invocation.
@param cost the bcrypt cost parameter. The cost of the bcrypt function grows as
2^cost
. Legal values are 4..31 inclusive.
@return the output of the raw bcrypt operation: a 192 bit (24 byte) hash.
initialise the key generator - if strength is set to zero
the key Generated will be 192 bits in size, otherwise
strength can be 128 or 192 (or 112 or 168 if you don't count
parity bits), depending on whether you wish to do 2-key or 3-key
triple DES.
@param param the parameters to be used for key generation
initialise the key generator - if strength is set to zero
the key generated will be 64 bits in size, otherwise
strength can be 64 or 56 bits (if you don't count the parity bits).
@param param the parameters to be used for key generation
a basic Diffie-Hellman key pair generator.
This generates keys consistent for use with the basic algorithm for
Diffie-Hellman.
a Diffie-Hellman key pair generator.
This generates keys consistent for use in the MTI/A0 key agreement protocol
as described in "Handbook of Applied Cryptography", Pages 516-519.
which Generates the p and g values from the given parameters,
returning the DHParameters object.
Note: can take a while...
a DSA key pair generator.
This Generates DSA keys in line with the method described
in FIPS 186-3 B.1 FFC Key Pair Generation.
Generate suitable parameters for DSA, in line with FIPS 186-2, or FIPS 186-3.
Initialise the generator
This form can only be used for older DSA (pre-DSA2) parameters
the size of keys in bits (from 512 up to 1024, and a multiple of 64)
measure of robustness of primes (at least 80 for FIPS 186-2 compliance)
the source of randomness to use
Initialise the generator for DSA 2
You must use this Init method if you need to generate parameters for DSA 2 keys
An instance of DsaParameterGenerationParameters used to configure this generator
Generates a set of DsaParameters
Can take a while...
generate suitable parameters for DSA, in line with
FIPS 186-3 A.1 Generation of the FFC Primes p and q.
Given the domain parameters this routine generates an EC key
pair in accordance with X9.62 section 5.2.1 pages 26, 27.
a ElGamal key pair generator.
This Generates keys consistent for use with ElGamal as described in
page 164 of "Handbook of Applied Cryptography".
* which Generates the p and g values from the given parameters,
* returning the ElGamalParameters object.
*
* Note: can take a while...
*
a GOST3410 key pair generator.
This generates GOST3410 keys in line with the method described
in GOST R 34.10-94.
generate suitable parameters for GOST3410.
initialise the key generator.
@param size size of the key
@param typeProcedure type procedure A,B = 1; A',B' - else
@param random random byte source.
Procedure C
procedure generates the a value from the given p,q,
returning the a value.
which generates the p , q and a values from the given parameters,
returning the Gost3410Parameters object.
HMAC-based Extract-and-Expand Key Derivation Function (HKDF) implemented
according to IETF RFC 5869, May 2010 as specified by H. Krawczyk, IBM
Research & P. Eronen, Nokia. It uses a HMac internally to compute de OKM
(output keying material) and is likely to have better security properties
than KDF's based on just a hash function.
Creates a HKDFBytesGenerator based on the given hash function.
@param hash the digest to be used as the source of generatedBytes bytes
Performs the extract part of the key derivation function.
@param salt the salt to use
@param ikm the input keying material
@return the PRK as KeyParameter
Performs the expand part of the key derivation function, using currentT
as input and output buffer.
@throws DataLengthException if the total number of bytes generated is larger than the one
specified by RFC 5869 (255 * HashLen)
KFD1 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
This implementation is based on IEEE P1363/ISO 18033.
Construct a KDF1 byte generator.
@param digest the digest to be used as the source of derived keys.
KDF2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
This implementation is based on IEEE P1363/ISO 18033.
Construct a KDF2 bytes generator. Generates key material
according to IEEE P1363 or ISO 18033 depending on the initialisation.
@param digest the digest to be used as the source of derived keys.
Generator for MGF1 as defined in Pkcs 1v2
the digest to be used as the source of generated bytes
the underlying digest.
Fill len bytes of the output buffer with bytes generated from the derivation function.
Key generation parameters for NaccacheStern cipher. For details on this cipher, please see
http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
Generates a permuted ArrayList from the original one. The original List
is not modified
@param arr
the ArrayList to be permuted
@param rand
the source of Randomness for permutation
@return a new IList with the permuted elements.
Finds the first 'count' primes starting with 3
@param count
the number of primes to find
@return a vector containing the found primes as Integer
Password hashing scheme BCrypt,
designed by Niels Provos and David Mazières, using the
String format and the Base64 encoding
of the reference implementation on OpenBSD
Creates a 60 character Bcrypt String, including
version, cost factor, salt and hash, separated by '$'
@param version the version, 2y,2b or 2a. (2a is not backwards compatible.)
@param cost the cost factor, treated as an exponent of 2
@param salt a 16 byte salt
@param password the password
@return a 60 character Bcrypt String
Creates a 60 character Bcrypt String, including
version, cost factor, salt and hash, separated by '$' using version
'2y'.
@param cost the cost factor, treated as an exponent of 2
@param salt a 16 byte salt
@param password the password
@return a 60 character Bcrypt String
Creates a 60 character Bcrypt String, including
version, cost factor, salt and hash, separated by '$'
@param version the version, may be 2b, 2y or 2a. (2a is not backwards compatible.)
@param cost the cost factor, treated as an exponent of 2
@param salt a 16 byte salt
@param password the password
@return a 60 character Bcrypt String
Checks if a password corresponds to a 60 character Bcrypt String
@param bcryptString a 60 character Bcrypt String, including
version, cost factor, salt and hash,
separated by '$'
@param password the password as an array of chars
@return true if the password corresponds to the
Bcrypt String, otherwise false
Generator for PBE derived keys and IVs as usd by OpenSSL. Originally this scheme was a simple extension of
PKCS 5 V2.0 Scheme 1 using MD5 with an iteration count of 1. The default digest was changed to SHA-256 with
OpenSSL 1.1.0. This implementation still defaults to MD5, but the digest can now be set.
Construct a OpenSSL Parameters generator - digest the original MD5.
Construct a OpenSSL Parameters generator - digest as specified.
the digest to use as the PRF.
Initialise - note the iteration count for this algorithm is fixed at 1.
@param password password to use.
@param salt salt to use.
the derived key function, the ith hash of the password and the salt.
Generate a key parameter for use with a MAC derived from the password,
salt, and iteration count we are currently initialised with.
@param keySize the size of the key we want (in bits)
@return a KeyParameter object.
@exception ArgumentException if the key length larger than the base hash size.
Generator for Pbe derived keys and ivs as defined by Pkcs 12 V1.0.
The document this implementation is based on can be found at
RSA's Pkcs12 Page
Construct a Pkcs 12 Parameters generator.
@param digest the digest to be used as the source of derived keys.
@exception ArgumentException if an unknown digest is passed in.
add a + b + 1, returning the result in a. The a value is treated
as a BigInteger of length (b.Length * 8) bits. The result is
modulo 2^b.Length in case of overflow.
generation of a derived key ala Pkcs12 V1.0.
Generate a key parameter for use with a MAC derived from the password,
salt, and iteration count we are currently initialised with.
@param keySize the size of the key we want (in bits)
@return a KeyParameter object.
Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 1.
Note this generator is limited to the size of the hash produced by the
digest used to drive it.
The document this implementation is based on can be found at
RSA's Pkcs5 Page
Construct a Pkcs 5 Scheme 1 Parameters generator.
@param digest the digest to be used as the source of derived keys.
the derived key function, the ith hash of the mPassword and the mSalt.
Generate a key parameter for use with a MAC derived from the mPassword,
mSalt, and iteration count we are currently initialised with.
@param keySize the size of the key we want (in bits)
@return a KeyParameter object.
@exception ArgumentException if the key length larger than the base hash size.
Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 2.
This generator uses a SHA-1 HMac as the calculation function.
The document this implementation is based on can be found at
RSA's Pkcs5 Page
construct a Pkcs5 Scheme 2 Parameters generator.
Generate a key parameter for use with a MAC derived from the password,
salt, and iteration count we are currently initialised with.
@param keySize the size of the key we want (in bits)
@return a KeyParameter object.
Generates keys for the Poly1305 MAC.
Poly1305 keys are 256 bit keys consisting of a 128 bit secret key used for the underlying block
cipher followed by a 128 bit {@code r} value used for the polynomial portion of the Mac.
The {@code r} value has a specific format with some bits required to be cleared, resulting in an
effective 106 bit key.
A separately generated 256 bit key can be modified to fit the Poly1305 key format by using the
{@link #clamp(byte[])} method to clear the required bits.
Initialises the key generator.
Poly1305 keys are always 256 bits, so the key length in the provided parameters is ignored.
Generates a 256 bit key in the format required for Poly1305 - e.g.
k[0] ... k[15], r[0] ... r[15]
with the required bits in r
cleared
as per .
Modifies an existing 32 byte key value to comply with the requirements of the Poly1305 key by
clearing required bits in the r
(second 16 bytes) portion of the key.
Specifically:
- r[3], r[7], r[11], r[15] have top four bits clear (i.e., are {0, 1, . . . , 15})
- r[4], r[8], r[12] have bottom two bits clear (i.e., are in {0, 4, 8, . . . , 252})
a 32 byte key value k[0] ... k[15], r[0] ... r[15]
Checks a 32 byte key for compliance with the Poly1305 key requirements, e.g.
k[0] ... k[15], r[0] ... r[15]
with the required bits in r
cleared
as per .
Key.
if the key is of the wrong length, or has invalid bits set
in the r
portion of the key.
Generate a random factor suitable for use with RSA blind signatures
as outlined in Chaum's blinding and unblinding as outlined in
"Handbook of Applied Cryptography", page 475.
Initialise the factor generator
@param param the necessary RSA key parameters.
Generate a suitable blind factor for the public key the generator was initialised with.
@return a random blind factor
an RSA key pair generator.
Choose a random prime value for use with RSA
the bit-length of the returned prime
the RSA public exponent
a prime p, with (p-1) relatively prime to e
Implementation of the scrypt a password-based key derivation function.
Scrypt was created by Colin Percival and is specified in
draft-josefsson-scrypt-kd.
Generate a key using the scrypt key derivation function.
the bytes of the pass phrase.
the salt to use for this invocation.
CPU/Memory cost parameter. Must be larger than 1, a power of 2 and less than
2^(128 * r / 8)
.
the block size, must be >= 1.
Parallelization parameter. Must be a positive integer less than or equal to
int.MaxValue / (128 * r * 8)
.
the length of the key to generate.
the generated key.
Base interface for mapping from an alphabet to a set of indexes
suitable for use with FPE.
Return the number of characters in the alphabet.
the radix for the alphabet.
Return the passed in char[] as a byte array of indexes (indexes
can be more than 1 byte)
an index array.
characters to be mapped.
Return a char[] for this alphabet based on the indexes passed.
an array of char corresponding to the index values.
input array of indexes.
Base interface for a public/private key block cipher.
The name of the algorithm this cipher implements.
Initialise the cipher.
Initialise for encryption if true, for decryption if false.
The key or other data required by the cipher.
The maximum size, in bytes, an input block may be.
The maximum size, in bytes, an output block will be.
Process a block.
The input buffer.
The offset into inBuf that the input block begins.
The length of the input block.
Input decrypts improperly.
Input is too large for the cipher.
interface that a public/private key pair generator should conform to.
intialise the key pair generator.
@param the parameters the key pair is to be initialised with.
return an AsymmetricCipherKeyPair containing the Generated keys.
@return an AsymmetricCipherKeyPair containing the Generated keys.
The basic interface that basic Diffie-Hellman implementations
conforms to.
initialise the agreement engine.
return the field size for the agreement algorithm in bytes.
given a public key from a given party calculate the next
message in the agreement sequence.
Base interface for a symmetric key block cipher.
The name of the algorithm this cipher implements.
Initialise the cipher.
Initialise for encryption if true, for decryption if false.
The key or other data required by the cipher.
The block size for this cipher, in bytes.
Process a block.
The input buffer.
The offset into inBuf that the input block begins.
The output buffer.
The offset into outBuf to write the output block.
If input block is wrong size, or outBuf too small.
The number of bytes processed and produced.
Process a block.
The input block as a span.
The output span.
If input block is wrong size, or output span too small.
The number of bytes processed and produced.
Operators that reduce their input to a single block return an object
of this type.
Return the final result of the operation.
A block of bytes, representing the result of an operation.
Store the final result of the operation by copying it into the destination array.
The number of bytes copied into destination.
The byte array to copy the result into.
The offset into destination to start copying the result at.
Store the final result of the operation by copying it into the destination span.
The number of bytes copied into destination.
The span to copy the result into.
Block cipher engines are expected to conform to this interface.
The name of the algorithm this cipher implements.
Initialise the cipher.
If true the cipher is initialised for encryption,
if false for decryption.
The key and other data required by the cipher.
Reset the cipher. After resetting the cipher is in the same state
as it was after the last init (if there was one).
Base interface for a ciphers that do not require data to be block aligned.
Note: In cases where the underlying algorithm is block based, these ciphers may add or remove padding as needed.
Return the size of the output buffer required for a Write() plus a
close() with the write() being passed inputLen bytes.
The returned size may be dependent on the initialisation of this cipher
and may not be accurate once subsequent input data is processed as the cipher may
add, add or remove padding, as it sees fit.
The space required to accommodate a call to processBytes and doFinal with inputLen bytes of input.
The length of the expected input.
Return the size of the output buffer required for a write() with the write() being
passed inputLen bytes and just updating the cipher output.
The space required to accommodate a call to processBytes with inputLen bytes of input.
The length of the expected input.
Gets the stream for reading/writing data processed/to be processed.
The stream associated with this cipher.
Base interface for cipher builders.
Return the algorithm and parameter details associated with any cipher built.
Return the maximum output size that a given input will produce.
the length of the expected input.
The maximum possible output size that can produced for the expected input length.
Build a cipher that operates on the passed in stream.
The stream to write/read any encrypted/decrypted data.
A cipher based around the given stream.
A cipher builder that can also return the key it was initialized with.
Return the key we were initialized with.
all parameter classes implement this.
Interface describing a provider of cipher builders for creating decrypting ciphers.
Return a cipher builder for creating decrypting ciphers.
The algorithm details/parameters to use to create the final cipher.
A new cipher builder.
base interface for general purpose byte derivation functions.
return the message digest used as the basis for the function
Parameters for key/byte stream derivation classes
Base interface for a message digest.
The algorithm name.
Return the size, in bytes, of the digest produced by this message digest.
the size, in bytes, of the digest produced by this message digest.
Return the size, in bytes, of the internal buffer used by this digest.
the size, in bytes, of the internal buffer used by this digest.
Update the message digest with a single byte.
the input byte to be entered.
Update the message digest with a block of bytes.
the byte array containing the data.
the offset into the byte array where the data starts.
the length of the data.
Update the message digest with a span of bytes.
the span containing the data.
Close the digest, producing the final digest value.
This call leaves the digest reset.
the byte array the digest is to be copied into.
the offset into the byte array the digest is to start at.
the number of bytes written
Close the digest, producing the final digest value.
This call leaves the digest reset.
the span the digest is to be copied into.
the number of bytes written
Reset the digest back to its initial state.
Base interface for operator factories that create stream-based digest calculators.
The algorithm details object for calculators made by this factory.
Return the size of the digest associated with this factory.
The length of the digest produced by this calculators from this factory in bytes.
Create a stream calculator for the digest associated with this factory. The stream
calculator is used for the actual operation of entering the data to be digested
and producing the digest block.
A calculator producing an IBlockResult with the final digest in it.
Interface for classes implementing the Digital Signature Algorithm
The algorithm name.
Initialise the signer for signature generation or signature verification.
true if we are generating a signature, false otherwise.
key parameters for signature generation.
Sign the passed in message (usually the output of a hash function).
the message to be signed.
two big integers representing the r and s values respectively.
The order of the group that the r, s values in signatures belong to.
Verify the message message against the signature values r and s.
the message that was supposed to have been signed.
the r signature value.
the s signature value.
Generate an exchange pair based on the recipient public key.
the encapsulated secret.
The length in bytes of the encapsulation.
Generate an exchange pair based on the recipient public key.
An SecretWithEncapsulation derived from the recipient public key.
Base interface describing an entropy source for a DRBG.
Return whether or not this entropy source is regarded as prediction resistant.
true if this instance is prediction resistant; otherwise, false.
Return a byte array of entropy.
The entropy bytes.
Return the number of bits of entropy this source can produce.
The size, in bits, of the return value of getEntropy.
Base interface describing a provider of entropy sources.
Return an entropy source providing a block of entropy.
The size of the block of entropy required.
An entropy source providing bitsRequired blocks of entropy.
Base interface for a key unwrapper.
The parameter set used to configure this key unwrapper.
Unwrap the passed in data.
The array containing the data to be unwrapped.
The offset into cipherText at which the unwrapped data starts.
The length of the data to be unwrapped.
an IBlockResult containing the unwrapped key data.
Base interface for a key wrapper.
The parameter set used to configure this key wrapper.
Wrap the passed in key data.
The key data to be wrapped.
an IBlockResult containing the wrapped key data.
The base interface for implementations of message authentication codes (MACs).
Initialise the MAC.
The key or other data required by the MAC.
The algorithm name.
Return the size, in bytes, of the MAC produced by this implementation.
the size, in bytes, of the MAC produced by this implementation.
Update the MAC with a single byte.
the input byte to be entered.
Update the MAC with a block of bytes.
the byte array containing the data.
the offset into the byte array where the data starts.
the length of the data.
Update the MAC with a span of bytes.
the span containing the data.
Perform final calculations, producing the result MAC.
This call leaves the MAC reset.
the byte array the MAC is to be copied into.
the offset into the byte array the MAC is to start at.
the number of bytes written
Perform final calculations, producing the result MAC.
This call leaves the MAC reset.
the span the MAC is to be copied into.
the number of bytes written
Reset the MAC back to its initial state.
The algorithm details object for this calculator.
Create a stream calculator for this signature calculator. The stream
calculator is used for the actual operation of entering the data to be signed
and producing the signature block.
A calculator producing an IBlockResult with a signature in it.
This exception is thrown whenever we find something we don't expect in a message.
Return the secret associated with the encapsulation.
the secret the encapsulation is for.
Return the data that carries the secret in its encapsulated form.
the encapsulation of the secret.
Base interface for operators that serve as stream-based signature calculators.
The algorithm details object for this calculator.
Create a stream calculator for this signature calculator. The stream
calculator is used for the actual operation of entering the data to be signed
and producing the signature block.
A calculator producing an IBlockResult with a signature in it.
The algorithm name.
Initialise the signer for signing or verification.
true if for signing, false otherwise.
necessary parameters.
Update the signer with a single byte.
the input byte to be entered.
Update the signer with a block of bytes.
the byte array containing the data.
the offset into the byte array where the data starts.
the length of the data.
Update the signer with a span of bytes.
the span containing the data.
Generate a signature for the message we've been loaded with using the key we were initialised with.
A byte array containing the signature for the message.
Return true if the internal state represents the signature described in the passed in array.
an array containing the candidate signature to verify.
true if the internal state represents the signature described in the passed in array.
Reset the signer back to its initial state.
Signer with message recovery.
Returns true if the signer has recovered the full message as
part of signature verification.
@return true if full message recovered.
Returns a reference to what message was recovered (if any).
@return full/partial message, null if nothing.
Perform an update with the recovered message before adding any other data. This must
be the first update method called, and calling it will result in the signer assuming
that further calls to update will include message content past what is recoverable.
@param signature the signature that we are in the process of verifying.
@throws IllegalStateException
Base interface for cryptographic operations such as Hashes, MACs, and Signatures which reduce a stream of data
to a single value.
Return a "sink" stream which only exists to update the implementing object.
A stream to write to in order to update the implementing object.
Return the result of processing the stream. This value is only available once the stream
has been closed.
The result of processing the stream.
The interface stream ciphers conform to.
The name of the algorithm this cipher implements.
Initialise the cipher.
If true the cipher is initialised for encryption,
if false for decryption.
The key and other data required by the cipher.
If the parameters argument is inappropriate.
encrypt/decrypt a single byte returning the result.
the byte to be processed.
the result of processing the input byte.
Process a block of bytes from , putting the result into .
The input byte array.
The offset into input where the data to be processed starts.
The number of bytes to be processed.
The output buffer the processed bytes go into.
The offset into output the processed data starts at.
If the input buffer is too small.
If the output buffer is too small.
Process a block of bytes from , putting the result into .
The input span.
The output span.
If the output span is too small.
Reset the cipher to the same state as it was after the last init (if there was one).
Operators that reduce their input to the validation of a signature produce this type.
Return true if the passed in data matches what is expected by the verification result.
The bytes representing the signature.
true if the signature verifies, false otherwise.
Return true if the length bytes from off in the source array match the signature
expected by the verification result.
Byte array containing the signature.
The offset into the source array where the signature starts.
The number of bytes in source making up the signature.
true if the signature verifies, false otherwise.
Base interface for operators that serve as stream-based signature verifiers.
The algorithm details object for this verifier.
Create a stream calculator for this verifier. The stream
calculator is used for the actual operation of entering the data to be verified
and producing a result which can be used to verify the original signature.
A calculator producing an IVerifier which can verify the signature.
Base interface for a provider to support the dynamic creation of signature verifiers.
Return a signature verfier for signature algorithm described in the passed in algorithm details object.
The details of the signature algorithm verification is required for.
A new signature verifier.
The name of the algorithm this cipher implements.
With FIPS PUB 202 a new kind of message digest was announced which supported extendable output, or variable digest sizes.
This interface provides the extra methods required to support variable output on a digest implementation.
Output the results of the final calculation for this XOF to outLen number of bytes.
output array to write the output bytes to.
offset to start writing the bytes at.
the number of output bytes requested.
the number of bytes written
Output the results of the final calculation for this XOF to fill the output span.
span to fill with the output bytes.
the number of bytes written
Start outputting the results of the final calculation for this XOF. Unlike DoFinal, this method
will continue producing output until the XOF is explicitly reset, or signals otherwise.
output array to write the output bytes to.
offset to start writing the bytes at.
the number of output bytes requested.
the number of bytes written
Start outputting the results of the final calculation for this XOF. Unlike OutputFinal, this method
will continue producing output until the XOF is explicitly reset, or signals otherwise.
span to fill with the output bytes.
the number of bytes written
The base class for parameters to key generators.
initialise the generator with a source of randomness
and a strength (in bits).
@param random the random byte source.
@param strength the size, in bits, of the keys we want to produce.
return the random source associated with this
generator.
@return the generators random source.
return the bit strength for keys produced by this generator,
@return the strength of the keys this generator produces (in bits).
standard CBC Block Cipher MAC - if no padding is specified the default of
pad of zeroes is used.
create a standard MAC based on a CBC block cipher. This will produce an
authentication code half the length of the block size of the cipher.
@param cipher the cipher to be used as the basis of the MAC generation.
create a standard MAC based on a CBC block cipher. This will produce an
authentication code half the length of the block size of the cipher.
@param cipher the cipher to be used as the basis of the MAC generation.
@param padding the padding to be used to complete the last block.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits. This class uses CBC mode as the basis for the
MAC generation.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits. This class uses CBC mode as the basis for the
MAC generation.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
@param padding the padding to be used to complete the last block.
Reset the mac generator.
implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of the
feedback mode.
@param blockSize the block size in bits (note: a multiple of 8)
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/CFB"
and the block size in bits.
return the block size we are operating at.
@return the block size we are operating at (in bytes).
reset the chaining vector back to the IV and reset the underlying
cipher.
create a standard MAC based on a CFB block cipher. This will produce an
authentication code half the length of the block size of the cipher, with
the CFB mode set to 8 bits.
@param cipher the cipher to be used as the basis of the MAC generation.
create a standard MAC based on a CFB block cipher. This will produce an
authentication code half the length of the block size of the cipher, with
the CFB mode set to 8 bits.
@param cipher the cipher to be used as the basis of the MAC generation.
@param padding the padding to be used.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits. This class uses CFB mode as the basis for the
MAC generation.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param cfbBitSize the size of an output block produced by the CFB mode.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits. This class uses CFB mode as the basis for the
MAC generation.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param cfbBitSize the size of an output block produced by the CFB mode.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
@param padding a padding to be used.
Reset the mac generator.
CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC
CMAC is a NIST recomendation - see
csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf
CMAC/OMAC1 is a blockcipher-based message authentication code designed and
analyzed by Tetsu Iwata and Kaoru Kurosawa.
CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message
Authentication Code). OMAC stands for One-Key CBC MAC.
It supports 128- or 64-bits block ciphers, with any key size, and returns
a MAC with dimension less or equal to the block size of the underlying
cipher.
create a standard MAC based on a CBC block cipher (64 or 128 bit block).
This will produce an authentication code the length of the block size
of the cipher.
@param cipher the cipher to be used as the basis of the MAC generation.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128.
Reset the mac generator.
Implementation of DSTU7564 mac mode
implementation of DSTU 7624 MAC
The GMAC specialisation of Galois/Counter mode (GCM) detailed in NIST Special Publication
800-38D.
GMac is an invocation of the GCM mode where no data is encrypted (i.e. all input data to the Mac
is processed as additional authenticated data with the underlying GCM block cipher).
Creates a GMAC based on the operation of a block cipher in GCM mode.
This will produce an authentication code the length of the block size of the cipher.
the cipher to be used in GCM mode to generate the MAC.
Creates a GMAC based on the operation of a 128 bit block cipher in GCM mode.
This will produce an authentication code the length of the block size of the cipher.
the cipher to be used in GCM mode to generate the MAC.
the mac size to generate, in bits. Must be a multiple of 8, between 32 and 128 (inclusive).
Sizes less than 96 are not recommended, but are supported for specialized applications.
Initialises the GMAC - requires a
providing a and a nonce.
implementation of GOST 28147-89 MAC
HMAC implementation based on RFC2104
H(K XOR opad, H(K XOR ipad, text))
Reset the mac generator.
DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC)
This could as well be derived from CBCBlockCipherMac, but then the property mac in the base
class must be changed to protected
create a Retail-MAC based on a CBC block cipher. This will produce an
authentication code of the length of the block size of the cipher.
@param cipher the cipher to be used as the basis of the MAC generation. This must
be DESEngine.
create a Retail-MAC based on a CBC block cipher. This will produce an
authentication code of the length of the block size of the cipher.
@param cipher the cipher to be used as the basis of the MAC generation.
@param padding the padding to be used to complete the last block.
create a Retail-MAC based on a block cipher with the size of the
MAC been given in bits. This class uses single DES CBC mode as the basis for the
MAC generation.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
create a standard MAC based on a block cipher with the size of the
MAC been given in bits. This class uses single DES CBC mode as the basis for the
MAC generation. The final block is decrypted and then encrypted using the
middle and right part of the key.
Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
or 16 bits if being used as a data authenticator (FIPS Publication 113),
and in general should be less than the size of the block cipher as it reduces
the chance of an exhaustive attack (see Handbook of Applied Cryptography).
@param cipher the cipher to be used as the basis of the MAC generation.
@param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
@param padding the padding to be used to complete the last block.
Reset the mac generator.
Poly1305 message authentication code, designed by D. J. Bernstein.
Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
effective key bits) used in the authenticator.
The polynomial calculation in this implementation is adapted from the public domain poly1305-donna-unrolled C implementation
by Andrew M (@floodyberry).
Polynomial key
Polynomial key
Polynomial key
Polynomial key
Polynomial key
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Encrypted nonce
Encrypted nonce
Encrypted nonce
Encrypted nonce
Current block of buffered input
Current offset in input buffer
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
Constructs a Poly1305 MAC, using a 128 bit block cipher.
Initialises the Poly1305 MAC.
a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.
Implementation of SipHash as specified in "SipHash: a fast short-input PRF", by Jean-Philippe
Aumasson and Daniel J. Bernstein (https://131002.net/siphash/siphash.pdf).
"SipHash is a family of PRFs SipHash-c-d where the integer parameters c and d are the number of
compression rounds and the number of finalization rounds. A compression round is identical to a
finalization round and this round function is called SipRound. Given a 128-bit key k and a
(possibly empty) byte string m, SipHash-c-d returns a 64-bit value..."
SipHash-2-4
SipHash-c-d
the number of compression rounds
the number of finalization rounds
Implementation of the Skein parameterised MAC function in 256, 512 and 1024 bit block sizes,
based on the Threefish tweakable block cipher.
This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3
competition in October 2010.
Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
256 bit block size - Skein-256
512 bit block size - Skein-512
1024 bit block size - Skein-1024
Constructs a Skein MAC with an internal state size and output size.
the internal state size in bits - one of or
.
the output/MAC size to produce in bits, which must be an integral number of
bytes.
Optionally initialises the Skein digest with the provided parameters.
See for details on the parameterisation of the Skein hash function.
the parameters to apply to this engine, or null
to use no parameters.
This exception is thrown whenever a cipher requires a change of key, IV or similar after x amount of
bytes enciphered.
implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of chaining.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/CBC".
return the block size of the underlying cipher.
@return the block size of the underlying cipher.
reset the chaining vector back to the IV and reset the underlying
cipher.
Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
NIST Special Publication 800-38C.
Note: this mode is a packet mode - it needs all the data up front.
Basic constructor.
@param cipher the block cipher to be used.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Returns a byte array containing the mac calculated as part of the
last encrypt or decrypt operation.
@return the last mac calculated.
Process a packet of data for either CCM decryption or encryption.
@param in data for processing.
@param inOff offset at which data starts in the input array.
@param inLen length of the data in the input array.
@return a byte array containing the processed input..
@throws IllegalStateException if the cipher is not appropriately set up.
@throws InvalidCipherTextException if the input data is truncated or the mac check fails.
Process a packet of data for either CCM decryption or encryption.
@param in data for processing.
@param inOff offset at which data starts in the input array.
@param inLen length of the data in the input array.
@param output output array.
@param outOff offset into output array to start putting processed bytes.
@return the number of bytes added to output.
@throws IllegalStateException if the cipher is not appropriately set up.
@throws InvalidCipherTextException if the input data is truncated or the mac check fails.
@throws DataLengthException if output buffer too short.
implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of the
feedback mode.
@param blockSize the block size in bits (note: a multiple of 8)
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/CFB"
and the block size in bits.
return the block size we are operating at.
@return the block size we are operating at (in bytes).
reset the chaining vector back to the IV and reset the underlying
cipher.
A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
be used to produce cipher text which is the same outLength as the plain text.
Create a buffered block cipher that uses Cipher Text Stealing
@param cipher the underlying block cipher this buffering object wraps.
return the size of the output buffer required for an update of 'length' bytes.
@param length the outLength of the input.
@return the space required to accommodate a call to update
with length bytes of input.
return the size of the output buffer required for an update plus a
doFinal with an input of length bytes.
@param length the outLength of the input.
@return the space required to accommodate a call to update and doFinal
with length bytes of input.
process a single byte, producing an output block if necessary.
@param in the input byte.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
process an array of bytes, producing output if necessary.
@param in the input byte array.
@param inOff the offset at which the input data starts.
@param length the number of bytes to be copied out of the input array.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
Process the last block in the buffer.
@param out the array the block currently being held is copied into.
@param outOff the offset at which the copying starts.
@return the number of output bytes copied to out.
@exception DataLengthException if there is insufficient space in out for
the output.
@exception InvalidOperationException if the underlying cipher is not
initialised.
@exception InvalidCipherTextException if cipher text decrypts wrongly (in
case the exception will never Get thrown).
A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
cipher to encrypt and authenticate data. It's on-line (the length of a
message isn't needed to begin processing it), has good performances, it's
simple and provably secure (provided the underlying block cipher is secure).
Of course, this implementations is NOT thread-safe.
Constructor that accepts an instance of a block cipher engine.
@param cipher the engine to use
Implements the Galois/Counter mode (GCM) detailed in NIST Special Publication 800-38D.
MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits.
Sizes less than 96 are not recommended, but are supported for specialized applications.
GCM-SIV Mode.
It should be noted that the specified limit of 236 bytes is not supported. This is because all bytes are
cached in a ByteArrayOutputStream object (which has a limit of a little less than 231 bytes),
and are output on the DoFinal() call (which can only process a maximum of 231 bytes).
The practical limit of 231 - 24 bytes is policed, and attempts to breach the limit will be rejected
In order to properly support the higher limit, an extended form of ByteArrayOutputStream would be needed
which would use multiple arrays to store the data. In addition, a new doOutput method would be required (similar
to that in XOF digests), which would allow the data to be output over multiple calls. Alternatively an extended
form of ByteArrayInputStream could be used to deliver the data.
The buffer length.
The halfBuffer length.
The nonce length.
The maximum data length (AEAD/PlainText). Due to implementation constraints this is restricted to the maximum
array length (https://programming.guide/java/array-maximum-length.html) minus the BUFLEN to allow for the MAC
The top bit mask.
The addition constant.
The initialisation flag.
The aeadComplete flag.
The cipher.
The multiplier.
The gHash buffer.
The reverse buffer.
The aeadHasher.
The dataHasher.
The plainDataStream.
The encryptedDataStream (decryption only).
Are we encrypting?
The initialAEAD.
The nonce.
The flags.
Constructor.
Constructor.
@param pCipher the underlying cipher
Constructor.
@param pCipher the underlying cipher
@param pMultiplier the multiplier
check AEAD status.
@param pLen the aeadLength
check status.
@param pLen the dataLength
Reset Streams.
Obtain buffer length (allowing for null).
@param pBuffer the buffere
@return the length
calculate tag.
@return the calculated tag
complete polyVAL.
@return the calculated value
process lengths.
perform the next GHASH step.
@param pNext the next value
xor a full block buffer.
@param pLeft the left operand and result
@param pRight the right operand
xor a partial block buffer.
@param pLeft the left operand and result
@param pRight the right operand
@param pOffset the offset in the right operand
@param pLength the length of data in the right operand
increment the counter.
@param pCounter the counter to increment
multiply by X.
@param pValue the value to adjust
Derive Keys.
@param pKey the keyGeneration key
Hash Control.
Cache.
Single byte cache.
Count of active bytes in cache.
Count of hashed bytes.
Obtain the count of bytes hashed.
@return the count
Reset the hasher.
update hash.
@param pByte the byte
update hash.
@param pBuffer the buffer
@param pOffset the offset within the buffer
@param pLen the length of data
complete hash.
implements the GOST 28147 OFB counter mode (GCTR).
Basic constructor.
@param cipher the block cipher to be used as the basis of the
counter mode (must have a 64 bit block size).
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param encrypting if true the cipher is initialised for
encryption, if false for decryption.
@param parameters the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/GCTR"
and the block size in bits
return the block size we are operating at (in bytes).
@return the block size we are operating at (in bytes).
reset the feedback vector back to the IV and reset the underlying
cipher.
An IAeadCipher based on an IBlockCipher.
The block size for this cipher, in bytes.
The block cipher underlying this algorithm.
A cipher mode that includes authenticated encryption with a streaming mode and optional
associated data.
Implementations of this interface may operate in a packet mode (where all input data is
buffered and processed during the call to DoFinal, or in a streaming mode (where output
data is incrementally produced with each call to ProcessByte or ProcessBytes. This is
important to consider during decryption: in a streaming mode, unauthenticated plaintext
data may be output prior to the call to DoFinal that results in an authentication failure.
The higher level protocol utilising this cipher must ensure the plaintext data is handled
appropriately until the end of data is reached and the entire ciphertext is authenticated.
The name of the algorithm this cipher implements.
Initialise the cipher.
Parameter can either be an AeadParameters or a ParametersWithIV object.
Initialise for encryption if true, for decryption if false.
The key or other data required by the cipher.
Add a single byte to the associated data check.
If the implementation supports it, this will be an online operation and will not retain the associated data.
The byte to be processed.
Add a sequence of bytes to the associated data check.
If the implementation supports it, this will be an online operation and will not retain the associated data.
The input byte array.
The offset into the input array where the data to be processed starts.
The number of bytes to be processed.
Add a span of bytes to the associated data check.
If the implementation supports it, this will be an online operation and will not retain the associated data.
the span containing the data.
Encrypt/decrypt a single byte.
@param input the byte to be processed.
@param outBytes the output buffer the processed byte goes into.
@param outOff the offset into the output byte array the processed data starts at.
@return the number of bytes written to out.
@exception DataLengthException if the output buffer is too small.
Process a block of bytes from in putting the result into out.
@param inBytes the input byte array.
@param inOff the offset into the in array where the data to be processed starts.
@param len the number of bytes to be processed.
@param outBytes the output buffer the processed bytes go into.
@param outOff the offset into the output byte array the processed data starts at.
@return the number of bytes written to out.
@exception DataLengthException if the output buffer is too small.
Finish the operation either appending or verifying the MAC at the end of the data.
@param outBytes space for any resulting output data.
@param outOff offset into out to start copying the data at.
@return number of bytes written into out.
@throws InvalidOperationException if the cipher is in an inappropriate state.
@throws InvalidCipherTextException if the MAC fails to match.
Return the value of the MAC associated with the last stream processed.
@return MAC for plaintext data.
Return the size of the output buffer required for a ProcessBytes
an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to ProcessBytes
with len bytes of input.
Return the size of the output buffer required for a ProcessBytes plus a
DoFinal with an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to ProcessBytes and DoFinal
with len bytes of input.
Reset the cipher to the same state as it was after the last init (if there was one).
Return the
underlying this cipher mode.
Indicates whether this cipher mode can handle partial blocks.
Reset the cipher mode to the same state as it was after the last init (if there was one).
Base constructor. Nb value is set to 4.
base cipher to use under CCM.
Constructor allowing Nb configuration.
Nb is a parameter specified in CCM mode of DSTU7624 standard.
This parameter specifies maximum possible length of input.It should
be calculated as follows: Nb = 1 / 8 * (-3 + log[2]Nmax) + 1,
where Nmax - length of input message in bits.For practical reasons
Nmax usually less than 4Gb, e.g. for Nmax = 2^32 - 1, Nb = 4.
base cipher to use under CCM.
Nb value to use.
Implements a Gamming or Counter (CTR) mode on top of a DSTU 7624 block cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of the
feedback mode.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/KCTR"
and the block size in bits.
return the block size we are operating at.
@return the block size we are operating at (in bytes).
Process one block of input from the array in and write it to
the out array.
@param input the array containing the input data.
@param inOff offset into the in array the data starts at.
@param output the array the output data will be copied into.
@param outOff the offset into the out array the output will start at.
@exception DataLengthException if there isn't enough data in in, or
space in out.
@exception InvalidOperationException if the cipher isn't initialised.
@return the number of bytes processed and produced.
reset the chaining vector back to the IV and reset the underlying
cipher.
An implementation of RFC 7253 on The OCB
Authenticated-Encryption Algorithm.
For those still concerned about the original patents around this, please see:
https://mailarchive.ietf.org/arch/msg/cfrg/qLTveWOdTJcLn4HP3ev-vrj05Vg/
Text reproduced below:
Phillip Rogaway<rogaway@cs.ucdavis.edu> Sat, 27 February 2021 02:46 UTC
I can confirm that I have abandoned all OCB patents and placed into the public domain all OCB-related IP of
mine. While I have been telling people this for quite some time, I don't think I ever made a proper announcement
to the CFRG or on the OCB webpage. Consider that done.
implements a Output-FeedBack (OFB) mode on top of a simple cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of the
feedback mode.
@param blockSize the block size in bits (note: a multiple of 8)
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/OFB"
and the block size in bits
return the block size we are operating at (in bytes).
@return the block size we are operating at (in bytes).
reset the feedback vector back to the IV and reset the underlying
cipher.
* Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
* on top of a simple cipher. This class assumes the IV has been prepended
* to the data stream already, and just accomodates the reset after
* (blockSize + 2) bytes have been read.
*
* For further info see RFC 2440.
*
Basic constructor.
@param cipher the block cipher to be used as the basis of the
feedback mode.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/PGPCFB"
and the block size in bits.
return the block size we are operating at.
@return the block size we are operating at (in bytes).
reset the chaining vector back to the IV and reset the underlying
cipher.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
An IV which is too short is handled in FIPS compliant fashion.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param parameters the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Encrypt one byte of data according to CFB mode.
@param data the byte to encrypt
@param blockOff offset in the current block
@returns the encrypted byte
Implements the Segmented Integer Counter (SIC) mode on top of a simple
block cipher.
Basic constructor.
@param c the block cipher to be used.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Return the digest algorithm using one of the standard JCA string
representations rather than the algorithm identifier (if possible).
Calculator factory class for signature generation in ASN.1 based profiles that use an AlgorithmIdentifier to preserve
signature algorithm details.
Base constructor.
The name of the signature algorithm to use.
The private key to be used in the signing operation.
Constructor which also specifies a source of randomness to be used if one is required.
The name of the signature algorithm to use.
The private key to be used in the signing operation.
The source of randomness to be used in signature calculation.
Allows enumeration of the signature names supported by the verifier provider.
Verifier class for signature verification in ASN.1 based profiles that use an AlgorithmIdentifier to preserve
signature algorithm details.
Base constructor.
The name of the signature algorithm to use.
The public key to be used in the verification operation.
Provider class which supports dynamic creation of signature verifiers.
Base constructor - specify the public key to be used in verification.
The public key to be used in creating verifiers provided by this object.
Allows enumeration of the signature names supported by the verifier provider.
Block cipher padders are expected to conform to this interface.
Initialise the padder.
A source of randomness, if any required.
The name of the algorithm this padder implements.
Add padding to the passed in block.
the block to add padding to.
the offset into the block the padding is to start at.
the number of bytes of padding added.
Add padding to the passed in block.
the block to add padding to.
the offset into the block the padding is to start at.
the number of bytes of padding added.
Determine the length of padding present in the passed in block.
the block to check padding for.
the number of bytes of padding present.
Determine the length of padding present in the passed in block.
the block to check padding for.
the number of bytes of padding present.
A padder that adds ISO10126-2 padding to a block.
Initialise the padder.
@param random a SecureRandom if available.
Return the name of the algorithm the cipher implements.
@return the name of the algorithm the cipher implements.
A padder that adds the padding according to the scheme referenced in
ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
Initialise the padder.
@param random - a SecureRandom if available.
Return the name of the algorithm the padder implements.
@return the name of the algorithm the padder implements.
A wrapper class that allows block ciphers to be used to process data in
a piecemeal fashion with padding. The PaddedBufferedBlockCipher
outputs a block only when the buffer is full and more data is being added,
or on a doFinal (unless the current block in the buffer is a pad block).
The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
Create a buffered block cipher with the desired padding.
@param cipher the underlying block cipher this buffering object wraps.
@param padding the padding type.
Create a buffered block cipher Pkcs7 padding
@param cipher the underlying block cipher this buffering object wraps.
initialise the cipher.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the minimum size of the output buffer required for an update
plus a doFinal with an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update and doFinal
with len bytes of input.
return the size of the output buffer required for an update
an input of len bytes.
@param len the length of the input.
@return the space required to accommodate a call to update
with len bytes of input.
process a single byte, producing an output block if necessary.
@param in the input byte.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
process an array of bytes, producing output if necessary.
@param in the input byte array.
@param inOff the offset at which the input data starts.
@param len the number of bytes to be copied out of the input array.
@param out the space for any output that might be produced.
@param outOff the offset from which the output will be copied.
@return the number of output bytes copied to out.
@exception DataLengthException if there isn't enough space in out.
@exception InvalidOperationException if the cipher isn't initialised.
Process the last block in the buffer. If the buffer is currently
full and padding needs to be added a call to doFinal will produce
2 * GetBlockSize() bytes.
@param out the array the block currently being held is copied into.
@param outOff the offset at which the copying starts.
@return the number of output bytes copied to out.
@exception DataLengthException if there is insufficient space in out for
the output or we are decrypting and the input is not block size aligned.
@exception InvalidOperationException if the underlying cipher is not
initialised.
@exception InvalidCipherTextException if padding is expected and not found.
A padder that adds Pkcs7/Pkcs5 padding to a block.
Initialise the padder.
@param random - a SecureRandom if available.
Return the name of the algorithm the cipher implements.
@return the name of the algorithm the cipher implements.
A padder that adds Trailing-Bit-Compliment padding to a block.
This padding pads the block out compliment of the last bit
of the plain text.
Return the name of the algorithm the cipher implements.
the name of the algorithm the cipher implements.
Initialise the padder.
- a SecureRandom if available.
add the pad bytes to the passed in block, returning the number of bytes added.
This assumes that the last block of plain text is always passed to it inside .
i.e. if is zero, indicating the padding will fill the entire block,the value of
should be the same as the last block of plain text.
add the pad bytes to the passed in block, returning the number of bytes added.
This assumes that the last block of plain text is always passed to it inside .
i.e. if is zero, indicating the padding will fill the entire block,the value of
should be the same as the last block of plain text.
A padder that adds X9.23 padding to a block - if a SecureRandom is
passed in random padding is assumed, otherwise padding with zeros is used.
Initialise the padder.
@param random a SecureRandom if one is available.
Return the name of the algorithm the cipher implements.
@return the name of the algorithm the cipher implements.
A padder that adds Null byte padding to a block.
Return the name of the algorithm the cipher implements.
the name of the algorithm the cipher implements.
Initialise the padder.
- a SecureRandom if available.
Base constructor.
@param key key to be used by underlying cipher
@param macSize macSize in bits
@param nonce nonce to be used
Base constructor.
@param key key to be used by underlying cipher
@param macSize macSize in bits
@param nonce nonce to be used
@param associatedText associated text, if any
Blake3 Parameters.
Create a key parameter.
the context
the parameter
Create a key parameter.
the key
the parameter
Obtain the key.
the key
Clear the key bytes.
Obtain the salt.
the salt
return true if the passed in key is a DES-EDE weak key.
@param key bytes making up the key
@param offset offset into the byte array the key starts at
@param length number of bytes making up the key
return true if the passed in key is a DES-EDE weak key.
@param key bytes making up the key
@param offset offset into the byte array the key starts at
return true if the passed in key is a real 2/3 part DES-EDE key.
@param key bytes making up the key
@param offset offset into the byte array the key starts at
return true if the passed in key is a real 2 part DES-EDE key.
@param key bytes making up the key
@param offset offset into the byte array the key starts at
return true if the passed in key is a real 3 part DES-EDE key.
@param key bytes making up the key
@param offset offset into the byte array the key starts at
DES has 16 weak keys. This method will check
if the given DES key material is weak or semi-weak.
Key material that is too short is regarded as weak.
See "Applied
Cryptography" by Bruce Schneier for more information.
@return true if the given DES key material is weak or semi-weak,
false otherwise.
DES Keys use the LSB as the odd parity bit. This can
be used to check for corrupt keys.
@param bytes the byte array to set the parity on.
The minimum bitlength of the private value.
The bitlength of the private value.
Construct without a usage index, this will do a random construction of G.
@param L desired length of prime P in bits (the effective key size).
@param N desired length of prime Q in bits.
@param certainty certainty level for prime number generation.
@param random the source of randomness to use.
Construct for a specific usage index - this has the effect of using verifiable canonical generation of G.
@param L desired length of prime P in bits (the effective key size).
@param N desired length of prime Q in bits.
@param certainty certainty level for prime number generation.
@param random the source of randomness to use.
@param usageIndex a valid usage index.
return the generator - g
return private value limit - l
Parameter class for the HkdfBytesGenerator class.
Generates parameters for HKDF, specifying both the optional salt and
optional info. Step 1: Extract won't be skipped.
@param ikm the input keying material or seed
@param salt the salt to use, may be null for a salt for hashLen zeros
@param info the info to use, may be null for an info field of zero bytes
Factory method that makes the HKDF skip the extract part of the key
derivation function.
@param ikm the input keying material or seed, directly used for step 2:
Expand
@param info the info to use, may be null for an info field of zero bytes
@return HKDFParameters that makes the implementation skip step 1
Returns the input keying material or seed.
@return the keying material
Returns if step 1: extract has to be skipped or not
@return true for skipping, false for no skipping of step 1
Returns the salt, or null if the salt should be generated as a byte array
of HashLen zeros.
@return the salt, or null
Returns the info field, which may be empty (null is converted to empty).
@return the info field, never null
parameters for using an integrated cipher in stream mode.
@param derivation the derivation parameter for the KDF function.
@param encoding the encoding parameter for the KDF function.
@param macKeySize the size of the MAC key (in bits).
@param derivation the derivation parameter for the KDF function.
@param encoding the encoding parameter for the KDF function.
@param macKeySize the size of the MAC key (in bits).
@param cipherKeySize the size of the associated Cipher key (in bits).
parameters for Key derivation functions for ISO-18033
Base constructor - suffix fixed input data only.
the KDF seed
fixed input data to follow counter.
length of the counter in bits
Base constructor - prefix and suffix fixed input data.
the KDF seed
fixed input data to precede counter
fixed input data to follow counter.
length of the counter in bits.
parameters for Key derivation functions for IEEE P1363a
Parameters for mask derivation functions.
Parameters for NaccacheStern public private key generation. For details on
this cipher, please see
http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
Parameters for generating a NaccacheStern KeyPair.
@param random
The source of randomness
@param strength
The desired strength of the Key in Bits
@param certainty
the probability that the generated primes are not really prime
as integer: 2^(-certainty) is then the probability
@param countSmallPrimes
How many small key factors are desired
@return Returns the certainty.
@return Returns the countSmallPrimes.
Public key parameters for NaccacheStern cipher. For details on this cipher,
please see
http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
@param privateKey
@return Returns the g.
@return Returns the lowerSigmaBound.
@return Returns the n.
Private key parameters for NaccacheStern cipher. For details on this cipher,
please see
http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
Constructs a NaccacheSternPrivateKey
@param g
the public enryption parameter g
@param n
the public modulus n = p*q
@param lowerSigmaBound
the public lower sigma bound up to which data can be encrypted
@param smallPrimes
the small primes, of which sigma is constructed in the right
order
@param phi_n
the private modulus phi(n) = (p-1)(q-1)
Cipher parameters with a fixed salt value associated with them.
Parameters for the Skein hash function - a series of byte[] strings identified by integer tags.
Parameterised Skein can be used for:
- MAC generation, by providing a key.
- Randomised hashing, by providing a nonce.
- A hash function for digital signatures, associating a
public key with the message digest.
- A key derivation function, by providing a
key identifier.
- Personalised hashing, by providing a
recommended format or
arbitrary personalisation string.
The parameter type for a secret key, supporting MAC or KDF functions: 0
The parameter type for the Skein configuration block: 4
The parameter type for a personalisation string: 8
The parameter type for a public key: 12
The parameter type for a key identifier string: 16
The parameter type for a nonce: 20
The parameter type for the message: 48
The parameter type for the output transformation: 63
Obtains a map of type (int) to value (byte[]) for the parameters tracked in this object.
Obtains the value of the key parameter, or null
if not
set.
The key.
Obtains the value of the personalisation parameter, or
null
if not set.
Obtains the value of the public key parameter, or
null
if not set.
Obtains the value of the key identifier parameter, or
null
if not set.
Obtains the value of the nonce parameter, or null
if
not set.
A builder for .
Sets a parameters to apply to the Skein hash function.
Parameter types must be in the range 0,5..62, and cannot use the value 48
(reserved for message body).
Parameters with type < 48 are processed before
the message content, parameters with type > 48
are processed after the message and prior to output.
the type of the parameter, in the range 5..62.
the byte sequence of the parameter.
Sets the parameter.
Sets the parameter.
Implements the recommended personalisation format for Skein defined in Section 4.11 of
the Skein 1.3 specification.
The format is YYYYMMDD email@address distinguisher
, encoded to a byte
sequence using UTF-8 encoding.
the date the personalised application of the Skein was defined.
the email address of the creation of the personalised application.
an arbitrary personalisation string distinguishing the application.
Sets the parameter.
Sets the parameter.
Sets the parameter.
Constructs a new instance with the parameters provided to this
builder.
Private parameters for an SM2 key exchange.
The ephemeralPrivateKey is used to calculate the random point used in the algorithm.
Public parameters for an SM2 key exchange.
In this case the ephemeralPublicKey provides the random point used in the algorithm.
Parameters for tweakable block ciphers.
Gets the key.
the key to use, or null
to use the current key.
Gets the tweak value.
The tweak to use, or null
to use the current tweak.
super class for all Password Based Encyrption (Pbe) parameter generator classes.
base constructor.
initialise the Pbe generator.
@param password the password converted into bytes (see below).
@param salt the salt to be mixed with the password.
@param iterationCount the number of iterations the "mixing" function
is to be applied for.
return the iteration count.
@return the iteration count.
Generate derived parameters for a key of length keySize, specifically
for use with a MAC.
@param keySize the length, in bits, of the key required.
@return a parameters object representing a key.
converts a password to a byte array according to the scheme in
Pkcs5 (ascii, no padding)
@param password a character array representing the password.
@return a byte array representing the password.
converts a password to a byte array according to the scheme in
PKCS5 (UTF-8, no padding)
@param password a character array representing the password.
@return a byte array representing the password.
converts a password to a byte array according to the scheme in
Pkcs12 (unicode, big endian, 2 zero pad bytes at the end).
@param password a character array representing the password.
@return a byte array representing the password.
An EntropySourceProvider where entropy generation is based on a SecureRandom output using SecureRandom.generateSeed().
Create a entropy source provider based on the passed in SecureRandom.
@param secureRandom the SecureRandom to base EntropySource construction on.
@param isPredictionResistant boolean indicating if the SecureRandom is based on prediction resistant entropy or not (true if it is).
Return an entropy source that will create bitsRequired bits of entropy on
each invocation of getEntropy().
@param bitsRequired size (in bits) of entropy to be created by the provided source.
@return an EntropySource that generates bitsRequired bits of entropy on each call to its getEntropy() method.
Uses RandomNumberGenerator.Create() to get randomness generator
Random generation based on the digest with counter. Calling AddSeedMaterial will
always increase the entropy of the hash.
Internal access to the digest is synchronized so a single one of these can be shared.
A SP800-90A CTR DRBG.
Construct a SP800-90A CTR DRBG.
Minimum entropy requirement is the security strength requested.
@param engine underlying block cipher to use to support DRBG
@param keySizeInBits size of the key to use with the block cipher.
@param securityStrength security strength required (in bits)
@param entropySource source of entropy to use for seeding/reseeding.
@param personalizationString personalization string to distinguish this DRBG (may be null).
@param nonce nonce to further distinguish this DRBG (may be null).
Return the block size (in bits) of the DRBG.
@return the number of bits produced on each internal round of the DRBG.
Populate a passed in array with random data.
@param output output array for generated bits.
@param additionalInput additional input to be added to the DRBG in this step.
@param predictionResistant true if a reseed should be forced, false otherwise.
@return number of bits generated, -1 if a reseed required.
Reseed the DRBG.
@param additionalInput additional input to be added to the DRBG in this step.
Pad out a key for TDEA, setting odd parity for each byte.
@param keyMaster
@param keyOff
@param tmp
@param tmpOff
Used by both Dual EC and Hash.
A SP800-90A Hash DRBG.
Construct a SP800-90A Hash DRBG.
Minimum entropy requirement is the security strength requested.
@param digest source digest to use for DRB stream.
@param securityStrength security strength required (in bits)
@param entropySource source of entropy to use for seeding/reseeding.
@param personalizationString personalization string to distinguish this DRBG (may be null).
@param nonce nonce to further distinguish this DRBG (may be null).
Return the block size (in bits) of the DRBG.
@return the number of bits produced on each internal round of the DRBG.
Populate a passed in array with random data.
@param output output array for generated bits.
@param additionalInput additional input to be added to the DRBG in this step.
@param predictionResistant true if a reseed should be forced, false otherwise.
@return number of bits generated, -1 if a reseed required.
Reseed the DRBG.
@param additionalInput additional input to be added to the DRBG in this step.
A SP800-90A HMAC DRBG.
Construct a SP800-90A Hash DRBG.
Minimum entropy requirement is the security strength requested.
@param hMac Hash MAC to base the DRBG on.
@param securityStrength security strength required (in bits)
@param entropySource source of entropy to use for seeding/reseeding.
@param personalizationString personalization string to distinguish this DRBG (may be null).
@param nonce nonce to further distinguish this DRBG (may be null).
Return the block size (in bits) of the DRBG.
@return the number of bits produced on each round of the DRBG.
Populate a passed in array with random data.
@param output output array for generated bits.
@param additionalInput additional input to be added to the DRBG in this step.
@param predictionResistant true if a reseed should be forced, false otherwise.
@return number of bits generated, -1 if a reseed required.
Reseed the DRBG.
@param additionalInput additional input to be added to the DRBG in this step.
Interface to SP800-90A deterministic random bit generators.
Return the block size of the DRBG.
@return the block size (in bits) produced by each round of the DRBG.
Populate a passed in array with random data.
@param output output array for generated bits.
@param additionalInput additional input to be added to the DRBG in this step.
@param predictionResistant true if a reseed should be forced, false otherwise.
@return number of bits generated, -1 if a reseed required.
Reseed the DRBG.
@param additionalInput additional input to be added to the DRBG in this step.
Generate numBytes worth of entropy from the passed in entropy source.
@param entropySource the entropy source to request the data from.
@param numBytes the number of bytes of entropy requested.
@return a byte array populated with the random data.
Generic interface for objects generating random bytes.
Add more seed material to the generator.
A byte array to be mixed into the generator's state.
Add more seed material to the generator.
A long value to be mixed into the generator's state.
Fill byte array with random values.
Array to be filled.
Fill byte array with random values.
Array to receive bytes.
Index to start filling at.
Length of segment to fill.
Force a reseed of the DRBG.
optional additional input
Builder class for making SecureRandom objects based on SP 800-90A Deterministic Random Bit Generators (DRBG).
Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with
predictionResistant set to false.
Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
the default SecureRandom does for its generateSeed() call.
Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value
for prediction resistance.
Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
the passed in SecureRandom does for its generateSeed() call.
@param entropySource
@param predictionResistant
Create a builder which makes creates the SecureRandom objects from a specified entropy source provider.
Note: If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored.
@param entropySourceProvider a provider of EntropySource objects.
Set the personalization string for DRBG SecureRandoms created by this builder
@param personalizationString the personalisation string for the underlying DRBG.
@return the current builder.
Set the security strength required for DRBGs used in building SecureRandom objects.
@param securityStrength the security strength (in bits)
@return the current builder.
Set the amount of entropy bits required for seeding and reseeding DRBGs used in building SecureRandom objects.
@param entropyBitsRequired the number of bits of entropy to be requested from the entropy source on each seed/reseed.
@return the current builder.
Build a SecureRandom based on a SP 800-90A Hash DRBG.
@param digest digest algorithm to use in the DRBG underneath the SecureRandom.
@param nonce nonce value to use in DRBG construction.
@param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
@return a SecureRandom supported by a Hash DRBG.
Build a SecureRandom based on a SP 800-90A CTR DRBG.
@param cipher the block cipher to base the DRBG on.
@param keySizeInBits key size in bits to be used with the block cipher.
@param nonce nonce value to use in DRBG construction.
@param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
@return a SecureRandom supported by a CTR DRBG.
Build a SecureRandom based on a SP 800-90A HMAC DRBG.
@param hMac HMAC algorithm to use in the DRBG underneath the SecureRandom.
@param nonce nonce value to use in DRBG construction.
@param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
@return a SecureRandom supported by a HMAC DRBG.
Permutation generated by code:
// First 1850 fractional digit of Pi number.
byte[] key = new BigInteger("14159265358979323846...5068006422512520511").ToByteArray();
s = 0;
P = new byte[256];
for (int i = 0; i < 256; i++)
{
P[i] = (byte) i;
}
for (int m = 0; m < 768; m++)
{
s = P[(s + P[m & 0xff] + key[m % key.length]) & 0xff];
byte temp = P[m & 0xff];
P[m & 0xff] = P[s & 0xff];
P[s & 0xff] = temp;
}
Value generated in the same way as P.
@param engine
@param entropySource
Reseed the RNG.
Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with
predictionResistant set to false.
Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
the default SecureRandom does for its generateSeed() call.
Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value
for prediction resistance.
Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
the passed in SecureRandom does for its generateSeed() call.
@param entropySource
@param predictionResistant
Create a builder which makes creates the SecureRandom objects from a specified entropy source provider.
Note: If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored.
@param entropySourceProvider a provider of EntropySource objects.
Construct a X9.31 secure random generator using the passed in engine and key. If predictionResistant is true the
generator will be reseeded on each request.
@param engine a block cipher to use as the operator.
@param key the block cipher key to initialise engine with.
@param predictionResistant true if engine to be reseeded on each use, false otherwise.
@return a SecureRandom.
The Digital Signature Algorithm - as described in "Handbook of Applied
Cryptography", pages 452 - 453.
Default configuration, random K values.
Configuration with an alternate, possibly deterministic calculator of K.
@param kCalculator a K value calculator.
Generate a signature for the given message using the key we were
initialised with. For conventional DSA the message should be a SHA-1
hash of the message of interest.
@param message the message that will be verified later.
return true if the value r and s represent a DSA signature for
the passed in message for standard DSA the message should be a
SHA-1 hash of the real message to be verified.
EC-DSA as described in X9.62
Default configuration, random K values.
Configuration with an alternate, possibly deterministic calculator of K.
@param kCalculator a K value calculator.
Generate a signature for the given message using the key we were
initialised with. For conventional DSA the message should be a SHA-1
hash of the message of interest.
@param message the message that will be verified later.
return true if the value r and s represent a DSA signature for
the passed in message (for standard DSA the message should be
a SHA-1 hash of the real message to be verified).
GOST R 34.10-2001 Signature Algorithm
generate a signature for the given message using the key we were
initialised with. For conventional GOST3410 the message should be a GOST3411
hash of the message of interest.
@param message the message that will be verified later.
return true if the value r and s represent a GOST3410 signature for
the passed in message (for standard GOST3410 the message should be
a GOST3411 hash of the real message to be verified).
EC-NR as described in IEEE 1363-2000
generate a signature for the given message using the key we were
initialised with. Generally, the order of the curve should be at
least as long as the hash of the message of interest, and with
ECNR it *must* be at least as long.
@param digest the digest to be signed.
@exception DataLengthException if the digest is longer than the key allows
return true if the value r and s represent a signature for the
message passed in. Generally, the order of the curve should be at
least as long as the hash of the message of interest, and with
ECNR, it *must* be at least as long. But just in case the signer
applied mod(n) to the longer digest, this implementation will
apply mod(n) during verification.
@param digest the digest to be verified.
@param r the r value of the signature.
@param s the s value of the signature.
@exception DataLengthException if the digest is longer than the key allows
initialise the signer for signing or verification.
@param forSigning
true if for signing, false otherwise
@param parameters
necessary parameters.
Gost R 34.10-94 Signature Algorithm
generate a signature for the given message using the key we were
initialised with. For conventional Gost3410 the message should be a Gost3411
hash of the message of interest.
@param message the message that will be verified later.
return true if the value r and s represent a Gost3410 signature for
the passed in message for standard Gost3410 the message should be a
Gost3411 hash of the real message to be verified.
A deterministic K calculator based on the algorithm in section 3.2 of RFC 6979.
Base constructor.
@param digest digest to build the HMAC on.
Supports use of additional input.
RFC 6979 3.6. Additional data may be added to the input of HMAC [..]. A use case may be a protocol that
requires a non-deterministic signature algorithm on a system that does not have access to a high-quality
random source. It suffices that the additional data[..] is non-repeating(e.g., a signature counter or a
monotonic clock) to ensure "random-looking" signatures are indistinguishable, in a cryptographic way, from
plain (EC)DSA signatures.
By default there is no additional input. Override this method to supply additional input, bearing in mind
that this calculator may be used for many signatures.
The to which the additional input should be added.
An interface for different encoding formats for DSA signatures.
Decode the (r, s) pair of a DSA signature.
The order of the group that r, s belong to.
An encoding of the (r, s) pair of a DSA signature.
The (r, s) of a DSA signature, stored in an array of exactly two elements, r followed by s.
Encode the (r, s) pair of a DSA signature.
The order of the group that r, s belong to.
The r value of a DSA signature.
The s value of a DSA signature.
An encoding of the DSA signature given by the provided (r, s) pair.
Interface define calculators of K values for DSA/ECDSA.
Return true if this calculator is deterministic, false otherwise.
@return true if deterministic, otherwise false.
Non-deterministic initialiser.
@param n the order of the DSA group.
@param random a source of randomness.
Deterministic initialiser.
@param n the order of the DSA group.
@param d the DSA private value.
@param message the message being signed.
Return the next valid value of K.
@return a K value.
ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
Note: the usual length for the salt is the length of the hash
function used in bytes.
Return a reference to the recoveredMessage message.
The full/partial recoveredMessage message.
Generate a signer with either implicit or explicit trailers for ISO9796-2, scheme 2 or 3.
base cipher to use for signature creation/verification
digest to use.
length of salt in bytes.
whether or not the trailer is implicit or gives the hash.
Constructor for a signer with an explicit digest trailer.
cipher to use.
digest to sign with.
length of salt in bytes.
Initialise the signer.
true if for signing, false if for verification.
parameters for signature generation/verification. If the
parameters are for generation they should be a ParametersWithRandom,
a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
are passed in a SecureRandom will be created.
if wrong parameter type or a fixed
salt is passed in which is the wrong length.
compare two byte arrays - constant time.
clear possible sensitive data
update the internal digest with the byte b
reset the internal state
Generate a signature for the loaded message using the key we were
initialised with.
return true if the signature represents a ISO9796-2 signature
for the passed in message.
Return true if the full message was recoveredMessage.
true on full message recovery, false otherwise, or if not sure.
int to octet string.
int to octet string.
long to octet string.
mask generator function, as described in Pkcs1v2.
ISO9796-2 - mechanism using a hash function with recovery (scheme 1)
Return a reference to the recoveredMessage message.
The full/partial recoveredMessage message.
Generate a signer with either implicit or explicit trailers for ISO9796-2.
base cipher to use for signature creation/verification
digest to use.
whether or not the trailer is implicit or gives the hash.
Constructor for a signer with an explicit digest trailer.
cipher to use.
digest to sign with.
compare two byte arrays - constant time.
clear possible sensitive data
reset the internal state
Generate a signature for the loaded message using the key we were
initialised with.
return true if the signature represents a ISO9796-2 signature
for the passed in message.
Return true if the full message was recoveredMessage.
true on full message recovery, false otherwise.
RSA-PSS as described in Pkcs# 1 v 2.1.
Note: the usual value for the salt length is the number of
bytes in the hash function.
Basic constructor
the asymmetric cipher to use.
the digest to use.
the length of the salt to use (in bytes).
Basic constructor
the asymmetric cipher to use.
the digest to use.
the fixed salt to be used.
clear possible sensitive data
int to octet string.
mask generator function, as described in Pkcs1v2.
Load oid table.
Initialise the signer for signing or verification.
@param forSigning true if for signing, false otherwise
@param param necessary parameters.
The SM2 Digital Signature algorithm.
X9.31-1998 - signing using a hash.
The message digest hash, H, is encapsulated to form a byte string as follows
EB = 06 || PS || 0xBA || H || TRAILER
where PS is a string of bytes all of value 0xBB of length such that |EB|=|n|, and TRAILER is the ISO/IEC 10118 part number†for the digest. The byte string, EB, is converted to an integer value, the message representative, f.
Generate a signer with either implicit or explicit trailers for X9.31.
@param cipher base cipher to use for signature creation/verification
@param digest digest to use.
@param implicit whether or not the trailer is implicit or gives the hash.
Constructor for a signer with an explicit digest trailer.
@param cipher cipher to use.
@param digest digest to sign with.
A simple block result object which just carries a byte array.
Base constructor - a wrapper for the passed in byte array.
The byte array to be wrapped.
Return the number of bytes in the result
The length of the result in bytes.
Return the final result of the operation.
A block of bytes, representing the result of an operation.
Store the final result of the operation by copying it into the destination array.
The number of bytes copied into destination.
The byte array to copy the result into.
The offset into destination to start copying the result at.
a wrapper for block ciphers with a single byte block size, so that they
can be treated like stream ciphers.
basic constructor.
@param cipher the block cipher to be wrapped.
@exception ArgumentException if the cipher has a block size other than
one.
initialise the underlying cipher.
@param forEncryption true if we are setting up for encryption, false otherwise.
@param param the necessary parameters for the underlying cipher to be initialised.
return the name of the algorithm we are wrapping.
@return the name of the algorithm we are wrapping.
encrypt/decrypt a single byte returning the result.
@param in the byte to be processed.
@return the result of processing the input byte.
process a block of bytes from in putting the result into out.
@param in the input byte array.
@param inOff the offset into the in array where the data to be processed starts.
@param len the number of bytes to be processed.
@param out the output buffer the processed bytes go into.
@param outOff the offset into the output byte array the processed data stars at.
@exception DataLengthException if the output buffer is too small.
reset the underlying cipher. This leaves it in the same state
it was at after the last init (if there was one).
Create an AlgorithmIdentifier for the passed in encryption algorithm.
@param encryptionOID OID for the encryption algorithm
@param keySize key size in bits (-1 if unknown)
@param random SecureRandom to use for parameter generation.
@return a full AlgorithmIdentifier including parameters
@throws IllegalArgumentException if encryptionOID cannot be matched
A basic alphabet mapper that just creates a mapper based on the
passed in array of characters.
Base constructor.
@param alphabet a string of characters making up the alphabet.
Base constructor.
@param alphabet an array of characters making up the alphabet.
Create a key generator for the passed in Object Identifier.
@param algorithm the Object Identifier indicating the algorithn the generator is for.
@param random a source of random to initialise the generator with.
@return an initialised CipherKeyGenerator.
@throws IllegalArgumentException if the algorithm cannot be identified.
Use KeyTransRecipientInfoGenerator
return a = a + b - b preserved.
unsigned comparison on two arrays - note the arrays may
start with leading zeros.
return z = x / y - done in place (z value preserved, x contains the
remainder)
return whether or not a BigInteger is probably prime with a
probability of 1 - (1/2)**certainty.
From Knuth Vol 2, pg 395.
Calculate the numbers u1, u2, and u3 such that:
u1 * a + u2 * b = u3
where u3 is the greatest common divider of a and b.
a and b using the extended Euclid algorithm (refer p. 323
of The Art of Computer Programming vol 2, 2nd ed).
This also seems to have the side effect of calculating
some form of multiplicative inverse.
@param a First number to calculate gcd for
@param b Second number to calculate gcd for
@param u1Out the return object for the u1 value
@return The greatest common divisor of a and b
return w with w = x * x - w is assumed to have enough space.
return x with x = y * z - x is assumed to have enough space.
Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size)
Montgomery multiplication: a = x * y * R^(-1) mod m
Based algorithm 14.36 of Handbook of Applied Cryptography.
m, x, y should have length n
a should have length (n + 1)
b = 2^32, R = b^n
The result is put in x
NOTE: the indices of x, y, m, a different in HAC and in Java
return x = x % y - done in place (y value preserved)
do a left shift - this returns a new array.
do a right shift - this does it in place.
do a right shift by one - this does it in place.
returns x = x - y - we assume x is >= y
Class representing a simple version of a big decimal. A
SimpleBigDecimal
is basically a
{@link java.math.BigInteger BigInteger} with a few digits on the right of
the decimal point. The number of (binary) digits on the right of the decimal
point is called the scale
of the SimpleBigDecimal
.
Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
automatically, but must be set manually. All SimpleBigDecimal
s
taking part in the same arithmetic operation must have equal scale. The
result of a multiplication of two SimpleBigDecimal
s returns a
SimpleBigDecimal
with double scale.
Returns a SimpleBigDecimal
representing the same numerical
value as value
.
@param value The value of the SimpleBigDecimal
to be
created.
@param scale The scale of the SimpleBigDecimal
to be
created.
@return The such created SimpleBigDecimal
.
Constructor for SimpleBigDecimal
. The value of the
constructed SimpleBigDecimal
Equals bigInt /
2scale
.
@param bigInt The bigInt
value parameter.
@param scale The scale of the constructed SimpleBigDecimal
.
Class holding methods for point multiplication based on the window
τ-adic nonadjacent form (WTNAF). The algorithms are based on the
paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves"
by Jerome A. Solinas. The paper first appeared in the Proceedings of
Crypto 1997.
The window width of WTNAF. The standard value of 4 is slightly less
than optimal for running time, but keeps space requirements for
precomputation low. For typical curves, a value of 5 or 6 results in
a better running time. When changing this value, the
αu
's must be computed differently, see
e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson,
Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004,
p. 121-122
24
The αu
's for a=0
as an array
of ZTauElement
s.
The αu
's for a=0
as an array
of TNAFs.
The αu
's for a=1
as an array
of ZTauElement
s.
The αu
's for a=1
as an array
of TNAFs.
Computes the norm of an element λ
of
Z[τ]
.
@param mu The parameter μ
of the elliptic curve.
@param lambda The element λ
of
Z[τ]
.
@return The norm of λ
.
Computes the norm of an element λ
of
R[τ]
, where λ = u + vτ
and u
and u
are real numbers (elements of
R
).
@param mu The parameter μ
of the elliptic curve.
@param u The real part of the element λ
of
R[τ]
.
@param v The τ
-adic part of the element
λ
of R[τ]
.
@return The norm of λ
.
Rounds an element λ
of R[τ]
to an element of Z[τ]
, such that their difference
has minimal norm. λ
is given as
λ = λ0 + λ1τ
.
@param lambda0 The component λ0
.
@param lambda1 The component λ1
.
@param mu The parameter μ
of the elliptic curve. Must
equal 1 or -1.
@return The rounded element of Z[τ]
.
@throws ArgumentException if lambda0
and
lambda1
do not have same scale.
Approximate division by n
. For an integer
k
, the value λ = s k / n
is
computed to c
bits of accuracy.
@param k The parameter k
.
@param s The curve parameter s0
or
s1
.
@param vm The Lucas Sequence element Vm
.
@param a The parameter a
of the elliptic curve.
@param m The bit length of the finite field
Fm
.
@param c The number of bits of accuracy, i.e. the scale of the returned
SimpleBigDecimal
.
@return The value λ = s k / n
computed to
c
bits of accuracy.
Computes the τ
-adic NAF (non-adjacent form) of an
element λ
of Z[τ]
.
@param mu The parameter μ
of the elliptic curve.
@param lambda The element λ
of
Z[τ]
.
@return The τ
-adic NAF of λ
.
Applies the operation τ()
to an
AbstractF2mPoint
.
@param p The AbstractF2mPoint to which τ()
is applied.
@return τ(p)
Returns the parameter μ
of the elliptic curve.
@param curve The elliptic curve from which to obtain μ
.
The curve must be a Koblitz curve, i.e. a
Equals
0
or 1
and b
Equals
1
.
@return μ
of the elliptic curve.
@throws ArgumentException if the given ECCurve is not a Koblitz
curve.
Calculates the Lucas Sequence elements Uk-1
and
Uk
or Vk-1
and
Vk
.
@param mu The parameter μ
of the elliptic curve.
@param k The index of the second element of the Lucas Sequence to be
returned.
@param doV If set to true, computes Vk-1
and
Vk
, otherwise Uk-1
and
Uk
.
@return An array with 2 elements, containing Uk-1
and Uk
or Vk-1
and Vk
.
Computes the auxiliary value tw
. If the width is
4, then for mu = 1
, tw = 6
and for
mu = -1
, tw = 10
@param mu The parameter μ
of the elliptic curve.
@param w The window width of the WTNAF.
@return the auxiliary value tw
Computes the auxiliary values s0
and
s1
used for partial modular reduction.
@param curve The elliptic curve for which to compute
s0
and s1
.
@throws ArgumentException if curve
is not a
Koblitz curve (Anomalous Binary Curve, ABC).
Partial modular reduction modulo
(τm - 1)/(τ - 1)
.
@param k The integer to be reduced.
@param m The bitlength of the underlying finite field.
@param a The parameter a
of the elliptic curve.
@param s The auxiliary values s0
and
s1
.
@param mu The parameter μ of the elliptic curve.
@param c The precision (number of bits of accuracy) of the partial
modular reduction.
@return ρ := k partmod (τm - 1)/(τ - 1)
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by a BigInteger
using the reduced τ
-adic
NAF (RTNAF) method.
@param p The AbstractF2mPoint to Multiply.
@param k The BigInteger
by which to Multiply p
.
@return k * p
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by an element λ
of Z[τ]
using the τ
-adic NAF (TNAF) method.
@param p The AbstractF2mPoint to Multiply.
@param lambda The element λ
of
Z[τ]
.
@return λ * p
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by an element λ
of Z[τ]
using the τ
-adic NAF (TNAF) method, given the TNAF
of λ
.
@param p The AbstractF2mPoint to Multiply.
@param u The the TNAF of λ
..
@return λ * p
Computes the [τ]
-adic window NAF of an element
λ
of Z[τ]
.
@param mu The parameter μ of the elliptic curve.
@param lambda The element λ
of
Z[τ]
of which to compute the
[τ]
-adic NAF.
@param width The window width of the resulting WNAF.
@param pow2w 2width.
@param tw The auxiliary value tw
.
@param alpha The αu
's for the window width.
@return The [τ]
-adic window NAF of
λ
.
Does the precomputation for WTNAF multiplication.
@param p The ECPoint
for which to do the precomputation.
@param a The parameter a
of the elliptic curve.
@return The precomputation array for p
.
Class representing an element of Z[τ]
. Let
λ
be an element of Z[τ]
. Then
λ
is given as λ = u + vτ
. The
components u
and v
may be used directly, there
are no accessor methods.
Immutable class.
The "real" part of λ
.
The "τ
-adic" part of λ
.
Constructor for an element λ
of
Z[τ]
.
@param u The "real" part of λ
.
@param v The "τ
-adic" part of
λ
.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
return a sqrt root - the routine verifies that the calculation returns the right value - if
none exists it returns null.
Simple shift-and-add multiplication. Serves as reference implementation to verify (possibly
faster) implementations, and for very small scalars. CAUTION: This implementation is NOT
constant-time in any way. It is only intended to be used for diagnostics.
@param p
The point to multiply.
@param k
The multiplier.
@return The result of the point multiplication kP
.
Base class for an elliptic curve.
Compute a PreCompInfo
for a point on this curve, under a given name. Used by
ECMultiplier
s to save the precomputation for this ECPoint
for use
by subsequent multiplication.
@param point
The ECPoint
to store precomputations for.
@param name
A String
used to index precomputations of different types.
@param callback
Called to calculate the PreCompInfo
.
Normalization ensures that any projective coordinate is 1, and therefore that the x, y
coordinates reflect those of the equivalent point in an affine coordinate system. Where more
than one point is to be normalized, this method will generally be more efficient than
normalizing each point separately.
@param points
An array of points that will be updated in place with their normalized versions,
where necessary
Normalization ensures that any projective coordinate is 1, and therefore that the x, y
coordinates reflect those of the equivalent point in an affine coordinate system. Where more
than one point is to be normalized, this method will generally be more efficient than
normalizing each point separately. An (optional) z-scaling factor can be applied; effectively
each z coordinate is scaled by this value prior to normalization (but only one
actual multiplication is needed).
@param points
An array of points that will be updated in place with their normalized versions,
where necessary
@param off
The start of the range of points to normalize
@param len
The length of the range of points to normalize
@param iso
The (optional) z-scaling factor - can be null
Create a cache-safe lookup table for the specified sequence of points. All the points MUST
belong to this ECCurve
instance, and MUST already be normalized.
Sets the default ECMultiplier
, unless already set.
We avoid locking for performance reasons, so there is no uniqueness guarantee.
Decode a point on this curve from its ASN.1 encoding. The different
encodings are taken account of, including point compression for
Fp
(X9.62 s 4.2.1 pg 17).
@return The decoded point.
Elliptic curve over Fp
The auxiliary values s0
and
s1
used for partial modular reduction for
Koblitz curves.
Solves a quadratic equation z2 + z = beta
(X9.62
D.1.6) The other solution is z + 1
.
@param beta
The value to solve the quadratic equation for.
@return the solution for z2 + z = beta
or
null
if no solution exists.
@return the auxiliary values s0
and
s1
used for partial modular reduction for
Koblitz curves.
Returns true if this is a Koblitz curve (ABC curve).
@return true if this is a Koblitz curve (ABC curve), false otherwise
Elliptic curves over F2m. The Weierstrass equation is given by
y2 + xy = x3 + ax2 + b
.
The exponent m
of F2m
.
TPB: The integer k
where xm +
xk + 1
represents the reduction polynomial
f(z)
.
PPB: The integer k1
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
TPB: Always set to 0
PPB: The integer k2
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
TPB: Always set to 0
PPB: The integer k3
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
The point at infinity on this curve.
Constructor for Trinomial Polynomial Basis (TPB).
@param m The exponent m
of
F2m
.
@param k The integer k
where xm +
xk + 1
represents the reduction
polynomial f(z)
.
@param a The coefficient a
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param b The coefficient b
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
Constructor for Trinomial Polynomial Basis (TPB).
@param m The exponent m
of
F2m
.
@param k The integer k
where xm +
xk + 1
represents the reduction
polynomial f(z)
.
@param a The coefficient a
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param b The coefficient b
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param order The order of the main subgroup of the elliptic curve.
@param cofactor The cofactor of the elliptic curve, i.e.
#Ea(F2m) = h * n
.
Constructor for Pentanomial Polynomial Basis (PPB).
@param m The exponent m
of
F2m
.
@param k1 The integer k1
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k2 The integer k2
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k3 The integer k3
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param a The coefficient a
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param b The coefficient b
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
Constructor for Pentanomial Polynomial Basis (PPB).
@param m The exponent m
of
F2m
.
@param k1 The integer k1
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k2 The integer k2
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param k3 The integer k3
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@param a The coefficient a
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param b The coefficient b
in the Weierstrass equation
for non-supersingular elliptic curves over
F2m
.
@param order The order of the main subgroup of the elliptic curve.
@param cofactor The cofactor of the elliptic curve, i.e.
#Ea(F2m) = h * n
.
Return true if curve uses a Trinomial basis.
@return true if curve Trinomial, false otherwise.
return the field name for this field.
@return the string "Fp".
return a sqrt root - the routine verifies that the calculation
returns the right value - if none exists it returns null.
Class representing the Elements of the finite field
F2m
in polynomial basis (PB)
representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial
basis representations are supported. Gaussian normal basis (GNB)
representation is not supported.
Indicates gaussian normal basis representation (GNB). Number chosen
according to X9.62. GNB is not implemented at present.
Indicates trinomial basis representation (Tpb). Number chosen
according to X9.62.
Indicates pentanomial basis representation (Ppb). Number chosen
according to X9.62.
Tpb or Ppb.
The exponent m
of F2m
.
The LongArray
holding the bits.
Checks, if the ECFieldElements a
and b
are elements of the same field F2m
(having the same representation).
@param a field element.
@param b field element to be compared.
@throws ArgumentException if a
and b
are not elements of the same field
F2m
(having the same
representation).
@return the representation of the field
F2m
, either of
{@link F2mFieldElement.Tpb} (trinomial
basis representation) or
{@link F2mFieldElement.Ppb} (pentanomial
basis representation).
@return the degree m
of the reduction polynomial
f(z)
.
@return Tpb: The integer k
where xm +
xk + 1
represents the reduction polynomial
f(z)
.
Ppb: The integer k1
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@return Tpb: Always returns 0
Ppb: The integer k2
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
@return Tpb: Always set to 0
Ppb: The integer k3
where xm +
xk3 + xk2 + xk1 + 1
represents the reduction polynomial f(z)
.
base class for points on elliptic curves.
Returns the affine x-coordinate after checking that this point is normalized.
@return The affine x-coordinate of this point
@throws IllegalStateException if the point is not normalized
Returns the affine y-coordinate after checking that this point is normalized
@return The affine y-coordinate of this point
@throws IllegalStateException if the point is not normalized
Returns the x-coordinate.
Caution: depending on the curve's coordinate system, this may not be the same value as in an
affine coordinate system; use Normalize() to get a point where the coordinates have their
affine values, or use AffineXCoord if you expect the point to already have been normalized.
@return the x-coordinate of this point
Returns the y-coordinate.
Caution: depending on the curve's coordinate system, this may not be the same value as in an
affine coordinate system; use Normalize() to get a point where the coordinates have their
affine values, or use AffineYCoord if you expect the point to already have been normalized.
@return the y-coordinate of this point
Normalization ensures that any projective coordinate is 1, and therefore that the x, y
coordinates reflect those of the equivalent point in an affine coordinate system.
@return a new ECPoint instance representing the same point, but with normalized coordinates
return the field element encoded with point compression. (S 4.3.6)
Multiplies this ECPoint
by the given number.
@param k The multiplicator.
@return k * this
.
Elliptic curve points over Fp
Elliptic curve points over F2m
Interface for classes encapsulating a point multiplication algorithm
for ECPoint
s.
Multiplies the ECPoint p
by k
, i.e.
p
is added k
times to itself.
@param p The ECPoint
to be multiplied.
@param k The factor by which p
is multiplied.
@return p
multiplied by k
.
Class holding precomputation data for fixed-point multiplications.
Lookup table for the precomputed ECPoint
s used for a fixed point multiplication.
The width used for the precomputation. If a larger width precomputation
is already available this may be larger than was requested, so calling
code should refer to the actual width.
Interface for classes storing precomputation data for multiplication
algorithms. Used as a Memento (see GOF patterns) for
WNafMultiplier
.
Class implementing the WNAF (Window Non-Adjacent Form) multiplication
algorithm.
Multiplies this
by an integer k
using the
Window NAF method.
@param k The integer by which this
is multiplied.
@return A new ECPoint
which equals this
multiplied by k
.
Class holding precomputation data for the WNAF (Window Non-Adjacent Form)
algorithm.
Array holding the precomputed ECPoint
s used for a Window
NAF multiplication.
Array holding the negations of the precomputed ECPoint
s used
for a Window NAF multiplication.
Holds an ECPoint
representing Twice(this). Used for the
Window NAF multiplication to create or extend the precomputed values.
Computes the Window NAF (non-adjacent Form) of an integer.
@param width The width w
of the Window NAF. The width is
defined as the minimal number w
, such that for any
w
consecutive digits in the resulting representation, at
most one is non-zero.
@param k The integer of which the Window NAF is computed.
@return The Window NAF of the given width, such that the following holds:
k = ∑i=0l-1 ki2i
, where the ki
denote the elements of the
returned byte[]
.
Determine window width to use for a scalar multiplication of the given size.
@param bits the bit-length of the scalar to multiply by
@return the window size to use
Determine window width to use for a scalar multiplication of the given size.
@param bits the bit-length of the scalar to multiply by
@param maxWidth the maximum window width to return
@return the window size to use
Determine window width to use for a scalar multiplication of the given size.
@param bits the bit-length of the scalar to multiply by
@param windowSizeCutoffs a monotonically increasing list of bit sizes at which to increment the window width
@return the window size to use
Determine window width to use for a scalar multiplication of the given size.
@param bits the bit-length of the scalar to multiply by
@param windowSizeCutoffs a monotonically increasing list of bit sizes at which to increment the window width
@param maxWidth the maximum window width to return
@return the window size to use
Class implementing the WTNAF (Window
τ
-adic Non-Adjacent Form) algorithm.
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by k
using the reduced τ
-adic NAF (RTNAF)
method.
@param p The AbstractF2mPoint to multiply.
@param k The integer by which to multiply k
.
@return p
multiplied by k
.
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by an element λ
of Z[τ]
using
the τ
-adic NAF (TNAF) method.
@param p The AbstractF2mPoint to multiply.
@param lambda The element λ
of
Z[τ]
of which to compute the
[τ]
-adic NAF.
@return p
multiplied by λ
.
Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
by an element λ
of Z[τ]
using the window τ
-adic NAF (TNAF) method, given the
WTNAF of λ
.
@param p The AbstractF2mPoint to multiply.
@param u The the WTNAF of λ
..
@return λ * p
Class holding precomputation data for the WTNAF (Window
τ
-adic Non-Adjacent Form) algorithm.
Array holding the precomputed AbstractF2mPoint
s used for the
WTNAF multiplication in
{@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
WTauNafMultiplier.multiply()}
.
A low-level implementation of the Ed25519, Ed25519ctx, and Ed25519ph instantiations of the Edwards-Curve Digital
Signature Algorithm specified in RFC 8032.
The implementation strategy is mostly drawn from
Mike Hamburg, "Fast and compact elliptic-curve cryptography", notably the "signed multi-comb" algorithm (for
scalar multiplication by a fixed point), the "half Niels coordinates" (for precomputed points), and the
"extensible coordinates" (for accumulators). Standard
extended coordinates are used during
precomputations, needing only a single extra point addition formula.
A low-level implementation of the Ed448 and Ed448ph instantiations of the Edwards-Curve Digital Signature
Algorithm specified in RFC 8032.
The implementation uses the "signed mult-comb" algorithm (for scalar multiplication by a fixed point) from
Mike Hamburg, "Fast and compact elliptic-curve cryptography". Standard
projective coordinates are used
for most point arithmetic.
Utility methods for generating primes and testing for primality.
Used to return the output from the
Enhanced Miller-Rabin Probabilistic Primality Test
Used to return the output from the
Shawe-Taylor Random_Prime Routine
FIPS 186-4 C.6 Shawe-Taylor Random_Prime Routine.
Construct a provable prime number using a hash function.
The instance to use (as "Hash()"). Cannot be null.
The length (in bits) of the prime to be generated. Must be at least 2.
The seed to be used for the generation of the requested prime. Cannot be null or
empty.
An instance containing the requested prime.
FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test.
Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. This is an alternative to
that provides more information about a
composite candidate, which may be useful when generating or validating RSA moduli.
The instance to test for primality.
The source of randomness to use to choose bases.
The number of randomly-chosen bases to perform the test for.
An instance that can be further queried for details.
A fast check for small divisors, up to some implementation-specific limit.
The instance to test for division by small factors.
true if the candidate is found to have any small factors, false otherwise.
FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test.
Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases.
The instance to test for primality.
The source of randomness to use to choose bases.
The number of randomly-chosen bases to perform the test for.
false if any witness to compositeness is found amongst the chosen bases (so
is definitely NOT prime), or else true (indicating primality with some
probability dependent on the number of iterations that were performed).
FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base).
Run a single iteration of the Miller-Rabin algorithm against the specified base.
The instance to test for primality.
The base value to use for this iteration.
false if is a witness to compositeness (so
is definitely NOT prime), or else true.
BasicOcspResponse ::= SEQUENCE {
tbsResponseData ResponseData,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING,
certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL
}
The DER encoding of the tbsResponseData field.
In the event of an encoding error.
The certificates, if any, associated with the response.
In the event of an encoding error.
Verify the signature against the tbsResponseData object we contain.
The ASN.1 encoded representation of this object.
Generator for basic OCSP response objects.
basic constructor
construct with the responderID to be the SHA-1 keyHash of the passed in public key.
Add a response for a particular Certificate ID.
@param certID certificate ID details
@param certStatus status of the certificate - null if okay
Add a response for a particular Certificate ID.
@param certID certificate ID details
@param certStatus status of the certificate - null if okay
@param singleExtensions optional extensions
Add a response for a particular Certificate ID.
@param certID certificate ID details
@param nextUpdate date when next update should be requested
@param certStatus status of the certificate - null if okay
@param singleExtensions optional extensions
Add a response for a particular Certificate ID.
@param certID certificate ID details
@param thisUpdate date this response was valid on
@param nextUpdate date when next update should be requested
@param certStatus status of the certificate - null if okay
@param singleExtensions optional extensions
Set the extensions for the response.
@param responseExtensions the extension object to carry.
Generate the signed response using the passed in signature calculator.
Implementation of signing calculator factory.
The certificate chain associated with the response signer.
"produced at" date.
Return an IEnumerable of the signature names supported by the generator.
@return an IEnumerable containing recognised names.
create from an issuer certificate and the serial number of the
certificate it signed.
@exception OcspException if any problems occur creating the id fields.
return the serial number for the certificate associated
with this request.
Create a new CertificateID for a new serial number derived from a previous one
calculated for the same CA certificate.
@param original the previously calculated CertificateID for the CA.
@param newSerialNumber the serial number for the new certificate of interest.
@return a new CertificateID for newSerialNumber
OcspRequest ::= SEQUENCE {
tbsRequest TBSRequest,
optionalSignature [0] EXPLICIT Signature OPTIONAL }
TBSRequest ::= SEQUENCE {
version [0] EXPLICIT Version DEFAULT v1,
requestorName [1] EXPLICIT GeneralName OPTIONAL,
requestList SEQUENCE OF Request,
requestExtensions [2] EXPLICIT Extensions OPTIONAL }
Signature ::= SEQUENCE {
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING,
certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL}
Version ::= INTEGER { v1(0) }
Request ::= SEQUENCE {
reqCert CertID,
singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
CertID ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
issuerNameHash OCTET STRING, -- Hash of Issuer's DN
issuerKeyHash OCTET STRING, -- Hash of Issuers public key
serialNumber CertificateSerialNumber }
Return the DER encoding of the tbsRequest field.
@return DER encoding of tbsRequest
@throws OcspException in the event of an encoding error.
return the object identifier representing the signature algorithm
If the request is signed return a possibly empty CertStore containing the certificates in the
request. If the request is not signed the method returns null.
@return null if not signed, a CertStore otherwise
@throws OcspException
Return whether or not this request is signed.
@return true if signed false otherwise.
Verify the signature against the TBSRequest object we contain.
return the ASN.1 encoded representation of this object.
Add a request for the given CertificateID.
@param certId certificate ID of interest
Add a request with extensions
@param certId certificate ID of interest
@param singleRequestExtensions the extensions to attach to the request
Set the requestor name to the passed in X509Principal
@param requestorName a X509Principal representing the requestor name.
Generate an unsigned request
@return the OcspReq
@throws OcspException
Return an IEnumerable of the signature names supported by the generator.
@return an IEnumerable containing recognised names.
return the ASN.1 encoded representation of this object.
base generator for an OCSP response - at the moment this only supports the
generation of responses containing BasicOCSP responses.
note 4 is not used.
Carrier for a ResponderID.
Wrapper for the RevokedInfo object
Return the revocation reason, if there is one.
This field is optional; test for it with first.
The revocation reason, if available.
If no revocation reason is available.
Return the status object for the response - null indicates good.
@return the status object for the response, null if it is good.
return the NextUpdate value - note: this is an optional field so may
be returned as null.
@return nextUpdate, or null if not present.
wrapper for the UnknownInfo object
Utility class for creating IBasicAgreement objects from their names/Oids
Cipher Utility class contains methods that can not be specifically grouped into other classes.
Utility class for creating IDigest objects from their names/Oids
Returns a ObjectIdentifier for a given digest mechanism.
A string representation of the digest meanism.
A DerObjectIdentifier, null if the Oid is not available.
A class containing methods to interface the BouncyCastle world to the .NET Crypto world.
Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure.
A System.Security.Cryptography.X509Certificate.
JksTrustedCertEntry is a internal container for the certificate entry.
Utility class for creating HMac object from their names/Oids
Returns a ObjectIdentifier for a give encoding.
A string representation of the encoding.
A DerObjectIdentifier, null if the Oid is not available.
Create and auto-seed an instance based on the given algorithm.
Equivalent to GetInstance(algorithm, true)
e.g. "SHA256PRNG"
Create an instance based on the given algorithm, with optional auto-seeding
e.g. "SHA256PRNG"
If true, the instance will be auto-seeded.
Use the specified instance of IRandomGenerator as random source.
This constructor performs no seeding of either the IRandomGenerator or the
constructed SecureRandom. It is the responsibility of the client to provide
proper seed material as necessary/appropriate for the given IRandomGenerator
implementation.
The source to generate all random bytes from.
Signer Utility class contains methods that can not be specifically grouped into other classes.
Returns an ObjectIdentifier for a given encoding.
A string representation of the encoding.
A DerObjectIdentifier, null if the OID is not available.
Utility class for creating IWrapper objects from their names/Oids
PEM generator for the original set of PEM objects used in Open SSL.
Class for reading OpenSSL PEM encoded streams containing
X509 certificates, PKCS8 encoded keys and PKCS7 objects.
In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
Certificates will be returned using the appropriate java.security type.
Create a new PemReader
@param reader the Reader
Create a new PemReader with a password finder
@param reader the Reader
@param pFinder the password finder
Reads in a X509Certificate.
@return the X509Certificate
@throws IOException if an I/O error occured
Reads in a X509CRL.
@return the X509Certificate
@throws IOException if an I/O error occured
Reads in a PKCS10 certification request.
@return the certificate request.
@throws IOException if an I/O error occured
Reads in a X509 Attribute Certificate.
@return the X509 Attribute Certificate
@throws IOException if an I/O error occured
Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
API.
@return the X509Certificate
@throws IOException if an I/O error occured
Read a Key Pair
General purpose writer for OpenSSL PEM objects.
The TextWriter object to write the output to.
Constructor for an unencrypted private key PEM object.
@param key private key to be encoded.
Constructor for an encrypted private key PEM object.
@param key private key to be encoded
@param algorithm encryption algorithm to use
@param provider provider to use
@throws NoSuchAlgorithmException if algorithm/mode cannot be found
A class for verifying and creating Pkcs10 Certification requests.
CertificationRequest ::= Sequence {
certificationRequestInfo CertificationRequestInfo,
signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
signature BIT STRING
}
CertificationRequestInfo ::= Sequence {
version Integer { v1(0) } (v1,...),
subject Name,
subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
attributes [0] Attributes{{ CRIAttributes }}
}
Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
Attr { ATTRIBUTE:IOSet } ::= Sequence {
type ATTRIBUTE.&id({IOSet}),
values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
}
see
Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
Name of Sig Alg.
X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
Public Key to be included in cert reqest.
ASN1Set of Attributes.
Matching Private key for nominated (above) public key to be used to sign the request.
Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
The factory for signature calculators to sign the PKCS#10 request with.
X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
Public Key to be included in cert reqest.
ASN1Set of Attributes.
Get the public key.
The public key.
Verify Pkcs10 Cert Request is valid.
true = valid.
Returns X509Extensions if the Extensions Request attribute can be found and returns the extensions block.
X509Extensions block or null if one cannot be found.
A class for creating and verifying Pkcs10 Certification requests (this is an extension on ).
The requests are made using delay signing. This is useful for situations where
the private key is in another environment and not directly accessible (e.g. HSM)
So the first step creates the request, then the signing is done outside this
object and the signature is then used to complete the request.
CertificationRequest ::= Sequence {
certificationRequestInfo CertificationRequestInfo,
signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
signature BIT STRING
}
CertificationRequestInfo ::= Sequence {
version Integer { v1(0) } (v1,...),
subject Name,
subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
attributes [0] Attributes{{ CRIAttributes }}
}
Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
Attr { ATTRIBUTE:IOSet } ::= Sequence {
type ATTRIBUTE.&id({IOSet}),
values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
}
see
Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
Name of Sig Alg.
X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
Public Key to be included in cert reqest.
ASN1Set of Attributes.
After the object is constructed use the and finally the
SignRequest methods to finalize the request.
simply return the cert entry for the private key
Utility class for reencoding PKCS#12 files to definite length.
Just re-encode the outer layer of the PKCS#12 file to definite length encoding.
@param berPKCS12File - original PKCS#12 file
@return a byte array representing the DER encoding of the PFX structure
@throws IOException
Re-encode the PKCS#12 structure to definite length encoding at the inner layer
as well, recomputing the MAC accordingly.
@param berPKCS12File - original PKCS12 file.
@param provider - provider to use for MAC calculation.
@return a byte array representing the DER encoding of the PFX structure.
@throws IOException on parsing, encoding errors.
A holding class for a PKCS#8 encrypted private key info object that allows for its decryption.
Base constructor from a PKCS#8 EncryptedPrivateKeyInfo object.
A PKCS#8 EncryptedPrivateKeyInfo object.
Base constructor from a BER encoding of a PKCS#8 EncryptedPrivateKeyInfo object.
A BER encoding of a PKCS#8 EncryptedPrivateKeyInfo objects.
Returns the underlying ASN.1 structure inside this object.
Return the EncryptedPrivateKeyInfo structure in this object.
Returns a copy of the encrypted data in this structure.
Return a copy of the encrypted data in this object.
Return a binary ASN.1 encoding of the EncryptedPrivateKeyInfo structure in this object.
A byte array containing the encoded object.
Get a decryptor from the passed in provider and decrypt the encrypted private key info, returning the result.
A provider to query for decryptors for the object.
The decrypted private key info structure.
Create the encrypted private key info using the passed in encryptor.
The encryptor to use.
An encrypted private key info containing the original private key info.
Base exception for PKCS related issues.
Base exception for parsing related issues in the PKCS namespace.
Create a PrivateKeyInfo representation of a private key with attributes.
@param privateKey the key to be encoded into the info object.
@param attributes the set of attributes to be included.
@return the appropriate PrivateKeyInfo
@throws java.io.IOException on an error encoding the key
Returns the revocationDate.
Returns the certStatus.
Returns an immutable Set
of X.509 attribute certificate
extensions that this PkixAttrCertChecker
supports or
null
if no extensions are supported.
Each element of the set is a String
representing the
Object Identifier (OID) of the X.509 extension that is supported.
All X.509 attribute certificate extensions that a
PkixAttrCertChecker
might possibly be able to process
should be included in the set.
@return an immutable Set
of X.509 extension OIDs (in
String
format) supported by this
PkixAttrCertChecker
, or null
if no
extensions are supported
Performs checks on the specified attribute certificate. Every handled
extension is rmeoved from the unresolvedCritExts
collection.
@param attrCert The attribute certificate to be checked.
@param certPath The certificate path which belongs to the attribute
certificate issuer public key certificate.
@param holderCertPath The certificate path which belongs to the holder
certificate.
@param unresolvedCritExts a Collection
of OID strings
representing the current set of unresolved critical extensions
@throws CertPathValidatorException if the specified attribute certificate
does not pass the check.
Returns a clone of this object.
@return a copy of this PkixAttrCertChecker
Build and validate a CertPath using the given parameter.
@param params PKIXBuilderParameters object containing all information to
build the CertPath
CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281.
@see org.bouncycastle.x509.ExtendedPkixParameters
Validates an attribute certificate with the given certificate path.
params
must be an instance of
ExtendedPkixParameters
.
The target constraints in the params
must be an
X509AttrCertStoreSelector
with at least the attribute
certificate criterion set. Obey that also target informations may be
necessary to correctly validate this attribute certificate.
The attribute certificate issuer must be added to the trusted attribute
issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}.
@param certPath The certificate path which belongs to the attribute
certificate issuer public key certificate.
@param params The PKIX parameters.
@return A PKIXCertPathValidatorResult
of the result of
validating the certPath
.
@throws InvalidAlgorithmParameterException if params
is
inappropriate for this validator.
@throws CertPathValidatorException if the verification fails.
Summary description for PkixBuilderParameters.
Returns an instance of PkixBuilderParameters
.
This method can be used to get a copy from other
PKIXBuilderParameters
, PKIXParameters
,
and ExtendedPKIXParameters
instances.
@param pkixParams The PKIX parameters to create a copy of.
@return An PkixBuilderParameters
instance.
Excluded certificates are not used for building a certification path.
the excluded certificates.
Sets the excluded certificates which are not used for building a
certification path. If the ISet
is null
an
empty set is assumed.
The given set is cloned to protect it against subsequent modifications.
The excluded certificates to set.
Can alse handle ExtendedPKIXBuilderParameters
and
PKIXBuilderParameters
.
@param params Parameters to set.
@see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters)
Makes a copy of this PKIXParameters
object. Changes to the
copy will not affect the original and vice versa.
@return a copy of this PKIXParameters
object
An immutable sequence of certificates (a certification path).
This is an abstract class that defines the methods common to all CertPaths.
Subclasses can handle different kinds of certificates (X.509, PGP, etc.).
All CertPath objects have a type, a list of Certificates, and one or more
supported encodings. Because the CertPath class is immutable, a CertPath
cannot change in any externally visible way after being constructed. This
stipulation applies to all public fields and methods of this class and any
added or overridden by subclasses.
The type is a string that identifies the type of Certificates in the
certification path. For each certificate cert in a certification path
certPath, cert.getType().equals(certPath.getType()) must be true.
The list of Certificates is an ordered List of zero or more Certificates.
This List and all of the Certificates contained in it must be immutable.
Each CertPath object must support one or more encodings so that the object
can be translated into a byte array for storage or transmission to other
parties. Preferably, these encodings should be well-documented standards
(such as PKCS#7). One of the encodings supported by a CertPath is considered
the default encoding. This encoding is used if no encoding is explicitly
requested (for the {@link #getEncoded()} method, for instance).
All CertPath objects are also Serializable. CertPath objects are resolved
into an alternate {@link CertPathRep} object during serialization. This
allows a CertPath object to be serialized into an equivalent representation
regardless of its underlying implementation.
CertPath objects can be created with a CertificateFactory or they can be
returned by other classes, such as a CertPathBuilder.
By convention, X.509 CertPaths (consisting of X509Certificates), are ordered
starting with the target certificate and ending with a certificate issued by
the trust anchor. That is, the issuer of one certificate is the subject of
the following one. The certificate representing the
{@link TrustAnchor TrustAnchor} should not be included in the certification
path. Unvalidated X.509 CertPaths may not follow these conventions. PKIX
CertPathValidators will detect any departure from these conventions that
cause the certification path to be invalid and throw a
CertPathValidatorException.
Concurrent Access
All CertPath objects must be thread-safe. That is, multiple threads may
concurrently invoke the methods defined in this class on a single CertPath
object (or more than one) with no ill effects. This is also true for the List
returned by CertPath.getCertificates.
Requiring CertPath objects to be immutable and thread-safe allows them to be
passed around to various pieces of code without worrying about coordinating
access. Providing this thread-safety is generally not difficult, since the
CertPath and List objects in question are immutable.
@see CertificateFactory
@see CertPathBuilder
CertPath implementation for X.509 certificates.
Creates a CertPath of the specified type.
This constructor is protected because most users should use
a CertificateFactory to create CertPaths.
@param type the standard name of the type of Certificatesin this path
Creates a CertPath of the specified type.
This constructor is protected because most users should use
a CertificateFactory to create CertPaths.
@param type the standard name of the type of Certificatesin this path
Returns an iteration of the encodings supported by this
certification path, with the default encoding
first. Attempts to modify the returned Iterator via its
remove method result in an UnsupportedOperationException.
@return an Iterator over the names of the supported encodings (as Strings)
Compares this certification path for equality with the specified object.
Two CertPaths are equal if and only if their types are equal and their
certificate Lists (and by implication the Certificates in those Lists)
are equal. A CertPath is never equal to an object that is not a CertPath.
This algorithm is implemented by this method. If it is overridden, the
behavior specified here must be maintained.
@param other
the object to test for equality with this certification path
@return true if the specified object is equal to this certification path,
false otherwise
@see Object#hashCode() Object.hashCode()
Returns the encoded form of this certification path, using
the default encoding.
@return the encoded bytes
@exception CertificateEncodingException if an encoding error occurs
Returns the encoded form of this certification path, using
the specified encoding.
@param encoding the name of the encoding to use
@return the encoded bytes
@exception CertificateEncodingException if an encoding error
occurs or the encoding requested is not supported
Returns the list of certificates in this certification
path.
Return a DERObject containing the encoded certificate.
@param cert the X509Certificate object to be encoded
@return the DERObject
Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
@see CertPathBuilderSpi
Build and validate a CertPath using the given parameter.
@param params PKIXBuilderParameters object containing all information to
build the CertPath
Summary description for PkixCertPathBuilderResult.
* Initializes the internal state of this PKIXCertPathChecker
.
*
* The forward
flag specifies the order that certificates
* will be passed to the {@link #check check} method (forward or reverse). A
* PKIXCertPathChecker
must support reverse checking
* and may support forward checking.
*
*
* @param forward
* the order that certificates are presented to the
* check
method. If true
,
* certificates are presented from target to most-trusted CA
* (forward); if false
, from most-trusted CA to
* target (reverse).
* @exception CertPathValidatorException
* if this PKIXCertPathChecker
is unable to
* check certificates in the specified order; it should never
* be thrown if the forward flag is false since reverse
* checking must be supported
Indicates if forward checking is supported. Forward checking refers to
the ability of the PKIXCertPathChecker
to perform its
checks when certificates are presented to the check
method
in the forward direction (from target to most-trusted CA).
@return true
if forward checking is supported,
false
otherwise
* Returns an immutable Set
of X.509 certificate extensions
* that this PKIXCertPathChecker
supports (i.e. recognizes,
* is able to process), or null
if no extensions are
* supported.
*
* Each element of the set is a String
representing the
* Object Identifier (OID) of the X.509 extension that is supported. The OID
* is represented by a set of nonnegative integers separated by periods.
*
* All X.509 certificate extensions that a PKIXCertPathChecker
* might possibly be able to process should be included in the set.
*
*
* @return an immutable Set
of X.509 extension OIDs (in
* String
format) supported by this
* PKIXCertPathChecker
, or null
if no
* extensions are supported
Performs the check(s) on the specified certificate using its internal
state and removes any critical extensions that it processes from the
specified collection of OID strings that represent the unresolved
critical extensions. The certificates are presented in the order
specified by the init
method.
@param cert
the Certificate
to be checked
@param unresolvedCritExts
a Collection
of OID strings representing the
current set of unresolved critical extensions
@exception CertPathValidatorException
if the specified certificate does not pass the check
Returns a clone of this object. Calls the Object.clone()
method. All subclasses which maintain state must support and override
this method, if necessary.
@return a copy of this PKIXCertPathChecker
The Service Provider Interface (SPI)
for the {@link CertPathValidator CertPathValidator} class. All
CertPathValidator
implementations must include a class (the
SPI class) that extends this class (CertPathValidatorSpi
)
and implements all of its methods. In general, instances of this class
should only be accessed through the CertPathValidator
class.
For details, see the Java Cryptography Architecture.
Concurrent Access
Instances of this class need not be protected against concurrent
access from multiple threads. Threads that need to access a single
CertPathValidatorSpi
instance concurrently should synchronize
amongst themselves and provide the necessary locking before calling the
wrapping CertPathValidator
object.
However, implementations of CertPathValidatorSpi
may still
encounter concurrency issues, since multiple threads each
manipulating a different CertPathValidatorSpi
instance need not
synchronize.
CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC
3280.
An exception indicating one of a variety of problems encountered when
validating a certification path.
A CertPathValidatorException
provides support for wrapping
exceptions. The {@link #getCause getCause} method returns the throwable,
if any, that caused this exception to be thrown.
A CertPathValidatorException
may also include the
certification path that was being validated when the exception was thrown
and the index of the certificate in the certification path that caused the
exception to be thrown. Use the {@link #getCertPath getCertPath} and
{@link #getIndex getIndex} methods to retrieve this information.
Concurrent Access
Unless otherwise specified, the methods defined in this class are not
thread-safe. Multiple threads that need to access a single
object concurrently should synchronize amongst themselves and
provide the necessary locking. Multiple threads each manipulating
separate objects need not synchronize.
@see CertPathValidator
Creates a PkixCertPathValidatorException
with the specified
detail message, cause, certification path, and index.
the detail message (or null
if none)
the cause (or null
if none)
the index of the certificate in the certification path that *
eturns the index of the certificate in the certification path that caused the exception to be
thrown.
Note that the list of certificates in a is zero based. If no index has been set,
-1 is returned.
The index that has been set, or -1 if none has been set.
Summary description for PkixCertPathValidatorResult.
Summary description for PkixCertPathValidatorUtilities.
key usage bits
Search the given Set of TrustAnchor's for one that is the
issuer of the given X509 certificate.
the X509 certificate
a Set of TrustAnchor's
the TrustAnchor
object if found or
null
if not.
@exception
Returns the issuer of an attribute certificate or certificate.
The attribute certificate or certificate.
The issuer as X500Principal
.
Return the next working key inheriting DSA parameters if necessary.
This methods inherits DSA parameters from the indexed certificate or
previous certificates in the certificate chain to the returned
PublicKey
. The list is searched upwards, meaning the end
certificate is at position 0 and previous certificates are following.
If the indexed certificate does not contain a DSA key this method simply
returns the public key. If the DSA key already contains DSA parameters
the key is also only returned.
@param certs The certification path.
@param index The index of the certificate which contains the public key
which should be extended with DSA parameters.
@return The public key of the certificate in list position
index
extended with DSA parameters if applicable.
@throws Exception if DSA parameters cannot be inherited.
Add the CRL issuers from the cRLIssuer field of the distribution point or
from the certificate if not given to the issuer criterion of the
selector
.
The issuerPrincipals
are a collection with a single
X500Principal
for X509Certificate
s. For
{@link X509AttributeCertificate}s the issuer may contain more than one
X500Principal
.
@param dp The distribution point.
@param issuerPrincipals The issuers of the certificate or attribute
certificate which contains the distribution point.
@param selector The CRL selector.
@param pkixParams The PKIX parameters containing the cert stores.
@throws Exception if an exception occurs while processing.
@throws ClassCastException if issuerPrincipals
does not
contain only X500Principal
s.
Fetches complete CRLs according to RFC 3280.
@param dp The distribution point for which the complete CRL
@param cert The X509Certificate
or
{@link org.bouncycastle.x509.X509AttributeCertificate} for
which the CRL should be searched.
@param currentDate The date for which the delta CRLs must be valid.
@param paramsPKIX The extended PKIX parameters.
@return A Set
of X509CRL
s with complete
CRLs.
@throws Exception if an exception occurs while picking the CRLs
or no CRLs are found.
Fetches delta CRLs according to RFC 3280 section 5.2.4.
@param currentDate The date for which the delta CRLs must be valid.
@param paramsPKIX The extended PKIX parameters.
@param completeCRL The complete CRL the delta CRL is for.
@return A Set
of X509CRL
s with delta CRLs.
@throws Exception if an exception occurs while picking the delta
CRLs.
Find the issuer certificates of a given certificate.
@param cert
The certificate for which an issuer should be found.
@param pkixParams
@return A Collection
object containing the issuer
X509Certificate
s. Never null
.
@exception Exception
if an error occurs.
crl checking
Return a Collection of all CRLs found in the X509Store's that are
matching the crlSelect criteriums.
a {@link X509CRLStoreSelector} object that will be used
to select the CRLs
a List containing only {@link org.bouncycastle.x509.X509Store
X509Store} objects. These are used to search for CRLs
a Collection of all found {@link X509CRL X509CRL} objects. May be
empty but never null
.
Returns the intersection of the permitted IP ranges in
permitted
with ip
.
@param permitted A Set
of permitted IP addresses with
their subnet mask as byte arrays.
@param ips The IP address with its subnet mask.
@return The Set
of permitted IP ranges intersected with
ip
.
Returns the union of the excluded IP ranges in excluded
with ip
.
@param excluded A Set
of excluded IP addresses with their
subnet mask as byte arrays.
@param ip The IP address with its subnet mask.
@return The Set
of excluded IP ranges unified with
ip
as byte arrays.
Calculates the union if two IP ranges.
@param ipWithSubmask1 The first IP address with its subnet mask.
@param ipWithSubmask2 The second IP address with its subnet mask.
@return A Set
with the union of both addresses.
Calculates the interesction if two IP ranges.
@param ipWithSubmask1 The first IP address with its subnet mask.
@param ipWithSubmask2 The second IP address with its subnet mask.
@return A Set
with the single IP address with its subnet
mask as a byte array or an empty Set
.
Concatenates the IP address with its subnet mask.
@param ip The IP address.
@param subnetMask Its subnet mask.
@return The concatenated IP address with its subnet mask.
Splits the IP addresses and their subnet mask.
@param ipWithSubmask1 The first IP address with the subnet mask.
@param ipWithSubmask2 The second IP address with the subnet mask.
@return An array with two elements. Each element contains the IP address
and the subnet mask in this order.
Based on the two IP addresses and their subnet masks the IP range is
computed for each IP address - subnet mask pair and returned as the
minimum IP address and the maximum address of the range.
@param ip1 The first IP address.
@param subnetmask1 The subnet mask of the first IP address.
@param ip2 The second IP address.
@param subnetmask2 The subnet mask of the second IP address.
@return A array with two elements. The first/second element contains the
min and max IP address of the first/second IP address and its
subnet mask.
Checks if the IP address ip
is constrained by
constraint
.
@param constraint The constraint. This is an IP address concatenated with
its subnetmask.
@param ip The IP address.
@return true
if constrained, false
otherwise.
Checks if the IP ip
is included in the permitted ISet
permitted
.
@param permitted A Set
of permitted IP addresses with
their subnet mask as byte arrays.
@param ip The IP address.
@throws PkixNameConstraintValidatorException
if the IP is not permitted.
Checks if the IP ip
is included in the excluded ISet
excluded
.
@param excluded A Set
of excluded IP addresses with their
subnet mask as byte arrays.
@param ip The IP address.
@throws PkixNameConstraintValidatorException
if the IP is excluded.
The common part of email1
and email2
is
added to the union union
. If email1
and
email2
have nothing in common they are added both.
@param email1 Email address constraint 1.
@param email2 Email address constraint 2.
@param union The union.
The most restricting part from email1
and
email2
is added to the intersection intersect
.
@param email1 Email address constraint 1.
@param email2 Email address constraint 2.
@param intersect The intersection.
Checks if the given GeneralName is in the permitted ISet.
@param name The GeneralName
@throws PkixNameConstraintValidatorException
If the name
Check if the given GeneralName is contained in the excluded ISet.
@param name The GeneralName.
@throws PkixNameConstraintValidatorException
If the name
is
excluded.
Updates the permitted ISet of these name constraints with the intersection
with the given subtree.
@param permitted The permitted subtrees
Adds a subtree to the excluded ISet of these name constraints.
@param subtree A subtree with an excluded GeneralName.
Returns the maximum IP address.
@param ip1 The first IP address.
@param ip2 The second IP address.
@return The maximum IP address.
Returns the minimum IP address.
@param ip1 The first IP address.
@param ip2 The second IP address.
@return The minimum IP address.
Compares IP address ip1
with ip2
. If ip1
is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1
otherwise.
@param ip1 The first IP address.
@param ip2 The second IP address.
@return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise.
Returns the logical OR of the IP addresses ip1
and
ip2
.
@param ip1 The first IP address.
@param ip2 The second IP address.
@return The OR of ip1
and ip2
.
Stringifies an IPv4 or v6 address with subnet mask.
@param ip The IP with subnet mask.
@return The stringified IP address.
Summary description for PkixParameters.
This is the default PKIX validity model. Actually there are two variants
of this: The PKIX model and the modified PKIX model. The PKIX model
verifies that all involved certificates must have been valid at the
current time. The modified PKIX model verifies that all involved
certificates were valid at the signing time. Both are indirectly choosen
with the {@link PKIXParameters#setDate(java.util.Date)} method, so this
methods sets the Date when all certificates must have been
valid.
This model uses the following validity model. Each certificate must have
been valid at the moment where is was used. That means the end
certificate must have been valid at the time the signature was done. The
CA certificate which signed the end certificate must have been valid,
when the end certificate was signed. The CA (or Root CA) certificate must
have been valid, when the CA certificate was signed and so on. So the
{@link PKIXParameters#setDate(java.util.Date)} method sets the time, when
the end certificate must have been valid. It is used e.g.
in the German signature law.
Creates an instance of PKIXParameters with the specified Set of
most-trusted CAs. Each element of the set is a TrustAnchor.
Note that the Set is copied to protect against subsequent modifications.
@param trustAnchors
a Set of TrustAnchors
@exception InvalidAlgorithmParameterException
if the specified Set is empty
(trustAnchors.isEmpty() == true)
@exception NullPointerException
if the specified Set is null
@exception ClassCastException
if any of the elements in the Set are not of type
java.security.cert.TrustAnchor
Returns the required constraints on the target certificate or attribute
certificate. The constraints are returned as an instance of
IX509Selector
. If null
, no constraints are
defined.
The target certificate in a PKIX path may be a certificate or an
attribute certificate.
Note that the IX509Selector
returned is cloned to protect
against subsequent modifications.
@return a IX509Selector
specifying the constraints on the
target certificate or attribute certificate (or null
)
@see #setTargetConstraints
@see X509CertStoreSelector
@see X509AttributeCertStoreSelector
Sets the required constraints on the target certificate or attribute
certificate. The constraints are specified as an instance of
IX509Selector
. If null
, no constraints are
defined.
The target certificate in a PKIX path may be a certificate or an
attribute certificate.
Note that the IX509Selector
specified is cloned to protect
against subsequent modifications.
@param selector a IX509Selector
specifying the constraints on
the target certificate or attribute certificate (or
null
)
@see #getTargetConstraints
@see X509CertStoreSelector
@see X509AttributeCertStoreSelector
Returns the required constraints on the target certificate. The
constraints are returned as an instance of CertSelector. If
null
, no constraints are defined.
Note that the CertSelector returned is cloned to protect against
subsequent modifications.
@return a CertSelector specifying the constraints on the target
certificate (or null
)
@see #setTargetCertConstraints(CertSelector)
Sets the required constraints on the target certificate. The constraints
are specified as an instance of CertSelector. If null, no constraints are
defined.
Note that the CertSelector specified is cloned to protect against
subsequent modifications.
@param selector
a CertSelector specifying the constraints on the target
certificate (or null
)
@see #getTargetCertConstraints()
Returns an immutable Set of initial policy identifiers (OID strings),
indicating that any one of these policies would be acceptable to the
certificate user for the purposes of certification path processing. The
default return value is an empty Set
, which is
interpreted as meaning that any policy would be acceptable.
@return an immutable Set
of initial policy OIDs in String
format, or an empty Set
(implying any policy is
acceptable). Never returns null
.
@see #setInitialPolicies(java.util.Set)
Sets the Set
of initial policy identifiers (OID strings),
indicating that any one of these policies would be acceptable to the
certificate user for the purposes of certification path processing. By
default, any policy is acceptable (i.e. all policies), so a user that
wants to allow any policy as acceptable does not need to call this
method, or can call it with an empty Set
(or
null
).
Note that the Set is copied to protect against subsequent modifications.
@param initialPolicies
a Set of initial policy OIDs in String format (or
null
)
@exception ClassCastException
if any of the elements in the set are not of type String
@see #getInitialPolicies()
Sets a List
of additional certification path checkers. If
the specified List contains an object that is not a PKIXCertPathChecker,
it is ignored.
Each PKIXCertPathChecker
specified implements additional
checks on a certificate. Typically, these are checks to process and
verify private extensions contained in certificates. Each
PKIXCertPathChecker
should be instantiated with any
initialization parameters needed to execute the check.
This method allows sophisticated applications to extend a PKIX
CertPathValidator
or CertPathBuilder
. Each
of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX
CertPathValidator
or CertPathBuilder
for
each certificate processed or validated.
Regardless of whether these additional PKIXCertPathCheckers are set, a
PKIX CertPathValidator
or CertPathBuilder
must perform all of the required PKIX checks on each certificate. The one
exception to this rule is if the RevocationEnabled flag is set to false
(see the {@link #setRevocationEnabled(boolean) setRevocationEnabled}
method).
Note that the List supplied here is copied and each PKIXCertPathChecker
in the list is cloned to protect against subsequent modifications.
@param checkers
a List of PKIXCertPathCheckers. May be null, in which case no
additional checkers will be used.
@exception ClassCastException
if any of the elements in the list are not of type
java.security.cert.PKIXCertPathChecker
@see #getCertPathCheckers()
Returns the List of certification path checkers. Each PKIXCertPathChecker
in the returned IList is cloned to protect against subsequent modifications.
@return an immutable List of PKIXCertPathCheckers (may be empty, but not
null
)
@see #setCertPathCheckers(java.util.List)
Adds a PKIXCertPathChecker
to the list of certification
path checkers. See the {@link #setCertPathCheckers setCertPathCheckers}
method for more details.
Note that the PKIXCertPathChecker
is cloned to protect
against subsequent modifications.
@param checker a PKIXCertPathChecker
to add to the list of
checks. If null
, the checker is ignored (not added to list).
Method to support Clone()
under J2ME.
super.Clone()
does not exist and fields are not copied.
@param params Parameters to set. If this are
ExtendedPkixParameters
they are copied to.
Whether delta CRLs should be used for checking the revocation status.
Defaults to false
.
The validity model.
@see #CHAIN_VALIDITY_MODEL
@see #PKIX_VALIDITY_MODEL
Returns if additional {@link X509Store}s for locations like LDAP found
in certificates or CRLs should be used.
@return Returns true
if additional stores are used.
Sets if additional {@link X509Store}s for locations like LDAP found in
certificates or CRLs should be used.
@param enabled true
if additional stores are used.
Returns the trusted attribute certificate issuers. If attribute
certificates is verified the trusted AC issuers must be set.
The returned ISet
consists of TrustAnchor
s.
The returned ISet
is immutable. Never null
@return Returns an immutable set of the trusted AC issuers.
Sets the trusted attribute certificate issuers. If attribute certificates
is verified the trusted AC issuers must be set.
The trustedACIssuers
must be a ISet
of
TrustAnchor
The given set is cloned.
@param trustedACIssuers The trusted AC issuers to set. Is never
null
.
@throws ClassCastException if an element of stores
is not
a TrustAnchor
.
Returns the necessary attributes which must be contained in an attribute
certificate.
The returned ISet
is immutable and contains
String
s with the OIDs.
@return Returns the necessary AC attributes.
Sets the necessary which must be contained in an attribute certificate.
The ISet
must contain String
s with the
OIDs.
The set is cloned.
@param necessaryACAttributes The necessary AC attributes to set.
@throws ClassCastException if an element of
necessaryACAttributes
is not a
String
.
Returns the attribute certificates which are not allowed.
The returned ISet
is immutable and contains
String
s with the OIDs.
@return Returns the prohibited AC attributes. Is never null
.
Sets the attribute certificates which are not allowed.
The ISet
must contain String
s with the
OIDs.
The set is cloned.
@param prohibitedACAttributes The prohibited AC attributes to set.
@throws ClassCastException if an element of
prohibitedACAttributes
is not a
String
.
Returns the attribute certificate checker. The returned set contains
{@link PKIXAttrCertChecker}s and is immutable.
@return Returns the attribute certificate checker. Is never
null
.
Sets the attribute certificate checkers.
All elements in the ISet
must a {@link PKIXAttrCertChecker}.
The given set is cloned.
@param attrCertCheckers The attribute certificate checkers to set. Is
never null
.
@throws ClassCastException if an element of attrCertCheckers
is not a PKIXAttrCertChecker
.
Summary description for PkixPolicyNode.
Constructors
This class helps to handle CRL revocation reasons mask. Each CRL handles a
certain set of revocation reasons.
Constructs are reason mask with the reasons.
The reasons.
A reason mask with no reason.
A mask with all revocation reasons.
Adds all reasons from the reasons mask to this mask.
@param mask The reasons mask to add.
Returns true
if this reasons mask contains all possible
reasons.
true if this reasons mask contains all possible reasons.
Intersects this mask with the given reasons mask.
mask The mask to intersect with.
The intersection of this and teh given mask.
Returns true if the passed reasons mask has new reasons.
The reasons mask which should be tested for new reasons.
true if the passed reasons mask has new reasons.
Returns the reasons in this mask.
If the complete CRL includes an issuing distribution point (IDP) CRL
extension check the following:
(i) If the distribution point name is present in the IDP CRL extension
and the distribution field is present in the DP, then verify that one of
the names in the IDP matches one of the names in the DP. If the
distribution point name is present in the IDP CRL extension and the
distribution field is omitted from the DP, then verify that one of the
names in the IDP matches one of the names in the cRLIssuer field of the
DP.
(ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
extension, verify that the certificate does not include the basic
constraints extension with the cA boolean asserted.
(iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
extension, verify that the certificate includes the basic constraints
extension with the cA boolean asserted.
(iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
@param dp The distribution point.
@param cert The certificate.
@param crl The CRL.
@throws AnnotatedException if one of the conditions is not met or an error occurs.
If the DP includes cRLIssuer, then verify that the issuer field in the
complete CRL matches cRLIssuer in the DP and that the complete CRL
contains an
g distribution point extension with the indirectCRL
boolean asserted. Otherwise, verify that the CRL issuer matches the
certificate issuer.
@param dp The distribution point.
@param cert The certificate ot attribute certificate.
@param crl The CRL for cert
.
@throws AnnotatedException if one of the above conditions does not apply or an error
occurs.
Obtain and validate the certification path for the complete CRL issuer.
If a key usage extension is present in the CRL issuer's certificate,
verify that the cRLSign bit is set.
@param crl CRL which contains revocation information for the certificate
cert
.
@param cert The attribute certificate or certificate to check if it is
revoked.
@param defaultCRLSignCert The issuer certificate of the certificate cert
.
@param defaultCRLSignKey The public key of the issuer certificate
defaultCRLSignCert
.
@param paramsPKIX paramsPKIX PKIX parameters.
@param certPathCerts The certificates on the certification path.
@return A Set
with all keys of possible CRL issuer
certificates.
@throws AnnotatedException if the CRL is not valid or the status cannot be checked or
some error occurs.
Checks a distribution point for revocation information for the
certificate cert
.
@param dp The distribution point to consider.
@param paramsPKIX PKIX parameters.
@param cert Certificate to check if it is revoked.
@param validDate The date when the certificate revocation status should be
checked.
@param defaultCRLSignCert The issuer certificate of the certificate cert
.
@param defaultCRLSignKey The public key of the issuer certificate
defaultCRLSignCert
.
@param certStatus The current certificate revocation status.
@param reasonMask The reasons mask which is already checked.
@param certPathCerts The certificates of the certification path.
@throws AnnotatedException if the certificate is revoked or the status cannot be checked
or some error occurs.
Checks a certificate if it is revoked.
@param paramsPKIX PKIX parameters.
@param cert Certificate to check if it is revoked.
@param validDate The date when the certificate revocation status should be
checked.
@param sign The issuer certificate of the certificate cert
.
@param workingPublicKey The public key of the issuer certificate sign
.
@param certPathCerts The certificates of the certification path.
@throws AnnotatedException if the certificate is revoked or the status cannot be checked
or some error occurs.
If use-deltas is set, verify the issuer and scope of the delta CRL.
@param deltaCRL The delta CRL.
@param completeCRL The complete CRL.
@param pkixParams The PKIX paramaters.
@throws AnnotatedException if an exception occurs.
Checks if an attribute certificate is revoked.
@param attrCert Attribute certificate to check if it is revoked.
@param paramsPKIX PKIX parameters.
@param issuerCert The issuer certificate of the attribute certificate
attrCert
.
@param validDate The date when the certificate revocation status should
be checked.
@param certPathCerts The certificates of the certification path to be
checked.
@throws CertPathValidatorException if the certificate is revoked or the
status cannot be checked or some error occurs.
Searches for a holder public key certificate and verifies its
certification path.
@param attrCert the attribute certificate.
@param pkixParams The PKIX parameters.
@return The certificate path of the holder certificate.
@throws Exception if
- no public key certificate can be found although holder
information is given by an entity name or a base certificate
ID
- support classes cannot be created
- no certification path for the public key certificate can
be built
Checks a distribution point for revocation information for the
certificate attrCert
.
@param dp The distribution point to consider.
@param attrCert The attribute certificate which should be checked.
@param paramsPKIX PKIX parameters.
@param validDate The date when the certificate revocation status should
be checked.
@param issuerCert Certificate to check if it is revoked.
@param reasonMask The reasons mask which is already checked.
@param certPathCerts The certificates of the certification path to be
checked.
@throws Exception if the certificate is revoked or the status
cannot be checked or some error occurs.
A trust anchor or most-trusted Certification Authority (CA).
This class represents a "most-trusted CA", which is used as a trust anchor
for validating X.509 certification paths. A most-trusted CA includes the
public key of the CA, the CA's name, and any constraints upon the set of
paths which may be validated using this key. These parameters can be
specified in the form of a trusted X509Certificate or as individual
parameters.
Creates an instance of TrustAnchor with the specified X509Certificate and
optional name constraints, which are intended to be used as additional
constraints when validating an X.509 certification path.
The name constraints are specified as a byte array. This byte array
should contain the DER encoded form of the name constraints, as they
would appear in the NameConstraints structure defined in RFC 2459 and
X.509. The ASN.1 definition of this structure appears below.
NameConstraints ::= SEQUENCE {
permittedSubtrees [0] GeneralSubtrees OPTIONAL,
excludedSubtrees [1] GeneralSubtrees OPTIONAL }
GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
GeneralSubtree ::= SEQUENCE {
base GeneralName,
minimum [0] BaseDistance DEFAULT 0,
maximum [1] BaseDistance OPTIONAL }
BaseDistance ::= INTEGER (0..MAX)
GeneralName ::= CHOICE {
otherName [0] OtherName,
rfc822Name [1] IA5String,
dNSName [2] IA5String,
x400Address [3] ORAddress,
directoryName [4] Name,
ediPartyName [5] EDIPartyName,
uniformResourceIdentifier [6] IA5String,
iPAddress [7] OCTET STRING,
registeredID [8] OBJECT IDENTIFIER}
Note that the name constraints byte array supplied is cloned to protect
against subsequent modifications.
a trusted X509Certificate
a byte array containing the ASN.1 DER encoding of a
NameConstraints extension to be used for checking name
constraints. Only the value of the extension is included, not
the OID or criticality flag. Specify null to omit the
parameter.
if the specified X509Certificate is null
Creates an instance of TrustAnchor where the
most-trusted CA is specified as an X500Principal and public key.
Name constraints are an optional parameter, and are intended to be used
as additional constraints when validating an X.509 certification path.
The name constraints are specified as a byte array. This byte array
contains the DER encoded form of the name constraints, as they
would appear in the NameConstraints structure defined in RFC 2459
and X.509. The ASN.1 notation for this structure is supplied in the
documentation for the other constructors.
Note that the name constraints byte array supplied here is cloned to
protect against subsequent modifications.
the name of the most-trusted CA as X509Name
the public key of the most-trusted CA
a byte array containing the ASN.1 DER encoding of a NameConstraints extension to
be used for checking name constraints. Only the value of the extension is included,
not the OID or criticality flag. Specify null to omit the parameter.
if caPrincipal or pubKey is null
Creates an instance of TrustAnchor
where the most-trusted
CA is specified as a distinguished name and public key. Name constraints
are an optional parameter, and are intended to be used as additional
constraints when validating an X.509 certification path.
The name constraints are specified as a byte array. This byte array
contains the DER encoded form of the name constraints, as they would
appear in the NameConstraints structure defined in RFC 2459 and X.509.
the X.500 distinguished name of the most-trusted CA in RFC
2253 string format
the public key of the most-trusted CA
a byte array containing the ASN.1 DER encoding of a
NameConstraints extension to be used for checking name
constraints. Only the value of the extension is included, not
the OID or criticality flag. Specify null to omit the
parameter.
throws NullPointerException, IllegalArgumentException
Returns the most-trusted CA certificate.
Returns the name of the most-trusted CA as an X509Name.
Returns the name of the most-trusted CA in RFC 2253 string format.
Returns the public key of the most-trusted CA.
Decode the name constraints and clone them if not null.
Returns a formatted string describing the TrustAnchor
.
a formatted string describing the TrustAnchor
Base class for a TLS client.
an of (or null).
The default implementation calls this to determine which named
groups to include in the supported_groups extension for the ClientHello.
The named group roles for which there should
be at least one supported group. By default this is inferred from the offered cipher suites and signature
algorithms.
an of . See for group constants.
Base class for supporting a TLS key exchange implementation.
Base class for supporting a TLS key exchange factory implementation.
Base class for a TLS client or server.
Get the values that are supported by this peer.
WARNING: Mixing DTLS and TLS versions in the returned array is currently NOT supported. Use a separate
(sub-)class for each case.
an array of supported values.
Base class for a TLS server.
RFC 5246 7.2.
This message notifies the recipient that the sender will not send any more messages on this
connection.
Note that as of TLS 1.1, failure to properly close a connection no longer requires that a session not be
resumed. This is a change from TLS 1.0 ("The session becomes unresumable if any connection is terminated
without proper close_notify messages with level equal to warning.") to conform with widespread
implementation practice.
An inappropriate message was received.
This alert is always fatal and should never be observed in communication between proper implementations.
This alert is returned if a record is received with an incorrect MAC.
This alert also MUST be returned if an alert is sent because a TLSCiphertext decrypted in an invalid way:
either it wasn't an even multiple of the block length, or its padding values, when checked, weren't
correct. This message is always fatal and should never be observed in communication between proper
implementations (except when messages were corrupted in the network).
This alert was used in some earlier versions of TLS, and may have permitted certain attacks against the CBC
mode [CBCATT]. It MUST NOT be sent by compliant implementations.
A TLSCiphertext record was received that had a length more than 2^14+2048 bytes, or a record
decrypted to a TLSCompressed record with more than 2^14+1024 bytes.
This message is always fatal and should never be observed in communication between proper implementations
(except when messages were corrupted in the network).
The decompression function received improper input (e.g., data that would expand to excessive
length).
This message is always fatal and should never be observed in communication between proper implementations.
Reception of a handshake_failure alert message indicates that the sender was unable to negotiate
an acceptable set of security parameters given the options available.
This is a fatal error.
This alert was used in SSLv3 but not any version of TLS. It MUST NOT be sent by compliant implementations.
A certificate was corrupt, contained signatures that did not verify correctly, etc.
A certificate was of an unsupported type.
A certificate was revoked by its signer.
A certificate has expired or is not currently valid.
Some other (unspecified) issue arose in processing the certificate, rendering it unacceptable.
A field in the handshake was out of range or inconsistent with other fields.
This message is always fatal.
A valid certificate chain or partial chain was received, but the certificate was not accepted
because the CA certificate could not be located or couldn't be matched with a known, trusted CA.
This message is always fatal.
A valid certificate was received, but when access control was applied, the sender decided not to
proceed with negotiation.
This message is always fatal.
A message could not be decoded because some field was out of the specified range or the length of
the message was incorrect.
This message is always fatal and should never be observed in communication between proper
implementations (except when messages were corrupted in the network).
A handshake cryptographic operation failed, including being unable to correctly verify a signature
or validate a Finished message.
This message is always fatal.
This alert was used in some earlier versions of TLS. It MUST NOT be sent by compliant implementations.
The protocol version the client has attempted to negotiate is recognized but not supported.
(For example, old protocol versions might be avoided for security reasons.) This message is always fatal.
Returned instead of handshake_failure when a negotiation has failed specifically because the
server requires ciphers more secure than those supported by the client.
This message is always fatal.
An internal error unrelated to the peer or the correctness of the protocol (such as a memory
allocation failure) makes it impossible to continue.
This message is always fatal.
This handshake is being canceled for some reason unrelated to a protocol failure.
If the user cancels an operation after the handshake is complete, just closing the connection by sending a
close_notify is more appropriate. This alert should be followed by a close_notify. This message is
generally a warning.
Sent by the client in response to a hello request or by the server in response to a client hello
after initial handshaking.
Either of these would normally lead to renegotiation; when that is not appropriate, the recipient should
respond with this alert. At that point, the original requester can decide whether to proceed with the
connection. One case where this would be appropriate is where a server has spawned a process to satisfy a
request; the process might receive security parameters (key length, authentication, etc.) at startup, and
it might be difficult to communicate changes to these parameters after that point. This message is always a
warning.
Sent by clients that receive an extended server hello containing an extension that they did not
put in the corresponding client hello.
This message is always fatal.
This alert is sent by servers who are unable to retrieve a certificate chain from the URL supplied
by the client(see Section 3.3).
This message MAY be fatal - for example if client authentication is required by the server for the
handshake to continue and the server is unable to retrieve the certificate chain, it may send a fatal
alert.
This alert is sent by servers that receive a server_name extension request, but do not recognize
the server name.
This message MAY be fatal.
This alert is sent by clients that receive an invalid certificate status response (see Section 3.6
).
This message is always fatal.
This alert is sent by servers when a certificate hash does not match a client provided
certificate_hash.
This message is always fatal.
If the server does not recognize the PSK identity, it MAY respond with an "unknown_psk_identity"
alert message.
In the event that the server supports no protocols that the client advertises, then the server
SHALL respond with a fatal "no_application_protocol" alert.
If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest protocol version
supported by the server is higher than the version indicated in ClientHello.client_version, the server MUST
respond with a fatal inappropriate_fallback alert[..].
Sent by endpoints that receive a handshake message not containing an extension that is mandatory
to send for the offered TLS version or other negotiated parameters.
Sent by servers when a client certificate is desired but none was provided by the client.
RFC 5246 7.2
A basic PSK Identity holder.
A basic SRP Identity holder.
A queue for bytes. This file could be more optimized.
The smallest number which can be written as 2^x which is bigger than i.
The buffer where we store our data.
How many bytes at the beginning of the buffer are skipped.
How many bytes in the buffer are valid data.
Add some data to our buffer.
A byte-array to read data from.
How many bytes to skip at the beginning of the array.
How many bytes to read from the array.
The number of bytes which are available in this buffer.
Copy some bytes from the beginning of the data to the provided .
The to copy the bytes to.
How many bytes to copy.
Read data from the buffer.
The buffer where the read data will be copied to.
How many bytes to skip at the beginning of buf.
How many bytes to read at all.
How many bytes from our data to skip.
Return a over some bytes at the beginning of the data.
How many bytes will be readable.
A over the data.
Remove some bytes from our data from the beginning.
How many bytes to remove.
Remove data from the buffer.
The buffer where the removed data will be copied to.
How many bytes to skip at the beginning of buf.
How many bytes to read at all.
How many bytes from our data to skip.
OutputStream based on a ByteQueue implementation.
Implementation of the RFC 3546 3.3. CertChainType.
Parsing and encoding of a Certificate struct from RFC 4346.
opaque ASN.1Cert<2^24-1>;
struct {
ASN.1Cert certificate_list<0..2^24-1>;
} Certificate;
an array of representing a certificate chain.
true if this certificate chain contains no certificates, or false otherwise.
Encode this to a , and optionally calculate the
"end point hash" (per RFC 5929's tls-server-end-point binding).
the of the current connection.
the to encode to.
the to write the "end point hash" to (or null).
Parse a from a .
the to apply during parsing.
the of the current connection.
the to parse from.
the to write the "end point hash" to (or null).
a object.
RFC 8879
Parsing and encoding of a CertificateRequest struct from RFC 4346.
struct {
ClientCertificateType certificate_types<1..2^8-1>;
DistinguishedName certificate_authorities<3..2^16-1>;
} CertificateRequest;
Updated for RFC 5246:
struct {
ClientCertificateType certificate_types <1..2 ^ 8 - 1>;
SignatureAndHashAlgorithm supported_signature_algorithms <2 ^ 16 - 1>;
DistinguishedName certificate_authorities <0..2 ^ 16 - 1>;
} CertificateRequest;
Revised for RFC 8446:
struct {
opaque certificate_request_context <0..2 ^ 8 - 1>;
Extension extensions <2..2 ^ 16 - 1>;
} CertificateRequest;
see for valid constants.
an of .
an array of certificate types
an of (or null before TLS 1.2).
an optional of . May be non-null from
TLS 1.3 onwards.
an of .
Encode this to a .
the of the current connection.
the to encode to.
Parse a from a
the of the current connection.
the to parse from.
a object.
an of (possibly null) .
Encode this to a .
the to encode to.
Parse a from a .
the of the current connection.
the to parse from.
a object.
Implementation of the RFC 3546 3.6. CertificateStatusRequest.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
Implementation of the RFC 6961 2.2. CertificateStatusRequestItemV2.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 6091
RFC 3546 3.3
see for valid constants.
an of .
an of .
Encode this to a .
the to encode to.
Parse a from a .
the of the current connection.
the to parse from.
a object.
a value.
Encode this to a .
the to encode to.
Parse a from a .
the of the current connection.
the to parse from.
a object.
RFC 5056
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g.serialization).
RFC 2246 A.5
RFC 2246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
Encode this to a .
the of the current connection.
the to encode to.
Parse a from a .
the to parse from.
for DTLS this should be non-null; the input is copied to this
, minus the cookie field.
a object.
A combined hash, which implements md5(m) || sha1(m).
RFC 2246 6.1
RFC 2246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values(e.g.serialization).
RFC 2246 6.2.1
Carrier class for Diffie-Hellman group parameters.
Base constructor with the prime factor of (p - 1).
the prime modulus.
specifies the prime factor of (p - 1).
the base generator.
Standard Diffie-Hellman groups from various IETF specifications.
Base class for a TlsCrypto implementation that provides some needed methods from elsewhere in the impl
package.
Base class for a TlsSecret implementation which captures common code and fields.
Base constructor.
the byte[] making up the secret value.
Credentialed class generating agreed secrets from a peer's public key for our end of the TLS connection
using the BC light-weight API.
Credentialed class decrypting RSA encrypted secrets sent from a peer for our end of the TLS connection
using the BC light-weight API.
Credentialed class for generating signatures based on the use of primitives from the BC light-weight API.
HMAC implementation based on original internet draft for HMAC (RFC 2104).
The difference is that padding is concatenated versus XORed with the key, e.g:
H(K + opad, H(K + ipad, text))
Base constructor for one of the standard digest algorithms for which the byteLength is known.
Behaviour is undefined for digests other than MD5 or SHA1.
the digest.
Reset the mac generator.
Implementation class for a single X.509 certificate based on the BC light-weight API.
Class for providing cryptographic services for TLS based on implementations in the BC light-weight API.
This class provides default implementations for everything. If you need to customise it, extend the class
and override the appropriate methods.
Support class for ephemeral Diffie-Hellman using the BC light-weight library.
BC light-weight support class for Diffie-Hellman key pair generation and key agreement over a
specified Diffie-Hellman configuration.
Implementation class for generation of the raw DSA signature type using the BC light-weight API.
Implementation class for the verification of the raw DSA signature type using the BC light-weight API.
BC light-weight base class for the signers implementing the two DSA style algorithms from FIPS PUB
186-4: DSA and ECDSA.
BC light-weight base class for the verifiers supporting the two DSA style algorithms from FIPS PUB
186-4: DSA and ECDSA.
Support class for ephemeral Elliptic Curve Diffie-Hellman using the BC light-weight library.
EC domain class for generating key pairs and performing key agreement.
Implementation class for generation of ECDSA signatures in TLS 1.3+ using the BC light-weight API.
Implementation class for generation of the raw ECDSA signature type using the BC light-weight API.
Implementation class for the verification of the raw ECDSA signature type using the BC light-weight
API.
Implementation class for a single X.509 certificate based on the BC light-weight API.
Operator supporting the generation of RSASSA-PSS signatures using the BC light-weight API.
Operator supporting the verification of RSASSA-PSS signatures using the BC light-weight API.
Operator supporting the generation of RSASSA-PKCS1-v1_5 signatures using the BC light-weight API.
Operator supporting the verification of RSASSA-PKCS1-v1_5 signatures using the BC light-weight API.
BC light-weight support class for handling TLS secrets and deriving key material and other secrets
from them.
Support class for X25519 using the BC light-weight library.
Support class for X448 using the BC light-weight library.
A generic TLS 1.2 AEAD cipher.
Base interface for services supporting AEAD encryption/decryption.
Set the key to be used by the AEAD cipher implementation supporting this service.
array holding the AEAD cipher key.
offset into the array the key starts at.
length of the key in the array.
Initialise the parameters for the AEAD operator.
the nonce.
MAC size in bytes.
any additional data to be included in the MAC calculation.
if the parameters are inappropriate.
Return the maximum size of the output for input of inputLength bytes.
the length (in bytes) of the proposed input.
the maximum size of the output.
Perform the cipher encryption/decryption returning the output in output.
Note: we have to use DoFinal() here as it is the only way to guarantee output from the underlying cipher.
array holding input data to the cipher.
offset into input array data starts at.
length of the input data in the array.
array to hold the cipher output.
offset into output array to start saving output.
the amount of data written to output.
in case of failure.
A generic TLS 1.0-1.2 block cipher. This can be used for AES or 3DES for example.
Interface for block cipher services.
Set the key to be used by the block cipher implementation supporting this service.
array holding the block cipher key.
offset into the array the key starts at.
length of the key in the array.
Initialise the parameters for operator.
array holding the initialization vector (IV).
offset into the array the IV starts at.
length of the IV in the array.
if the parameters are inappropriate.
Perform the cipher encryption/decryption returning the output in output.
Note: we have to use DoFinal() here as it is the only way to guarantee output from the underlying cipher.
array holding input data to the cipher.
offset into input array data starts at.
length of the input data in the array.
array to hold the cipher output.
offset into output array to start saving output.
the amount of data written to output.
in case of failure.
Return the blocksize (in bytes) of the underlying block cipher.
the cipher's blocksize.
Useful utility methods.
The NULL cipher.
A generic TLS MAC implementation, acting as an HMAC based on some underlying Digest.
Generate a new instance of a TlsMac.
the TLS client context specific crypto parameters.
The MAC to use.
Base interface for a generic TLS MAC implementation for use with a bulk cipher.
Return the output length (in bytes) of this MAC.
The output length of this MAC.
Calculate the MAC for some given data.
The sequence number of the record.
The content type of the message.
A byte array containing the message.
The number of bytes to skip, before the message starts.
The length of the message.
A new byte array containing the MAC value.
Constant time calculation of the MAC for some given data with a given expected length.
The sequence number of the record.
The content type of the message.
A byte array containing the message.
The number of bytes to skip, before the message starts.
The length of the message.
The expected length of the full message.
Random data for padding out the MAC calculation if required.
A new byte array containing the MAC value.
Carrier class for SRP-6 group parameters.
Base constructor.
the n value.
the g value.
A selection of standard groups for SRP-6.
Base interface for ephemeral key agreement calculator.
Generate an ephemeral key pair, returning the encoding of the public key.
a byte encoding of the public key.
Pass in the public key for the peer to the agreement calculator.
a byte encoding of the peer public key.
Calculate the agreed secret based on the calculator's current state.
the calculated secret.
Interface providing the functional representation of a single X.509 certificate.
Return an encryptor based on the public key in this certificate.
a based on this certificate's public key.
the OID of this certificate's 'signatureAlgorithm', as a string.
true if (and only if) this certificate can be used to verify the given signature algorithm.
Base interface for a TLS bulk cipher.
Return the maximum input size for a ciphertext given a maximum output size for the plaintext of
plaintextLimit bytes.
the maximum output size for the plaintext.
the maximum input size of the ciphertext for plaintextlimit bytes of output.
Return the maximum output size for a ciphertext given an actual input plaintext size of
plaintextLength bytes and a maximum input plaintext size of plaintextLimit bytes.
the actual input size for the plaintext.
the maximum input size for the plaintext.
the maximum output size of the ciphertext for plaintextlimit bytes of input.
Return the maximum size for the plaintext given ciphertextlimit bytes of ciphertext.
the maximum number of bytes of ciphertext.
the maximum size of the plaintext for ciphertextlimit bytes of input.
Encode the passed in plaintext using the current bulk cipher.
sequence number of the message represented by plaintext.
content type of the message represented by plaintext.
used for the record.
extra bytes to allocate at start of returned byte array.
array holding input plaintext to the cipher.
offset into input array the plaintext starts at.
length of the plaintext in the array.
A containing the result of encoding (after 'headerAllocation' unused
bytes).
Decode the passed in ciphertext using the current bulk cipher.
sequence number of the message represented by ciphertext.
content type used in the record for this message.
used for the record.
array holding input ciphertext to the cipher.
offset into input array the ciphertext starts at.
length of the ciphertext in the array.
A containing the result of decoding.
Service and object creation interface for the primitive types and services that are associated with
cryptography in the API.
Return true if this TlsCrypto would use a stream verifier for any of the passed in algorithms.
This method is only relevant to handshakes negotiating (D)TLS 1.2.
A list of
values.
true if this instance would use a stream verifier for any of the passed in algorithms, otherwise
false.
Return true if this TlsCrypto would use a stream verifier for any of the passed in algorithms.
This method is only relevant to handshakes negotiating (D)TLS versions older than 1.2.
An array of values.
true if this instance would use a stream verifier for any of the passed in algorithms, otherwise
false.
Return true if this TlsCrypto can support the passed in hash algorithm.
the algorithm of interest.
true if cryptoHashAlgorithm is supported, false otherwise.
Return true if this TlsCrypto can support the passed in signature algorithm (not necessarily in
combination with EVERY hash algorithm).
the algorithm of interest.
true if cryptoSignatureAlgorithm is supported, false otherwise.
Return true if this TlsCrypto can support DH key agreement.
true if this instance can support DH key agreement, false otherwise.
Return true if this TlsCrypto can support ECDH key agreement.
true if this instance can support ECDH key agreement, false otherwise.
Return true if this TlsCrypto can support the passed in block/stream encryption algorithm.
the algorithm of interest.
true if encryptionAlgorithm is supported, false otherwise.
Return true if this TlsCrypto can support HKDF with the passed in hash algorithm.
the algorithm of interest.
true if HKDF is supported with cryptoHashAlgorithm, false otherwise.
Return true if this TlsCrypto can support the passed in MAC algorithm.
the algorithm of interest.
true if macAlgorithm is supported, false otherwise.
Return true if this TlsCrypto supports the passed in named group
value.
true if this instance supports the passed in named group value.
Return true if this TlsCrypto can support RSA encryption/decryption.
true if this instance can support RSA encryption/decryption, false otherwise.
Return true if this TlsCrypto can support the passed in signature algorithm (not necessarily in
combination with EVERY hash algorithm).
true if signatureAlgorithm is supported, false otherwise.
Return true if this TlsCrypto can support the passed in signature algorithm.
the algorithm of interest.
true if sigAndHashAlgorithm is supported, false otherwise.
Return true if this TlsCrypto can support the passed in signature scheme.
the scheme of interest.
true if signatureScheme is supported, false otherwise.
Return true if this TlsCrypto can support SRP authentication.
true if this instance can support SRP authentication, false otherwise.
Create a TlsSecret object based on provided data.
the data to base the TlsSecret on.
a TlsSecret based on the provided data.
Create a TlsSecret object containing a randomly-generated RSA PreMasterSecret
the client version to place in the first 2 bytes
a TlsSecret containing the PreMasterSecret.
Return the primary (safest) SecureRandom for this crypto.
a SecureRandom suitable for key generation.
Create a TlsCertificate from an ASN.1 binary encoding of an X.509 certificate.
DER/BER encoding of the certificate of interest.
a TlsCertificate.
if there is an issue on decoding or constructing the certificate.
Create a TlsCertificate from an ASN.1 binary encoding of a certificate.
Certificate type as per IANA TLS Certificate Types registry.
DER/BER encoding of the certificate of interest.
a TlsCertificate.
if there is an issue on decoding or constructing the certificate.
Create a cipher for the specified encryption and MAC algorithms.
See enumeration classes , for appropriate
argument values.
context specific parameters.
the encryption algorithm to be employed by the cipher.
the MAC algorithm to be employed by the cipher.
a implementing the encryption and MAC algorithms.
Create a domain object supporting the domain parameters described in dhConfig.
the config describing the DH parameters to use.
a TlsDHDomain supporting the parameters in dhConfig.
Create a domain object supporting the domain parameters described in ecConfig.
the config describing the EC parameters to use.
a TlsECDomain supporting the parameters in ecConfig.
Adopt the passed in secret, creating a new copy of it.
the secret to make a copy of.
a TlsSecret based on the original secret.
Create a suitable hash for the hash algorithm identifier passed in.
See enumeration class for appropriate argument values.
the hash algorithm the hash needs to implement.
a .
Create a suitable HMAC for the MAC algorithm identifier passed in.
See enumeration class for appropriate argument values.
the MAC algorithm the HMAC needs to match.
a .
Create a suitable HMAC using the hash algorithm identifier passed in.
See enumeration class for appropriate argument values.
the hash algorithm the HMAC should use.
a .
Create a nonce generator.
Each call should construct a new generator, and the generator should be returned from this call only after
automatically seeding from this 's entropy source, and from the provided additional
seed material. The output of each returned generator must be completely independent of the others.
context-specific seed material
a .
Create an SRP-6 client.
client config.
an initialised SRP6 client object.
Create an SRP-6 server.
server config.
the SRP6 verifier value.
an initialised SRP6 server object.
Create an SRP-6 verifier generator.
generator config.
an initialized SRP6 verifier generator.
Setup an initial "secret" for a chain of HKDF calls (RFC 5869), containing a string of HashLen
zeroes.
the hash algorithm to instantiate HMAC with. See
for values.
Basic exception class for crypto services to pass back a cause.
Carrier class for context-related parameters needed for creating secrets and ciphers.
Base constructor.
the context for this parameters object.
Basic config for Diffie-Hellman.
Domain interface to service factory for creating Diffie-Hellman operators.
Return an agreement operator suitable for ephemeral Diffie-Hellman.
a key agreement operator.
Carrier class for Elliptic Curve parameter configuration.
Return the group used.
the named group used.
Domain interface to service factory for creating Elliptic-Curve (EC) based operators.
Return an agreement operator suitable for ephemeral EC Diffie-Hellman.
a key agreement operator.
Base interface for an encryptor.
Encrypt data from the passed in input array.
byte array containing the input data.
offset into input where the data starts.
the length of the data to encrypt.
the encrypted data.
Interface for message digest, or hash, services.
Update the hash with the passed in input.
input array containing the data.
offset into the input array the input starts at.
the length of the input data.
Return calculated hash for any input passed in.
the hash value.
Return a clone of this hash object representing its current state.
a clone of the current hash.
Reset the hash underlying this service.
Interface for MAC services based on HMAC.
Return the internal block size for the message digest underlying this HMAC service.
the internal block size for the digest (in bytes).
Interface for MAC services.
Set the key to be used by the MAC implementation supporting this service.
array holding the MAC key.
offset into the array the key starts at.
length of the key in the array.
Update the MAC with the passed in input.
input array containing the data.
offset into the input array the input starts at.
the length of the input data.
Return calculated MAC for any input passed in.
the MAC value.
Write the calculated MAC to an output buffer.
output array to write the MAC to.
offset into the output array to write the MAC to.
Return the length of the MAC generated by this service.
the MAC length.
Reset the MAC underlying this service.
Generate a nonce byte[] string.
the length, in bytes, of the nonce to generate.
the nonce value.
The cipher for TLS_NULL_WITH_NULL_NULL.
Interface supporting the generation of key material and other SSL/TLS secret values from PRFs.
Calculate an HMAC with this secret's data as the key.
the hash algorithm to instantiate HMAC with. See
for values.
array containing the input data.
offset into the input array the input starts at.
the length of the input data.
Return a new secret based on applying a PRF to this one.
PRF algorithm to use.
the label details.
the seed details.
the size (in bytes) of the secret to generate.
the new secret.
Destroy the internal state of the secret.
After this call, any attempt to use the will result in an
being thrown.
Return an encrypted copy of the data this secret is based on.
the encryptor to use for protecting the internal data.
an encrypted copy of this secret's internal data.
Return the internal data from this secret.
The does not keep a copy of the data. After this call, any attempt to use the
will result in an being thrown.
the secret's internal data.
RFC 5869 HKDF-Expand function, with this secret's data as the pseudo-random key ('prk').
the hash algorithm to instantiate HMAC with. See
for values.
optional context and application specific information (can be zero-length).
length of output keying material in octets.
output keying material (of 'length' octets).
RFC 5869 HKDF-Extract function, with this secret's data as the 'salt'.
The does not keep a copy of the data. After this call, any attempt to use
the will result in an being thrown.
the hash algorithm to instantiate HMAC with. See
for values.
input keying material.
a pseudo-random key (of HashLen octets).
Base interface for a TLS signer that works on raw message digests.
Generate an encoded signature based on the passed in hash.
the signature algorithm to use.
the hash calculated for the signature.
an encoded signature.
in case of an exception processing the hash.
Basic interface for an SRP-6 client implementation.
Generates the secret S given the server's credentials
The server's credentials
Client's verification message for the server
If server's credentials are invalid
Generates client's credentials given the client's salt, identity and password
The salt used in the client's verifier.
The user's identity (eg. username)
The user's password
Client's public value to send to server
Basic interface for an SRP-6 server implementation.
Generates the server's credentials that are to be sent to the client.
The server's public value to the client
Processes the client's credentials. If valid the shared secret is generated and returned.
The client's credentials.
A shared secret .
If client's credentials are invalid.
Base interface for a generator for SRP-6 verifiers.
Creates a new SRP-6 verifier value.
The salt to use, generally should be large and random
The user's identifying information (eg. username)
The user's password
A new verifier for use in future SRP authentication
Basic config for SRP.
Return the (N, g) values used in SRP-6.
(N, g) as a BigInteger array (N=[0], g=[1]).
Set the (N, g) values used for SRP-6.
(N, g) as a BigInteger array (N=[0], g=[1]).
Base interface for a TLS verifier that works with signatures and either raw message digests, or entire
messages.
Return true if the passed in signature and hash represent a real signature.
the signature object containing the signature to be verified.
the hash calculated for the signature.
true if signature verifies, false otherwise.
in case of an exception verifying signature.
Base interface for an object sending and receiving DTLS data.
Container class for generating signatures that carries the signature type, parameters, public key
certificate and public key's associated signer object.
Accept named groups and various standard DH groups with 'P' at least
bits.
Accept named groups and various standard DH groups with 'P' at least the specified number of bits.
the minimum bitlength of 'P'.
Accept named groups and a custom set of group parameters, subject to a minimum bitlength for 'P'.
a list of acceptable s.
the minimum bitlength of 'P'.
Accept only the group parameters specified in RFC 5054 Appendix A.
Specify a custom set of acceptable group parameters.
an of acceptable .
Buffers input until the hash algorithm is determined.
a (or null before TLS 1.2).
Encode this to a .
the to encode to.
Parse a from a .
the of the current connection.
the to parse from.
a object.
Check that there are no "extra" messages left in the current inbound flight
RFC 4347 4.1.2.5 Anti-replay
Support fast rejection of duplicate records by maintaining a sliding receive window
Check whether a received record with the given sequence number should be rejected as a duplicate.
the 48-bit DTLSPlainText.sequence_number field of a received record.
true if the record should be discarded without further processing.
Report that a received record with the given sequence number passed authentication checks.
the 48-bit DTLSPlainText.sequence_number field of an authenticated record.
RFC 4492 5.4
Indicates the elliptic curve domain parameters are conveyed verbosely, and the
underlying finite field is a prime field.
Indicates the elliptic curve domain parameters are conveyed verbosely, and the
underlying finite field is a characteristic-2 field.
Indicates that a named curve is used. This option SHOULD be used when applicable.
RFC 4492 5.1.2
RFC 2246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
RFC 5705
RFC 5246 7.4.1.4.1
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 6520 3.
RFC 6066
RFC 2246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 8446 4.6.3
RFC 2246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
RFC 7919
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 3546 3.6
an of , specifying the list of
trusted OCSP responders. An empty list has the special meaning that the responders are implicitly known to
the server - e.g., by prior arrangement.
OCSP request extensions. A null value means that there are no extensions.
an of .
OCSP request extensions.
Encode this to a .
the to encode to.
Parse an from a .
the to parse from.
an object.
RFC 5246
Note that the values here are implementation-specific and arbitrary. It is recommended not to depend on the
particular values (e.g. serialization).
RFC 7301 Represents a protocol name for use with ALPN.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
An implementation of the TLS 1.0/1.1/1.2 record layer.
Encode this to a .
the of the current connection.
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 6066 3. Server Name Indication
Current implementation uses this guidance: "For backward compatibility, all future data structures associated
with new NameTypes MUST begin with a 16-bit length field. TLS MAY treat provided server names as opaque data
and pass the names and types to the application.". RFC 6066 specifies ASCII encoding for host_name (possibly
using A-labels for IDNs), but note that the previous version (RFC 4366) specified UTF-8 encoding (see RFC 6066
Appendix A). For maximum compatibility, it is recommended that client code tolerate receiving UTF-8 from the
peer, but only generate ASCII itself.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
an of .
an of .
Encode this to a .
the to encode to .
Parse a from a .
the to parse from.
a object.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 5246 7.4.1.4.1 (in RFC 2246, there were no specific values assigned)
RFC 5246 7.4.1.4.1
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
For TLS 1.3+ usage, some signature schemes are constrained to use a particular
({@link NamedGroup}. Not relevant for TLS 1.2 and below.
An implementation of that simulates the existence of "unknown"
identities to obscure the fact that there is no verifier for them.
Create a that implements the algorithm from RFC 5054
2.5.1.3.
the defining the group that SRP is operating in.
the secret "seed key" referred to in RFC 5054 2.5.1.3.
an instance of .
RFC 4680
Base interface to provide TLS authentication credentials.
Called by the protocol handler to report the server certificate.
Note: this method is responsible for certificate verification and validation.
the server certificate received.
Return client credentials in response to server's certificate request.
The returned value may be null, or else it MUST implement exactly one of
, , or
, depending on the key exchange that was negotiated and the details of
the .
details of the certificate request.
a object or null for no client authentication.
Return the session this client wants to resume, if any.
Note that the peer's certificate chain for the session (if any) may need to be periodically revalidated.
A representing the resumable session to be used for this connection, or
null to use a new session.
Return the external PSKs to offer in the ClientHello.
This will only be called when TLS 1.3 or higher is amongst the offered protocol versions.
an of instances, or null if none should be
offered.
(Int32 -> byte[])
If this client is offering TLS 1.3 or higher, this method may be called to determine for which
groups a key share should be included in the initial ClientHello.
Groups that were not included in the supported_groups extension (by will
be ignored. The protocol will then add a suitable key_share extension to the ClientHello extensions.
an of named group values, possibly empty or
null.
Notifies the client of the session that will be offered in ClientHello for resumption, if any.
This will be either the session returned from {@link #getSessionToResume()} or null if that session was
unusable. NOTE: the actual negotiated session_id is notified by .
The representing the resumable session to be offered for
this connection, or null if there is none.
Notifies the client of the session_id sent in the ServerHello.
The protocol implementation validates that any server extensions received correspond to client
extensions sent.
If further processing of the server extensions is needed, it can be done in this callback. NOTE: This is
not called for session resumption handshakes.
(Int32 -> byte[])
(SupplementalDataEntry)
(SupplementalDataEntry)
RFC 5077 3.3. NewSessionTicket Handshake Message
This method will be called (only) when a NewSessionTicket handshake message is received. The ticket is
opaque to the client and clients MUST NOT examine the ticket under the assumption that it complies with e.g.
RFC 5077 4. "Recommended Ticket Construction".
The ticket.
Marker interface to distinguish a TLS client context.
Constructor for non-blocking mode.
When data is received, use to provide the received ciphertext,
then use to read the corresponding cleartext.
Similarly, when data needs to be sent, use
to provide the cleartext, then use to get the
corresponding ciphertext.
Constructor for blocking mode.
The of data to/from the server.
Constructor for blocking mode.
The of data from the server.
The of data to the server.
Initiates a TLS handshake in the role of client.
In blocking mode, this will not return until the handshake is complete. In non-blocking mode, use
to receive a callback when the handshake is complete.
The to use for the handshake.
If in blocking mode and handshake was not successful.
Base interface for a TLS context implementation.
Return true if this context is for a server, false otherwise.
true for a server based context, false for a client based one.
Used to get the resumable session, if any, used by this connection.
Only available after the handshake has successfully completed.
A representing the resumable session used by this connection, or null if
no resumable session available.
Used to get the session information for this connection.
Only available after the handshake has successfully completed. Use
to find out if the session is resumable.
A representing the session used by this connection.
Export the value of the specified channel binding.
Only available after the handshake has successfully completed.
A constant specifying the channel binding to
export.
A copy of the channel binding data as a byte[], or null if the binding could not be
determined.
Export (early data) keying material according to RFC 5705: "Keying Material Exporters for TLS", as
updated for TLS 1.3 (RFC 8446).
NOTE: for use in settings where an exporter is needed for 0-RTT data.
indicates which application will use the exported keys.
allows the application using the exporter to mix its own data with the TLS PRF
for the exporter output.
the number of bytes to generate.
a pseudorandom bit string of 'length' bytes generated from the (exporter_)master_secret.
Export keying material according to RFC 5705: "Keying Material Exporters for TLS", as updated for
TLS 1.3 (RFC 8446) when negotiated.
indicates which application will use the exported keys.
allows the application using the exporter to mix its own data with the TLS PRF
for the exporter output.
the number of bytes to generate.
a pseudorandom bit string of 'length' bytes generated from the (exporter_)master_secret.
Support interface for generating a secret based on the credentials sent by a TLS peer.
Calculate an agreed secret based on our credentials and the public key credentials of our peer.
public key certificate of our TLS peer.
the agreed secret.
in case of an exception on generation of the secret.
Base interface for a class that decrypts TLS secrets.
Decrypt the passed in cipher text using the parameters available.
the parameters to use for the decryption.
the cipher text containing the secret.
a TLS secret.
on a parsing or decryption error.
Support interface for generating a signature based on our private credentials.
Generate a signature against the passed in hash.
a message digest calculated across the message the signature is to apply to.
an encoded signature.
if the hash cannot be processed, or there is an issue with the private
credentials.
Return the algorithm IDs for the signature algorithm and the associated hash it uses.
the full algorithm details for the signature.
Base interface for interfaces/classes carrying TLS credentials.
Return the certificate structure representing our identity.
our certificate structure.
(D)TLS DH_anon key exchange.
Interface for verifying explicit Diffie-Hellman group parameters.
Check whether the given DH group is acceptable for use.
the to check.
true if (and only if) the specified group is acceptable.
(D)TLS DH key exchange.
(D)TLS ECDH_anon key exchange (see RFC 4492).
(D)TLS ECDHE key exchange (see RFC 4492).
(D)TLS ECDH key exchange (see RFC 4492).
(Int32 -> byte[])
an of .
an of .
an of .
an of .
Base interface for an object that can calculate a handshake hash.
A generic interface for key exchange implementations in (D)TLS.
Interface for a key exchange factory offering a variety of specific algorithms.
This exception will be thrown (only) when the connection is closed by the peer without sending a
close_notify warning alert.
If this happens, the TLS protocol cannot rule out truncation of the connection data (potentially
malicious). It may be possible to check for truncation via some property of a higher level protocol
built upon TLS, e.g.the Content-Length header for HTTPS.
Object Identifiers associated with TLS extensions.
RFC 7633
Base interface for a (D)TLS endpoint.
Notifies the peer that a new handshake is about to begin.
Specify the timeout, in milliseconds, to use for the complete handshake process.
NOTE: Currently only respected by DTLS protocols. Negative values are not allowed. A timeout of zero means
an infinite timeout (i.e.the handshake will never time out).
the handshake timeout, in milliseconds.
This option is provided as a last resort for interoperability with TLS peers that fail to correctly send a
close_notify alert at end of stream. Implementations SHOULD return true; caution is advised if returning
false without a full understanding of the implications.
This implementation supports RFC 7627 and will always negotiate the extended_master_secret
extension where possible. When connecting to a peer that does not offer/accept this extension, it is
recommended to abort the handshake.This option is provided for interoperability with legacy peers, although
some TLS features will be disabled in that case (see RFC 7627 5.4).
true if the handshake should be aborted when the peer does not negotiate the
extended_master_secret extension, or false to support legacy interoperability.
See RFC 5246 6.2.3.2. Controls whether block cipher encryption may randomly add extra padding
beyond the minimum.
Note that in configurations where this is known to be potential security risk this setting will be ignored
(and extended padding disabled). Extra padding is always supported when decrypting received records.
true if random extra padding should be added during block cipher encryption, or
false to always use the minimum amount of required padding.
draft-mathewson-no-gmtunixtime-00 2. "If existing users of a TLS implementation may rely on
gmt_unix_time containing the current time, we recommend that implementors MAY provide the ability to set
gmt_unix_time as an option only, off by default.".
NOTE: For a server that has negotiated TLS 1.3 (or later), or a client that has offered TLS 1.3 (or later),
this is not called and gmt_unix_time is not used.
true if the current time should be used in the gmt_unix_time field of Random, or
false if gmt_unix_time should contain a cryptographically random value.
RFC 5746 3.4/3.6. In case this is false, peers may want to terminate the handshake instead of
continuing; see Section 4.1/4.3 for discussion.
NOTE: TLS 1.3 forbids renegotiation, so this is never called when TLS 1.3 (or later) was negotiated.
This method will be called when an alert is raised by the protocol.
A human-readable message explaining what caused this alert. May be null.
The that caused this alert to be raised. May be null.
This method will be called when an alert is received from the remote peer.
Notifies the peer that the handshake has been successfully completed.
Return a instance that will control the generation of heartbeats
locally (if permitted by the remote peer), or null to not generate heartbeats. Heartbeats are described in
RFC 6520.
an instance of .
Return the heartbeat mode applicable to the remote peer. Heartbeats are described in RFC 6520.
See enumeration class for appropriate return values.
the value.
Indicates whether a DTLS connection should ignore corrupt records (bad_record_mac) instead of
failing the connection.
Called only once at the start of a connection and applies throughout.
The value true to ignore corrupt DTLS records, or false to fail the connection.
This method is called, when a change cipher spec message is received.
If the message has an invalid content or the handshake is not in the correct
state.
Read data from the network.
The method will return immediately, if there is still some data left in the buffer, or block until some
application data has been read from the network.
The buffer where the data will be copied to.
The position where the data will be placed in the buffer.
The maximum number of bytes to read.
The number of bytes read.
If something goes wrong during reading data.
Write some application data.
Fragmentation is handled internally. Usable in both blocking/non-blocking modes.
In blocking mode, the output will be automatically sent via the underlying transport. In non-blocking mode,
call to get the output bytes to send to the peer.
This method must not be called until after the initial handshake is complete. Attempting to call it earlier
will result in an .
The buffer containing application data to send.
The offset at which the application data begins
The number of bytes of application data.
If called before the initial handshake has completed.
If connection is already closed, or for encryption or transport errors.
The secure bidirectional stream for this connection
Only allowed in blocking mode.
Should be called in non-blocking mode when the input data reaches EOF.
Equivalent to OfferInput(input, 0, input.Length)
.
The input buffer to offer.
Offer input from an arbitrary source.
Only allowed in non-blocking mode.
This method will decrypt and process all records that are fully available. If only part of a record is
available, the buffer will be retained until the remainder of the record is offered.
If any records containing application data were processed, the decrypted data can be obtained using
. If any records containing protocol data were processed, a
response may have been generated. You should always check to see if there is any available output after
calling this method by calling .
The input buffer to offer.
The offset within the input buffer that input begins.
The number of bytes of input being offered.
If an error occurs while decrypting or processing a record.
Gets the amount of received application data.
A call to is guaranteed to be able to return at least
this much data.
Only allowed in non-blocking mode.
The number of bytes of available application data.
Retrieves received application data.
Use to check how much application data is currently available. This
method functions similarly to , except that it never blocks. If
no data is available, nothing will be copied and zero will be returned.
Only allowed in non-blocking mode.
The buffer to hold the application data.
The start offset in the buffer at which the data is written.
The maximum number of bytes to read.
The total number of bytes copied to the buffer. May be less than the length specified if the
length was greater than the amount of available data.
Gets the amount of encrypted data available to be sent.
A call to is guaranteed to be able to return at least this much
data. Only allowed in non-blocking mode.
The number of bytes of available encrypted data.
Retrieves encrypted data to be sent.
Use to check how much encrypted data is currently available. This
method functions similarly to , except that it never blocks. If
no data is available, nothing will be copied and zero will be returned. Only allowed in non-blocking mode.
The buffer to hold the encrypted data.
The start offset in the buffer at which the data is written.
The maximum number of bytes to read.
The total number of bytes copied to the buffer. May be less than the length specified if the
length was greater than the amount of available data.
Make sure the 'buf' is now empty. Fail otherwise.
The to check.
Processor interface for a PSK identity.
Base interface for an object that can process a PSK identity.
(D)TLS PSK key exchange (RFC 4279).
(D)TLS RSA key exchange.
Interface describing a TLS server endpoint.
Return the specified session, if available.
Note that the peer's certificate chain for the session (if any) may need to be periodically revalidated.
the ID of the session to resume.
A with the specified session ID, or null.
Return the external PSK to select from the ClientHello.
WARNING: EXPERIMENTAL FEATURE, UNSTABLE API
Note that this will only be called when TLS 1.3 or higher is amongst the offered protocol versions, and one
or more PSKs are actually offered.
an of instances.
The corresponding to the selected identity, or null to not select
any.
(Int32 -> byte[])
(Int32 -> byte[])
(Int32 -> byte[])
(SupplementalDataEntry)
Return server credentials to use.
The returned value may be null, or else it MUST implement exactly one of
, , or
, depending on the key exchange that was negotiated.
a object or null for anonymous key exchanges.
This method will be called (only) if the server included an extension of type "status_request" with empty
"extension_data" in the extended server hello. See RFC 3546 3.6. Certificate Status Request. If a
non-null is returned, it is sent to the client as a handshake message of
type "certificate_status".
A to be sent to the client (or null for none).
(SupplementalDataEntry)
Called by the protocol handler to report the client certificate, only if
returned non-null.
Note: this method is responsible for certificate verification and validation.
the effective client certificate (may be an empty chain).
RFC 5077 3.3. NewSessionTicket Handshake Message.
This method will be called (only) if a NewSessionTicket extension was sent by the server. See RFC 5077
4. Recommended Ticket Construction for recommended format and protection.
The ticket.
Server certificate carrier interface.
Marker interface to distinguish a TLS server context.
Constructor for non-blocking mode.
When data is received, use to provide the received ciphertext,
then use to read the corresponding cleartext.
Similarly, when data needs to be sent, use
to provide the cleartext, then use to get the
corresponding ciphertext.
Constructor for blocking mode.
The of data to/from the server.
Constructor for blocking mode.
The of data from the server.
The of data to the server.
Receives a TLS handshake in the role of server.
In blocking mode, this will not return until the handshake is complete. In non-blocking mode, use
to receive a callback when the handshake is complete.
The to use for the handshake.
If in blocking mode and handshake was not successful.
Base interface for a carrier object for a TLS session.
Interface for verifying SRP config needs to conform to.
Check whether the given SRP configuration is acceptable for use.
the to check.
true if (and only if) the specified configuration is acceptable.
Processor interface for an SRP identity.
Base interface for an object that can return login parameters from an SRP identity.
Lookup the corresponding to the specified identity.
NOTE: To avoid "identity probing", unknown identities SHOULD be handled as recommended in RFC 5054 2.5.1.3.
is provided for this purpose.
the SRP identity sent by the connecting client.
the for the specified identity, or else 'simulated' parameters
if the identity is not recognized. A null value is also allowed, but not recommended.
(D)TLS SRP key exchange (RFC 5054).
RFC 5764 DTLS Extension to Establish Keys for SRTP.
Whether a server can select the specified cipher suite given the available signature algorithms
for ServerKeyExchange.
Check the signature algorithm for certificates in the peer's CertPath as specified in RFC 5246
7.4.2, 7.4.4, 7.4.6 and similar rules for earlier TLS versions.
The supplied CertPath should include the trust anchor (its signature algorithm isn't checked, but in the
general case checking a certificate requires the issuer certificate).
if any certificate in the CertPath (excepting the trust anchor) has a
signature algorithm that is not one of the locally supported signature algorithms.
Generate a pre_master_secret and send it encrypted to the server.
Encode this to a .
the to encode to.
Parse a from a .
the to parse from.
a object.
RFC 6066 5.
Encode this to a .
the to encode to.
Parse a from a .
the of the current connection.
the to parse from.
a object.
RFC 4681
RFC 5764 4.1.1
see for valid constants.
valid lengths from 0 to 255.
see for valid constants.
valid lengths from 0 to 255.
Base class for an RFC 3161 Time Stamp Request.
Create a TimeStampRequest from the past in byte array.
@param req byte array containing the request.
@throws IOException if the request is malformed.
Create a TimeStampRequest from the past in input stream.
@param in input stream containing the request.
@throws IOException if the request is malformed.
Validate the timestamp request, checking the digest to see if it is of an
accepted type and whether it is of the correct length for the algorithm specified.
@param algorithms a set of string OIDS giving accepted algorithms.
@param policies if non-null a set of policies we are willing to sign under.
@param extensions if non-null a set of extensions we are willing to accept.
@throws TspException if the request is invalid, or processing fails.
return the ASN.1 encoded representation of this object.
Generator for RFC 3161 Time Stamp Request objects.
add a given extension field for the standard extensions tag (tag 3)
@throws IOException
add a given extension field for the standard extensions tag
The value parameter becomes the contents of the octet string associated
with the extension.
Base class for an RFC 3161 Time Stamp Response object.
Create a TimeStampResponse from a byte array containing an ASN.1 encoding.
@param resp the byte array containing the encoded response.
@throws TspException if the response is malformed.
@throws IOException if the byte array doesn't represent an ASN.1 encoding.
Create a TimeStampResponse from an input stream containing an ASN.1 encoding.
@param input the input stream containing the encoded response.
@throws TspException if the response is malformed.
@throws IOException if the stream doesn't represent an ASN.1 encoding.
Check this response against to see if it a well formed response for
the passed in request. Validation will include checking the time stamp
token if the response status is GRANTED or GRANTED_WITH_MODS.
@param request the request to be checked against
@throws TspException if the request can not match this response.
return the ASN.1 encoded representation of this object.
Generator for RFC 3161 Time Stamp Responses.
Return an appropriate TimeStampResponse.
If genTime is null a timeNotAvailable error response will be returned.
@param request the request this response is for.
@param serialNumber serial number for the response token.
@param genTime generation time for the response token.
@param provider provider to use for signature calculation.
@return
@throws NoSuchAlgorithmException
@throws NoSuchProviderException
@throws TSPException
Generate a TimeStampResponse with chosen status and FailInfoField.
@param status the PKIStatus to set.
@param failInfoField the FailInfoField to set.
@param statusString an optional string describing the failure.
@return a TimeStampResponse with a failInfoField and optional statusString
@throws TSPException in case the response could not be created
Validate the time stamp token.
To be valid the token must be signed by the passed in certificate and
the certificate must be the one referred to by the SigningCertificate
attribute included in the hashed attributes of the token. The
certificate must also have the ExtendedKeyUsageExtension with only
KeyPurposeID.IdKPTimeStamping and have been valid at the time the
timestamp was created.
A successful call to validate means all the above are true.
Return the underlying CmsSignedData object.
@return the underlying CMS structure.
Return a ASN.1 encoded byte stream representing the encoded object.
@throws IOException if encoding fails.
return the ASN.1 encoded representation of this object using the specified encoding.
@param encoding the ASN.1 encoding format to use ("BER" or "DER").
basic creation - only the default attributes will be included here.
create with a signer with extra signed/unsigned attributes.
@return the nonce value, null if there isn't one.
Recognised hash algorithms for the time stamp protocol.
Fetches the signature time-stamp attributes from a SignerInformation object.
Checks that the MessageImprint for each time-stamp matches the signature field.
(see RFC 3161 Appendix A).
@param signerInfo a SignerInformation to search for time-stamps
@return a collection of TimeStampToken objects
@throws TSPValidationException
Validate the passed in certificate as being of the correct type to be used
for time stamping. To be valid it must have an ExtendedKeyUsage extension
which has a key purpose identifier of id-kp-timeStamping.
@param cert the certificate of interest.
@throws TspValidationException if the certicate fails on one of the check points.
Return the digest algorithm using one of the standard JCA string
representations rather than the algorithm identifier (if possible).
Exception thrown if a TSP request or response fails to validate.
If a failure code is associated with the exception it can be retrieved using
the getFailureCode() method.
The failure code associated with this exception, if one is set.
General array utilities.
Are two arrays equal.
Left side.
Right side.
True if equal.
A constant time equals comparison - does not terminate early if
test will fail.
first array
second array
true if arrays equal, false otherwise.
Make a copy of a range of bytes from the passed in data array. The range can
extend beyond the end of the input array, in which case the return array will
be padded with zeroes.
@param data the array from which the data is to be copied.
@param from the start index at which the copying should take place.
@param to the final index of the range (exclusive).
@return a new byte array containing the range given.
BigInteger utilities.
Return the passed in value as an unsigned byte array.
@param value the value to be converted.
@return a byte array without a leading zero byte if present in the signed encoding.
Return the passed in value as an unsigned byte array of the specified length, padded with
leading zeros as necessary.
@param length the fixed length of the result.
@param n the value to be converted.
@return a byte array padded to a fixed length with leading zeros.
Write the passed in value as unsigned bytes to the specified buffer range, padded with
leading zeros as necessary.
@param n
the value to be converted.
@param buf
the buffer to which the value is written.
@param off
the start offset in array buf
at which the data is written.
@param len
the fixed length of data written (possibly padded with leading zeros).
Creates a Random BigInteger from the secure random of a given bit length.
Return a random BigInteger not less than 'min' and not greater than 'max'
@param min the least value that may be generated
@param max the greatest value that may be generated
@param random the source of randomness
@return a random BigInteger value in the range [min,max]
Base class for both the compress and decompress classes.
Holds common arrays, and static data.
@author Keiron Liddle
An input stream that decompresses from the BZip2 format (with the file
header chars) to be read as any other stream.
@author Keiron Liddle
NB: note this class has been modified to read the leading BZ from the
start of the BZIP2 stream to make it compatible with other PGP programs.
An output stream that compresses into the BZip2 format (with the file
header chars) into another stream.
@author Keiron Liddle
TODO: Update to BZip2 1.0.1
NB: note this class has been modified to add a leading BZ to the
start of the BZIP2 stream to make it compatible with other PGP programs.
modified by Oliver Merkel, 010128
A simple class the hold and calculate the CRC for sanity checking
of the data.
@author Keiron Liddle
Interface for matching objects in an .
The contravariant type of selectable objects.
Match the passed in object, returning true if it would be selected by this selector, false
otherwise.
The object to be matched.
true
if the objects is matched by this selector, false otherwise.
A generic interface describing a simple store of objects.
The covariant type of stored objects.
Enumerate the (possibly empty) collection of objects matched by the given selector.
The used to select matching objects.
An of the matching objects.
Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
The DateTime value will be converted to UTC (using before
conversion.
A DateTime value not before the epoch.
Number of whole milliseconds after epoch.
'dateTime' is before the epoch.
Create a UTC DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
Number of milliseconds since the epoch.
A UTC DateTime value
'unixMs' is before 'MinUnixMs' or after 'MaxUnixMs'.
Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
encode the input data producing a base 64 encoded byte array.
@return a byte array containing the base 64 encoded data.
encode the input data producing a base 64 encoded byte array.
@return a byte array containing the base 64 encoded data.
Encode the byte data to base 64 writing it to the given output stream.
@return the number of bytes produced.
Encode the byte data to base 64 writing it to the given output stream.
@return the number of bytes produced.
decode the base 64 encoded input data. It is assumed the input data is valid.
@return a byte array representing the decoded data.
decode the base 64 encoded string data - whitespace will be ignored.
@return a byte array representing the decoded data.
decode the base 64 encoded string data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
encode the input data producing a base 64 output stream.
@return the number of bytes produced.
decode the base 64 encoded byte data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
decode the base 64 encoded string data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
A buffering class to allow translation from one format to another to
be done in discrete chunks.
Create a buffered Decoder.
The translater to use.
The size of the buffer.
Process one byte of data.
Data in.
Byte array for the output.
The offset in the output byte array to start writing from.
The amount of output bytes.
Process data from a byte array.
The input data.
Start position within input data array.
Amount of data to process from input data array.
Array to store output.
Position in output array to start writing from.
The amount of output bytes.
A class that allows encoding of data using a specific encoder to be processed in chunks.
Create.
The translator to use.
Size of the chunks.
Process one byte of data.
The byte.
An array to store output in.
Offset within output array to start writing from.
Process data from a byte array.
Input data Byte array containing data to be processed.
Start position within input data array.
Amount of input data to be processed.
Output data array.
Offset within output data array to start writing to.
The amount of data written.
Class to decode and encode Hex.
encode the input data producing a Hex encoded byte array.
@return a byte array containing the Hex encoded data.
encode the input data producing a Hex encoded byte array.
@return a byte array containing the Hex encoded data.
Hex encode the byte data writing it to the given output stream.
@return the number of bytes produced.
Hex encode the byte data writing it to the given output stream.
@return the number of bytes produced.
decode the Hex encoded input data. It is assumed the input data is valid.
@return a byte array representing the decoded data.
decode the Hex encoded string data - whitespace will be ignored.
@return a byte array representing the decoded data.
decode the Hex encoded string data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be
considered an error.
@return a byte array representing the decoded data.
Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be
considered an error.
@return a byte array representing the decoded data.
encode the input data producing a Hex output stream.
@return the number of bytes produced.
decode the Hex encoded byte data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
decode the Hex encoded string data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
A hex translator.
Return encoded block size.
2
Encode some data.
Input data array.
Start position within input data array.
The amount of data to process.
The output data array.
The offset within the output data array to start writing from.
Amount of data encoded.
Returns the decoded block size.
1
Decode data from a byte array.
The input data array.
Start position within input data array.
The amounty of data to process.
The output data array.
The position within the output data array to start writing from.
The amount of data written.
Encode and decode byte arrays (typically from binary to 7-bit ASCII
encodings).
Translator interface.
Convert binary data to and from UrlBase64 encoding. This is identical to
Base64 encoding, except that the padding character is "." and the other
non-alphanumeric characters are "-" and "_" instead of "+" and "/".
The purpose of UrlBase64 encoding is to provide a compact encoding of binary
data that is safe for use as an URL parameter. Base64 encoding does not
produce encoded values that are safe for use in URLs, since "/" can be
interpreted as a path delimiter; "+" is the encoded form of a space; and
"=" is used to separate a name from the corresponding value in an URL
parameter.
Encode the input data producing a URL safe base 64 encoded byte array.
@return a byte array containing the URL safe base 64 encoded data.
Encode the byte data writing it to the given output stream.
@return the number of bytes produced.
Decode the URL safe base 64 encoded input data - white space will be ignored.
@return a byte array representing the decoded data.
decode the URL safe base 64 encoded byte data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
decode the URL safe base 64 encoded string data - whitespace will be ignored.
@return a byte array representing the decoded data.
Decode the URL safe base 64 encoded string data writing it to the given output stream,
whitespace characters will be ignored.
@return the number of bytes produced.
Convert binary data to and from UrlBase64 encoding. This is identical to
Base64 encoding, except that the padding character is "." and the other
non-alphanumeric characters are "-" and "_" instead of "+" and "/".
The purpose of UrlBase64 encoding is to provide a compact encoding of binary
data that is safe for use as an URL parameter. Base64 encoding does not
produce encoded values that are safe for use in URLs, since "/" can be
interpreted as a path delimiter; "+" is the encoded form of a space; and
"=" is used to separate a name from the corresponding value in an URL
parameter.
Return a byte array representing the implementing object.
An encoding of this object as a byte array.
Produce a copy of this object with its configuration and in its current state.
The returned object may be used simply to store the state, or may be used as a similar object
starting from the copied state.
Restore a copied object state into this object.
Implementations of this method should try to avoid or minimise memory allocation to perform the reset.
an object originally {@link #copy() copied} from an object of the same type as this instance.
if the provided object is not of the correct type.
if the other parameter is in some other way invalid.
A
A
An
A
Seek ':" up to the limit.
Consume the dashes
Skip white space leave char in stream.
Read forward consuming the expected string.
expected string
false if not consumed
Consume until dash.
true if stream end not met
A generic PEM writer, based on RFC 1421
Base constructor.
@param out output stream to use.
Return the number of bytes or characters required to contain the
passed in object if it is PEM encoded.
@param obj pem object to be output
@return an estimate of the number of bytes
Write the full contents of inStr to the destination stream outStr.
Source stream.
Destination stream.
In case of IO failure.
Write the full contents of inStr to the destination stream outStr.
Source stream.
Destination stream.
The size of temporary buffer to use.
In case of IO failure.
Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater
than limit bytes in inStr.
A
A
A
The number of bytes actually transferred, if not greater than limit
Exception to be thrown on a failure to reset an object implementing Memoable.
The exception extends InvalidCastException to enable users to have a single handling case,
only introducing specific handling of this one if required.
Validate the given IPv4 or IPv6 address.
@param address the IP address as a string.
@return true if a valid address, false otherwise
Validate the given IPv4 or IPv6 address and netmask.
@param address the IP address as a string.
@return true if a valid address with netmask, false otherwise
Validate the given IPv4 address.
@param address the IP address as a string.
@return true if a valid IPv4 address, false otherwise
Validate the given IPv6 address.
@param address the IP address as a string.
@return true if a valid IPv4 address, false otherwise
General string utilities.
The Holder object.
Holder ::= SEQUENCE {
baseCertificateID [0] IssuerSerial OPTIONAL,
-- the issuer and serial number of
-- the holder's Public Key Certificate
entityName [1] GeneralNames OPTIONAL,
-- the name of the claimant or role
objectDigestInfo [2] ObjectDigestInfo OPTIONAL
-- used to directly authenticate the holder,
-- for example, an executable
}
Constructs a holder for v2 attribute certificates with a hash value for
some type of object.
digestedObjectType
can be one of the following:
- 0 - publicKey - A hash of the public key of the holder must be
passed.
- 1 - publicKeyCert - A hash of the public key certificate of the
holder must be passed.
- 2 - otherObjectDigest - A hash of some other object type must be
passed.
otherObjectTypeID
must not be empty.
This cannot be used if a v1 attribute certificate is used.
@param digestedObjectType The digest object type.
@param digestAlgorithm The algorithm identifier for the hash.
@param otherObjectTypeID The object type ID if
digestedObjectType
is
otherObjectDigest
.
@param objectDigest The hash value.
Returns the digest object type if an object digest info is used.
- 0 - publicKey - A hash of the public key of the holder must be
passed.
- 1 - publicKeyCert - A hash of the public key certificate of the
holder must be passed.
- 2 - otherObjectDigest - A hash of some other object type must be
passed.
otherObjectTypeID
must not be empty.
@return The digest object type or -1 if no object digest info is set.
Returns the other object type ID if an object digest info is used.
@return The other object type ID or null
if no object
digest info is set.
Returns the hash if an object digest info is used.
@return The hash or null
if no object digest info is set.
Returns the digest algorithm ID if an object digest info is used.
@return The digest algorithm ID or null
if no object
digest info is set.
Return any principal objects inside the attribute certificate holder entity names field.
@return an array of IPrincipal objects (usually X509Name), null if no entity names field is set.
Return the principals associated with the issuer attached to this holder
@return an array of principals, null if no BaseCertificateID is set.
Return the serial number associated with the issuer attached to this holder.
@return the certificate serial number, null if no BaseCertificateID is set.
Carrying class for an attribute certificate issuer.
Set the issuer directly with the ASN.1 structure.
@param issuer The issuer
Return any principal objects inside the attribute certificate issuer object.
An array of IPrincipal objects (usually X509Principal).
A high level authority key identifier.
Constructor which will take the byte[] returned from getExtensionValue()
@param encodedValue a DER octet encoded string with the extension structure in it.
@throws IOException on parsing errors.
Create an AuthorityKeyIdentifier using the passed in certificate's public
key, issuer and serial number.
@param certificate the certificate providing the information.
@throws CertificateParsingException if there is a problem processing the certificate
Create an AuthorityKeyIdentifier using just the hash of the
public key.
@param pubKey the key to generate the hash from.
@throws InvalidKeyException if there is a problem using the key.
A high level subject key identifier.
Constructor which will take the byte[] returned from getExtensionValue()
@param encodedValue a DER octet encoded string with the extension structure in it.
@throws IOException on parsing errors.
Extract the value of the given extension, if it exists.
The extensions object.
The object identifier to obtain.
Asn1Object
if the extension cannot be read.
Get all critical extension values, by oid
IDictionary with string (OID) keys and Asn1OctetString values
Get all non-critical extension values, by oid
IDictionary with string (OID) keys and Asn1OctetString values
A utility class that will extract X509Principal objects from X.509 certificates.
Use this in preference to trying to recreate a principal from a string, not all
DNs are what they should be, so it's best to leave them encoded where they
can be.
Return the issuer of the given cert as an X509Principal.
Return the subject of the given cert as an X509Principal.
Return the issuer of the given CRL as an X509Principal.
This class is an Selector
like implementation to select
attribute certificates from a given set of criteria.
@see org.bouncycastle.x509.X509AttributeCertificate
@see org.bouncycastle.x509.X509Store
Decides if the given attribute certificate should be selected.
The attribute certificate to be checked.
true
if the object matches this selector.
The attribute certificate which must be matched.
If null is given, any will do.
The criteria for validity
If null is given any will do.
The holder.
If null is given any will do.
The issuer.
If null is given any will do.
The serial number.
If null is given any will do.
Adds a target name criterion for the attribute certificate to the target
information extension criteria. The X509AttributeCertificate
must contain at least one of the specified target names.
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.
@param name The name as a GeneralName (not null
)
Adds a target name criterion for the attribute certificate to the target
information extension criteria. The X509AttributeCertificate
must contain at least one of the specified target names.
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.
@param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName
@throws IOException if a parsing error occurs.
Adds a collection with target names criteria. If null
is
given any will do.
The collection consists of either GeneralName objects or byte[] arrays representing
DER encoded GeneralName structures.
@param names A collection of target names.
@throws IOException if a parsing error occurs.
@see #AddTargetName(byte[])
@see #AddTargetName(GeneralName)
Gets the target names. The collection consists of List
s
made up of an Integer
in the first entry and a DER encoded
byte array or a String
in the second entry.
The returned collection is immutable.
@return The collection of target names
@see #setTargetNames(Collection)
Adds a target group criterion for the attribute certificate to the target
information extension criteria. The X509AttributeCertificate
must contain at least one of the specified target groups.
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.
@param group The group as GeneralName form (not null
)
Adds a target group criterion for the attribute certificate to the target
information extension criteria. The X509AttributeCertificate
must contain at least one of the specified target groups.
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.
@param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName
@throws IOException if a parsing error occurs.
Adds a collection with target groups criteria. If null
is
given any will do.
The collection consists of GeneralName
objects or byte[]
representing DER encoded GeneralNames.
@param names A collection of target groups.
@throws IOException if a parsing error occurs.
@see #AddTargetGroup(byte[])
@see #AddTargetGroup(GeneralName)
Gets the target groups. The collection consists of List
s
made up of an Integer
in the first entry and a DER encoded
byte array or a String
in the second entry.
The returned collection is immutable.
@return The collection of target groups.
@see #setTargetGroups(Collection)
This class is an IX509Selector
implementation to select
certificate pairs, which are e.g. used for cross certificates. The set of
criteria is given from two X509CertStoreSelector
objects,
each of which, if present, must match the respective component of a pair.
The certificate pair which is used for testing on equality.
The certificate selector for the forward part.
The certificate selector for the reverse part.
Decides if the given certificate pair should be selected. If
obj is not a X509CertificatePair
, this method
returns false
.
The X509CertificatePair
to be tested.
true
if the object matches this selector.
An ISet
of DerObjectIdentifier
objects.
An ICollection
of X509Name
objects
The attribute certificate being checked. This is not a criterion.
Rather, it is optional information that may help a {@link X509Store} find
CRLs that would be relevant when checking revocation for the specified
attribute certificate. If null
is specified, then no such
optional information is provided.
@param attrCert the IX509AttributeCertificate
being checked (or
null
)
@see #getAttrCertificateChecking()
If true
only complete CRLs are returned. Defaults to
false
.
@return true
if only complete CRLs are returned.
Returns if this selector must match CRLs with the delta CRL indicator
extension set. Defaults to false
.
@return Returns true
if only CRLs with the delta CRL
indicator extension are selected.
The issuing distribution point.
The issuing distribution point extension is a CRL extension which
identifies the scope and the distribution point of a CRL. The scope
contains among others information about revocation reasons contained in
the CRL. Delta CRLs and complete CRLs must have matching issuing
distribution points.
The byte array is cloned to protect against subsequent modifications.
You must also enable or disable this criteria with
{@link #setIssuingDistributionPointEnabled(bool)}.
@param issuingDistributionPoint The issuing distribution point to set.
This is the DER encoded OCTET STRING extension value.
@see #getIssuingDistributionPoint()
Whether the issuing distribution point criteria should be applied.
Defaults to false
.
You may also set the issuing distribution point criteria if not a missing
issuing distribution point should be assumed.
@return Returns if the issuing distribution point check is enabled.
The maximum base CRL number. Defaults to null
.
@return Returns the maximum base CRL number.
@see #setMaxBaseCRLNumber(BigInteger)
A factory to produce Public Key Info Objects.
Create a Subject Public Key Info object for a given public key.
One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters
A subject public key info object.
Throw exception if object provided is not one of the above.
Create loading data from byte array.
Create loading data from byte array.
Generates a certificate object and initializes it with the data
read from the input stream inStream.
Returns a (possibly empty) collection view of the certificates
read from the given input stream inStream.
Class for carrying the values in an X.509 Attribute.
@param at an object representing an attribute.
Create an X.509 Attribute with the type given by the passed in oid and
the value represented by an ASN.1 Set containing value.
@param oid type of the attribute
@param value value object to go into the atribute's value set.
Create an X.59 Attribute with the type given by the passed in oid and the
value represented by an ASN.1 Set containing the objects in value.
@param oid type of the attribute
@param value vector of values to go in the attribute's value set.
An Object representing an X509 Certificate.
Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
Return true if the current time is within the start and end times nominated on the certificate.
true id certificate is valid for the current time.
Return true if the nominated time is within the start and end times nominated on the certificate.
The time to test validity against.
True if certificate is valid for nominated time.
Checks if the current date is within certificate's validity period.
Checks if the given date is within certificate's validity period.
if the certificate is expired by given date
if the certificate is not yet valid on given date
Return the certificate's version.
An integer whose value Equals the version of the cerficate.
Return a BigInteger containing the serial number.
The Serial number.
Get the Issuer Distinguished Name. (Who signed the certificate.)
And X509Object containing name and value pairs.
Get the subject of this certificate.
An X509Name object containing name and value pairs.
The time that this certificate is valid from.
A DateTime object representing that time in the local time zone.
The time that this certificate is valid up to.
A DateTime object representing that time in the local time zone.
Return the Der encoded TbsCertificate data.
This is the certificate component less the signature.
To Get the whole certificate call the GetEncoded() member.
A byte array containing the Der encoded Certificate component.
The signature.
A byte array containg the signature of the certificate.
A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA)
A sting representing the signature algorithm.
Get the Signature Algorithms Object ID.
A string containg a '.' separated object id.
Get the signature algorithms parameters. (EG DSA Parameters)
A byte array containing the Der encoded version of the parameters or null if there are none.
Get the issuers UID.
A DerBitString.
Get the subjects UID.
A DerBitString.
Get a key usage guidlines.
Get the public key of the subject of the certificate.
The public key parameters.
Return the DER encoding of this certificate.
A byte array containing the DER encoding of this certificate.
If there is an error encoding the certificate.
Verify the certificate's signature using the nominated public key.
An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters
True if the signature is valid.
If key submitted is not of the above nominated types.
Verify the certificate's signature using a verifier created using the passed in verifier provider.
An appropriate provider for verifying the certificate's signature.
True if the signature is valid.
If verifier provider is not appropriate or the certificate algorithm is invalid.
This class contains a cross certificate pair. Cross certificates pairs may
contain two cross signed certificates from two CAs. A certificate from the
other CA to this CA is contained in the forward certificate, the certificate
from this CA to the other CA is contained in the reverse certificate.
Constructor
Certificate from the other CA to this CA.
Certificate from this CA to the other CA.
Constructor from a ASN.1 CertificatePair structure.
The CertificatePair ASN.1 object.
Returns the certificate from the other CA to this CA.
Returns the certificate from this CA to the other CA.
class for dealing with X509 certificates.
At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----"
base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7
objects.
Create loading data from byte array.
Create loading data from byte array.
Generates a certificate object and initializes it with the data
read from the input stream inStream.
Returns a (possibly empty) collection view of the certificates
read from the given input stream inStream.
Create loading data from byte array.
Create loading data from byte array.
The following extensions are listed in RFC 2459 as relevant to CRLs
Authority Key Identifier
Issuer Alternative Name
CRL Number
Delta CRL Indicator (critical)
Issuing Distribution Point (critical)
Verify the CRL's signature using a verifier created using the passed in verifier provider.
An appropriate provider for verifying the CRL's signature.
True if the signature is valid.
If verifier provider is not appropriate or the CRL algorithm is invalid.
Return the DER encoding of this CRL.
A byte array containing the DER encoding of this CRL.
If there is an error encoding the CRL.
Returns a string representation of this CRL.
@return a string representation of this CRL.
Checks whether the given certificate is on this CRL.
@param cert the certificate to check for.
@return true if the given certificate is on this CRL,
false otherwise.
The following extensions are listed in RFC 2459 as relevant to CRL Entries
ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer
(critical)
Constructor for CRLEntries of indirect CRLs. If isIndirect
is false
{@link #getCertificateIssuer()} will always
return null
, previousCertificateIssuer
is
ignored. If this isIndirect
is specified and this CrlEntry
has no certificate issuer CRL entry extension
previousCertificateIssuer
is returned by
{@link #getCertificateIssuer()}.
@param c
TbsCertificateList.CrlEntry object.
@param isIndirect
true
if the corresponding CRL is a indirect
CRL.
@param previousCertificateIssuer
Certificate issuer of the previous CrlEntry.
Create loading data from byte array.
Create loading data from byte array.
Generates a certificate revocation list (CRL) object and initializes
it with the data read from the input stream inStream.
Returns a (possibly empty) collection view of the CRLs read from
the given input stream inStream.
The inStream may contain a sequence of DER-encoded CRLs, or
a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the
only significant field being crls. In particular the signature
and the contents are ignored.
Get non critical extensions.
A set of non critical extension oids.
Get any critical extensions.
A sorted list of critical entension.
A holding class for constructing an X509 Key Usage extension.
id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
KeyUsage ::= BIT STRING {
digitalSignature (0),
nonRepudiation (1),
keyEncipherment (2),
dataEncipherment (3),
keyAgreement (4),
keyCertSign (5),
cRLSign (6),
encipherOnly (7),
decipherOnly (8) }
Basic constructor.
@param usage - the bitwise OR of the Key Usage flags giving the
allowed uses for the key.
e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment)
Return the digest algorithm using one of the standard JCA string
representations rather than the algorithm identifier (if possible).
Class to Generate X509V1 Certificates.
Default Constructor.
Reset the generator.
Set the certificate's serial number.
Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
You will be surprised how ugly a serial number collision can get.
The serial number.
Set the issuer distinguished name.
The issuer is the entity whose private key is used to sign the certificate.
The issuers DN.
Set the date that this certificate is to be valid from.
Set the date after which this certificate will no longer be valid.
Set the subject distinguished name.
The subject describes the entity associated with the public key.
Set the public key that this certificate identifies.
Generate a new using the provided .
A signature factory with the necessary
algorithm details.
An .
Allows enumeration of the signature names supported by the generator.
An implementation of a version 2 X.509 Attribute Certificate.
Verify the certificate's signature using a verifier created using the passed in verifier provider.
An appropriate provider for verifying the certificate's signature.
True if the signature is valid.
If verifier provider is not appropriate or the certificate algorithm is invalid.
Class to produce an X.509 Version 2 AttributeCertificate.
Reset the generator
Set the Holder of this Attribute Certificate.
Set the issuer.
Set the serial number for the certificate.
Add an attribute.
Add a given extension field for the standard extensions tag.
Add a given extension field for the standard extensions tag.
The value parameter becomes the contents of the octet string associated
with the extension.
Generate a new using the provided .
A signature factory with the necessary
algorithm details.
An .
Allows enumeration of the signature names supported by the generator.
class to produce an X.509 Version 2 CRL.
reset the generator
Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
certificate.
Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
or 0 if CrlReason is not to be used
Add a CRL entry with an Invalidity Date extension as well as a CrlReason extension.
Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
or 0 if CrlReason is not to be used
Add a CRL entry with extensions.
Add the CRLEntry objects contained in a previous CRL.
@param other the X509Crl to source the other entries from.
add a given extension field for the standard extensions tag (tag 0)
add a given extension field for the standard extensions tag (tag 0)
add a given extension field for the standard extensions tag (tag 0)
add a given extension field for the standard extensions tag (tag 0)
Generate a new using the provided .
A signature factory with the necessary
algorithm details.
An .
Allows enumeration of the signature names supported by the generator.
A class to Generate Version 3 X509Certificates.
Reset the Generator.
Set the certificate's serial number.
Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
You will be surprised how ugly a serial number collision can Get.
The serial number.
Set the distinguished name of the issuer.
The issuer is the entity which is signing the certificate.
The issuer's DN.
Set the date that this certificate is to be valid from.
Set the date after which this certificate will no longer be valid.
Set the DN of the entity that this certificate is about.
Set the public key that this certificate identifies.
Set the subject unique ID - note: it is very rare that it is correct to do this.
Set the issuer unique ID - note: it is very rare that it is correct to do this.
Add a given extension field for the standard extensions tag (tag 3).
string containing a dotted decimal Object Identifier.
Is it critical.
The value.
Add an extension to this certificate.
Its Object Identifier.
Is it critical.
The value.
Add an extension using a string with a dotted decimal OID.
string containing a dotted decimal Object Identifier.
Is it critical.
byte[] containing the value of this extension.
Add an extension to this certificate.
Its Object Identifier.
Is it critical.
byte[] containing the value of this extension.
Add a given extension field for the standard extensions tag (tag 3),
copying the extension value from another certificate.
add a given extension field for the standard extensions tag (tag 3)
copying the extension value from another certificate.
@throws CertificateParsingException if the extension cannot be extracted.
Generate a new using the provided .
A signature factory with the necessary
algorithm details.
An .
Allows enumeration of the signature names supported by the generator.
Computes a CRC-32. The CRC-32 algorithm is parameterized - you
can set the polynomial and enable or disable bit
reversal. This can be used for GZIP, BZip2, or ZIP.
This type is used internally by DotNetZip; it is generally not used
directly by applications wishing to create, read, or manipulate zip
archive files.
Indicates the total number of bytes applied to the CRC.
Indicates the current CRC for all blocks slurped in.
Returns the CRC32 for the specified stream.
The stream over which to calculate the CRC32
the CRC32 calculation
Returns the CRC32 for the specified stream, and writes the input into the
output stream.
The stream over which to calculate the CRC32
The stream into which to deflate the input
the CRC32 calculation
Get the CRC32 for the given (word,byte) combo. This is a
computation defined by PKzip for PKZIP 2.0 (weak) encryption.
The word to start with.
The byte to combine it with.
The CRC-ized result.
Update the value for the running CRC32 using the given block of bytes.
This is useful when using the CRC32() class in a Stream.
block of bytes to slurp
starting point in the block
how many bytes within the block to slurp
Process one byte in the CRC.
the byte to include into the CRC .
Process a run of N identical bytes into the CRC.
This method serves as an optimization for updating the CRC when a
run of identical bytes is found. Rather than passing in a buffer of
length n, containing all identical bytes b, this method accepts the
byte value and the length of the (virtual) buffer - the length of
the run.
the byte to include into the CRC.
the number of times that byte should be repeated.
Combines the given CRC32 value with the current running total.
This is useful when using a divide-and-conquer approach to
calculating a CRC. Multiple threads can each calculate a
CRC32 on a segment of the data, and then combine the
individual CRC32 values at the end.
the crc value to be combined with this one
the length of data the CRC value was calculated on
Create an instance of the CRC32 class using the default settings: no
bit reversal, and a polynomial of 0xEDB88320.
Create an instance of the CRC32 class, specifying whether to reverse
data bits or not.
specify true if the instance should reverse data bits.
In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
want a CRC32 with compatibility with BZip2, you should pass true
here. In the CRC-32 used by GZIP and PKZIP, the bits are not
reversed; Therefore if you want a CRC32 with compatibility with
those, you should pass false.
Create an instance of the CRC32 class, specifying the polynomial and
whether to reverse data bits or not.
The polynomial to use for the CRC, expressed in the reversed (LSB)
format: the highest ordered bit in the polynomial value is the
coefficient of the 0th power; the second-highest order bit is the
coefficient of the 1 power, and so on. Expressed this way, the
polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
specify true if the instance should reverse data bits.
In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
want a CRC32 with compatibility with BZip2, you should pass true
here for the reverseBits parameter. In the CRC-32 used by
GZIP and PKZIP, the bits are not reversed; Therefore if you want a
CRC32 with compatibility with those, you should pass false for the
reverseBits parameter.
Reset the CRC-32 class - clear the CRC "remainder register."
Use this when employing a single instance of this class to compute
multiple, distinct CRCs on multiple, distinct data blocks.
A class for compressing and decompressing streams using the Deflate algorithm.
The DeflateStream is a Decorator on a . It adds DEFLATE compression or decompression to any
stream.
Using this stream, applications can compress or decompress data via stream
Read and Write operations. Either compresssion or decompression
can occur through either reading or writing. The compression format used is
DEFLATE, which is documented in IETF RFC 1951, "DEFLATE
Compressed Data Format Specification version 1.3.".
Create a DeflateStream using the specified CompressionMode.
When mode is CompressionMode.Compress, the DeflateStream will use
the default compression level. The "captive" stream will be closed when
the DeflateStream is closed.
This example uses a DeflateStream to compress data from a file, and writes
the compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream which will be read or written.
Indicates whether the DeflateStream will compress or decompress.
Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel.
When mode is CompressionMode.Decompress, the level parameter is
ignored. The "captive" stream will be closed when the DeflateStream is
closed.
This example uses a DeflateStream to compress data from a file, and writes
the compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to be read or written while deflating or inflating.
Indicates whether the DeflateStream will compress or decompress.
A tuning knob to trade speed for effectiveness.
Create a DeflateStream using the specified
CompressionMode, and explicitly specify whether the
stream should be left open after Deflation or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compression. Specify true for
the parameter to leave the stream open.
The DeflateStream will use the default compression level.
See the other overloads of this constructor for example code.
The stream which will be read or written. This is called the
"captive" stream in other places in this documentation.
Indicates whether the DeflateStream will compress or decompress.
true if the application would like the stream to
remain open after inflation/deflation.
Create a DeflateStream using the specified CompressionMode
and the specified CompressionLevel, and explicitly specify whether
the stream should be left open after Deflation or Inflation.
When mode is CompressionMode.Decompress, the level parameter is ignored.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
that will be re-read after
compression. Specify true for the parameter
to leave the stream open.
This example shows how to use a DeflateStream to compress data from
a file, and store the compressed data into another file.
using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".deflated")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using
The stream which will be read or written.
Indicates whether the DeflateStream will compress or decompress.
true if the application would like the stream to remain open after inflation/deflation.
A tuning knob to trade speed for effectiveness.
Create a DeflateStream using the specified CompressionMode
and the specified CompressionLevel, and explicitly specify whether
the stream should be left open after Deflation or Inflation.
When mode is CompressionMode.Decompress, the level parameter is ignored.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
that will be re-read after
compression. Specify true for the parameter
to leave the stream open.
This example shows how to use a DeflateStream to compress data from
a file, and store the compressed data into another file.
using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".deflated")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using
The stream which will be read or written.
Indicates whether the DeflateStream will compress or decompress.
true if the application would like the stream to remain open after inflation/deflation.
A tuning knob to trade speed for effectiveness.
Desired window bits.
This property sets the flush behavior on the stream.
See the ZLIB documentation for the meaning of the flush behavior.
The size of the working buffer for the compression codec.
The working buffer is used for all stream operations. The default size is
1024 bytes. The minimum size is 128 bytes. You may get better performance
with a larger buffer. Then again, you might not. You would have to test
it.
Set this before the first call to Read() or Write() on the
stream. If you try to set it afterwards, it will throw.
The ZLIB strategy to be used during compression.
By tweaking this parameter, you may be able to optimize the compression for
data with particular characteristics.
Returns the total number of bytes input so far.
Returns the total number of bytes output so far.
Dispose the stream.
This may or may not result in a Close() call on the captive
stream. See the constructors that have a leaveOpen parameter
for more information.
Application code won't call this code directly. This method may be
invoked in two distinct scenarios. If disposing == true, the method
has been called directly or indirectly by a user's code, for example
via the public Dispose() method. In this case, both managed and
unmanaged resources can be referenced and disposed. If disposing ==
false, the method has been called by the runtime from inside the
object finalizer and this method should not reference other objects;
in that case only unmanaged resources must be referenced or
disposed.
true if the Dispose method was invoked by user code.
Indicates whether the stream can be read.
The return value depends on whether the captive stream supports reading.
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream can be written.
The return value depends on whether the captive stream supports writing.
Flush the stream.
Reading this property always throws a .
The position of the stream pointer.
Setting this property always throws a . Reading will return the total bytes
written out, if used in writing, or the total bytes read in, if used in
reading. The count may refer to compressed bytes or uncompressed bytes,
depending on how you've used the stream.
Read data from the stream.
If you wish to use the DeflateStream to compress data while
reading, you can create a DeflateStream with
CompressionMode.Compress, providing an uncompressed data stream.
Then call Read() on that DeflateStream, and the data read will be
compressed as you read. If you wish to use the DeflateStream to
decompress data while reading, you can create a DeflateStream with
CompressionMode.Decompress, providing a readable compressed data
stream. Then call Read() on that DeflateStream, and the data read
will be decompressed as you read.
A DeflateStream can be used for Read() or Write(), but not both.
The buffer into which the read data should be placed.
the offset within that data array to put the first byte read.
the number of bytes to read.
the number of bytes actually read
Calling this method always throws a .
this is irrelevant, since it will always throw!
this is irrelevant, since it will always throw!
irrelevant!
Will call the base stream's SetLength method.
Write data to the stream.
If you wish to use the DeflateStream to compress data while
writing, you can create a DeflateStream with
CompressionMode.Compress, and a writable output stream. Then call
Write() on that DeflateStream, providing uncompressed data
as input. The data sent to the output stream will be the compressed form
of the data written. If you wish to use the DeflateStream to
decompress data while writing, you can create a DeflateStream with
CompressionMode.Decompress, and a writable output stream. Then
call Write() on that stream, providing previously compressed
data. The data sent to the output stream will be the decompressed form of
the data written.
A DeflateStream can be used for Read() or Write(),
but not both.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
A class for compressing and decompressing GZIP streams.
The GZipStream is a Decorator on a
. It adds GZIP compression or decompression to any
stream.
Like the System.IO.Compression.GZipStream in the .NET Base Class Library, the
Ionic.Zlib.GZipStream can compress while writing, or decompress while
reading, but not vice versa. The compression method used is GZIP, which is
documented in IETF RFC
1952, "GZIP file format specification version 4.3".
A GZipStream can be used to decompress data (through Read()) or
to compress data (through Write()), but not both.
If you wish to use the GZipStream to compress data, you must wrap it
around a write-able stream. As you call Write() on the GZipStream, the
data will be compressed into the GZIP format. If you want to decompress data,
you must wrap the GZipStream around a readable stream that contains an
IETF RFC 1952-compliant stream. The data will be decompressed as you call
Read() on the GZipStream.
Though the GZIP format allows data from multiple files to be concatenated
together, this stream handles only a single segment of GZIP format, typically
representing a single file.
The comment on the GZIP stream.
The GZIP format allows for each file to optionally have an associated
comment stored with the file. The comment is encoded with the ISO-8859-1
code page. To include a comment in a GZIP stream you create, set this
property before calling Write() for the first time on the
GZipStream.
When using GZipStream to decompress, you can retrieve this property
after the first call to Read(). If no comment has been set in the
GZIP bytestream, the Comment property will return null
(Nothing in VB).
The FileName for the GZIP stream.
The GZIP format optionally allows each file to have an associated
filename. When compressing data (through Write()), set this
FileName before calling Write() the first time on the GZipStream.
The actual filename is encoded into the GZIP bytestream with the
ISO-8859-1 code page, according to RFC 1952. It is the application's
responsibility to insure that the FileName can be encoded and decoded
correctly with this code page.
When decompressing (through Read()), you can retrieve this value
any time after the first Read(). In the case where there was no filename
encoded into the GZIP bytestream, the property will return null (Nothing
in VB).
The last modified time for the GZIP stream.
GZIP allows the storage of a last modified time with each GZIP entity.
When compressing data, you can set this before the first call to
Write(). When decompressing, you can retrieve this value any time
after the first call to Read().
The CRC on the GZIP stream.
This is used for internal error checking. You probably don't need to look at this property.
Create a GZipStream using the specified CompressionMode.
When mode is CompressionMode.Compress, the GZipStream will use the
default compression level.
As noted in the class documentation, the CompressionMode (Compress
or Decompress) also establishes the "direction" of the stream. A
GZipStream with CompressionMode.Compress works only through
Write(). A GZipStream with
CompressionMode.Decompress works only through Read().
This example shows how to use a GZipStream to compress data.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
This example shows how to use a GZipStream to uncompress a file.
private void GunZipFile(string filename)
{
if (!filename.EndsWith(".gz))
throw new ArgumentException("filename");
var DecompressedFile = filename.Substring(0,filename.Length-3);
byte[] working = new byte[WORKING_BUFFER_SIZE];
int n= 1;
using (System.IO.Stream input = System.IO.File.OpenRead(filename))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(DecompressedFile))
{
while (n !=0)
{
n= decompressor.Read(working, 0, working.Length);
if (n > 0)
{
output.Write(working, 0, n);
}
}
}
}
}
}
Private Sub GunZipFile(ByVal filename as String)
If Not (filename.EndsWith(".gz)) Then
Throw New ArgumentException("filename")
End If
Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
Dim working(WORKING_BUFFER_SIZE) as Byte
Dim n As Integer = 1
Using input As Stream = File.OpenRead(filename)
Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
Using output As Stream = File.Create(UncompressedFile)
Do
n= decompressor.Read(working, 0, working.Length)
If n > 0 Then
output.Write(working, 0, n)
End IF
Loop While (n > 0)
End Using
End Using
End Using
End Sub
The stream which will be read or written.
Indicates whether the GZipStream will compress or decompress.
Create a GZipStream using the specified CompressionMode and
the specified CompressionLevel.
The CompressionMode (Compress or Decompress) also establishes the
"direction" of the stream. A GZipStream with
CompressionMode.Compress works only through Write(). A
GZipStream with CompressionMode.Decompress works only
through Read().
This example shows how to use a GZipStream to compress a file into a .gz file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
{
using (Stream compressor = new GZipStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".gz")
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to be read or written while deflating or inflating.
Indicates whether the GZipStream will compress or decompress.
A tuning knob to trade speed for effectiveness.
Create a GZipStream using the specified CompressionMode, and
explicitly specify whether the stream should be left open after Deflation
or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compressed data has been written
to it. Specify true for the parameter to leave
the stream open.
The (Compress or Decompress) also
establishes the "direction" of the stream. A GZipStream with
CompressionMode.Compress works only through Write(). A GZipStream
with CompressionMode.Decompress works only through Read().
The GZipStream will use the default compression level. If you want
to specify the compression level, see .
See the other overloads of this constructor for example code.
The stream which will be read or written. This is called the "captive"
stream in other places in this documentation.
Indicates whether the GZipStream will compress or decompress.
true if the application would like the base stream to remain open after
inflation/deflation.
Create a GZipStream using the specified CompressionMode and the
specified CompressionLevel, and explicitly specify whether the
stream should be left open after Deflation or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compressed data has been written
to it. Specify true for the parameter to
leave the stream open.
As noted in the class documentation, the CompressionMode (Compress
or Decompress) also establishes the "direction" of the stream. A
GZipStream with CompressionMode.Compress works only through
Write(). A GZipStream with CompressionMode.Decompress works only
through Read().
This example shows how to use a GZipStream to compress data.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream which will be read or written.
Indicates whether the GZipStream will compress or decompress.
true if the application would like the stream to remain open after inflation/deflation.
A tuning knob to trade speed for effectiveness.
This property sets the flush behavior on the stream.
The size of the working buffer for the compression codec.
The working buffer is used for all stream operations. The default size is
1024 bytes. The minimum size is 128 bytes. You may get better performance
with a larger buffer. Then again, you might not. You would have to test
it.
Set this before the first call to Read() or Write() on the
stream. If you try to set it afterwards, it will throw.
Returns the total number of bytes input so far.
Returns the total number of bytes output so far.
Dispose the stream.
This may or may not result in a Close() call on the captive
stream. See the constructors that have a leaveOpen parameter
for more information.
This method may be invoked in two distinct scenarios. If disposing
== true, the method has been called directly or indirectly by a
user's code, for example via the public Dispose() method. In this
case, both managed and unmanaged resources can be referenced and
disposed. If disposing == false, the method has been called by the
runtime from inside the object finalizer and this method should not
reference other objects; in that case only unmanaged resources must
be referenced or disposed.
indicates whether the Dispose method was invoked by user code.
Indicates whether the stream can be read.
The return value depends on whether the captive stream supports reading.
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream can be written.
The return value depends on whether the captive stream supports writing.
Flush the stream.
Reading this property always throws a .
The position of the stream pointer.
Setting this property always throws a . Reading will return the total bytes
written out, if used in writing, or the total bytes read in, if used in
reading. The count may refer to compressed bytes or uncompressed bytes,
depending on how you've used the stream.
Read and decompress data from the source stream.
With a GZipStream, decompression is done through reading.
byte[] working = new byte[WORKING_BUFFER_SIZE];
using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(_DecompressedFile))
{
int n;
while ((n= decompressor.Read(working, 0, working.Length)) !=0)
{
output.Write(working, 0, n);
}
}
}
}
The buffer into which the decompressed data should be placed.
the offset within that data array to put the first byte read.
the number of bytes to read.
the number of bytes actually read
Calling this method always throws a .
irrelevant; it will always throw!
irrelevant; it will always throw!
irrelevant!
Calling this method always throws a .
irrelevant; this method will always throw!
Write data to the stream.
If you wish to use the GZipStream to compress data while writing,
you can create a GZipStream with CompressionMode.Compress, and a
writable output stream. Then call Write() on that GZipStream,
providing uncompressed data as input. The data sent to the output stream
will be the compressed form of the data written.
A GZipStream can be used for Read() or Write(), but not
both. Writing implies compression. Reading implies decompression.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
Describes how to flush the current deflate operation.
The different FlushType values are useful when using a Deflate in a streaming application.
No flush at all.
Closes the current block, but doesn't flush it to
the output. Used internally only in hypothetical
scenarios. This was supposed to be removed by Zlib, but it is
still in use in some edge cases.
Use this during compression to specify that all pending output should be
flushed to the output buffer and the output should be aligned on a byte
boundary. You might use this in a streaming communication scenario, so that
the decompressor can get all input data available so far. When using this
with a ZlibCodec, AvailableBytesIn will be zero after the call if
enough output space has been provided before the call. Flushing will
degrade compression and so it should be used only when necessary.
Use this during compression to specify that all output should be flushed, as
with FlushType.Sync, but also, the compression state should be reset
so that decompression can restart from this point if previous compressed
data has been damaged or if random access is desired. Using
FlushType.Full too often can significantly degrade the compression.
Signals the end of the compression/decompression stream.
The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
None means that the data will be simply stored, with no change at all.
If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
cannot be opened with the default zip reader. Use a different CompressionLevel.
Same as None.
The fastest but least effective compression.
A synonym for BestSpeed.
A little slower, but better, than level 1.
A little slower, but better, than level 2.
A little slower, but better, than level 3.
A little slower than level 4, but with better compression.
The default compression level, with a good balance of speed and compression efficiency.
A synonym for Default.
Pretty good compression!
Better compression than Level7!
The "best" compression, where best means greatest reduction in size of the input data stream.
This is also the slowest compression.
A synonym for BestCompression.
Describes options for how the compression algorithm is executed. Different strategies
work better on different sorts of data. The strategy parameter can affect the compression
ratio and the speed of compression but not the correctness of the compresssion.
The default strategy is probably the best for normal data.
The Filtered strategy is intended to be used most effectively with data produced by a
filter or predictor. By this definition, filtered data consists mostly of small
values with a somewhat random distribution. In this case, the compression algorithm
is tuned to compress them better. The effect of Filtered is to force more Huffman
coding and less string matching; it is a half-step between Default and HuffmanOnly.
Using HuffmanOnly will force the compressor to do Huffman encoding only, with no
string matching.
An enum to specify the direction of transcoding - whether to compress or decompress.
Used to specify that the stream should compress the data.
Used to specify that the stream should decompress the data.
A general purpose exception class for exceptions in the Zlib library.
The ZlibException class captures exception information generated
by the Zlib library.
This ctor collects a message attached to the exception.
the message for the exception.
Performs an unsigned bitwise right shift with the specified number
Number to operate on
Ammount of bits to shift
The resulting number from the shift operation
Reads a number of characters from the current source TextReader and writes
the data to the target array at the specified index.
The source TextReader to read from
Contains the array of characteres read from the source TextReader.
The starting index of the target array.
The maximum number of characters to read from the source TextReader.
The number of characters read. The number will be less than or equal to
count depending on the data available in the source TextReader. Returns -1
if the end of the stream is reached.
Computes an Adler-32 checksum.
The Adler checksum is similar to a CRC checksum, but faster to compute, though less
reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
is a required part of the "ZLIB" standard. Applications will almost never need to
use this class directly.
Calculates the Adler32 checksum.
This is used within ZLIB. You probably don't need to use this directly.
To compute an Adler32 checksum on a byte array:
var adler = Adler.Adler32(0, null, 0, 0);
adler = Adler.Adler32(adler, buffer, index, length);
Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
This class compresses and decompresses data according to the Deflate algorithm
and optionally, the ZLIB format, as documented in RFC 1950 - ZLIB and RFC 1951 - DEFLATE.
The buffer from which data is taken.
An index into the InputBuffer array, indicating where to start reading.
The number of bytes available in the InputBuffer, starting at NextIn.
Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
The class will update this number as calls to Inflate/Deflate are made.
Total number of bytes read so far, through all calls to Inflate()/Deflate().
Buffer to store output data.
An index into the OutputBuffer array, indicating where to start writing.
The number of bytes available in the OutputBuffer, starting at NextOut.
Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
The class will update this number as calls to Inflate/Deflate are made.
Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
used for diagnostics, when something goes wrong!
The compression level to use in this codec. Useful only in compression mode.
The number of Window Bits to use.
This gauges the size of the sliding window, and hence the
compression effectiveness as well as memory consumption. It's best to just leave this
setting alone if you don't know what it is. The maximum value is 15 bits, which implies
a 32k window.
The compression strategy to use.
This is only effective in compression. The theory offered by ZLIB is that different
strategies could potentially produce significant differences in compression behavior
for different data sets. Unfortunately I don't have any good recommendations for how
to set it differently. When I tested changing the strategy I got minimally different
compression performance. It's best to leave this property alone if you don't have a
good feel for it. Or, you may want to produce a test harness that runs through the
different strategy options and evaluates them on different file types. If you do that,
let me know your results.
The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
Create a ZlibCodec.
If you use this default constructor, you will later have to explicitly call
InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
or decompress.
Create a ZlibCodec that either compresses or decompresses.
Indicates whether the codec should compress (deflate) or decompress (inflate).
Initialize the inflation state.
It is not necessary to call this before using the ZlibCodec to inflate data;
It is implicitly called when you call the constructor.
Z_OK if everything goes well.
Initialize the inflation state with an explicit flag to
govern the handling of RFC1950 header bytes.
By default, the ZLIB header defined in RFC 1950 is expected. If
you want to read a zlib stream you should specify true for
expectRfc1950Header. If you have a deflate stream, you will want to specify
false. It is only necessary to invoke this initializer explicitly if you
want to specify false.
whether to expect an RFC1950 header byte
pair when reading the stream of data to be inflated.
Z_OK if everything goes well.
Initialize the ZlibCodec for inflation, with the specified number of window bits.
The number of window bits to use. If you need to ask what that is,
then you shouldn't be calling this initializer.
Z_OK if all goes well.
Initialize the inflation state with an explicit flag to govern the handling of
RFC1950 header bytes.
If you want to read a zlib stream you should specify true for
expectRfc1950Header. In this case, the library will expect to find a ZLIB
header, as defined in RFC
1950, in the compressed stream. If you will be reading a DEFLATE or
GZIP stream, which does not have such a header, you will want to specify
false.
whether to expect an RFC1950 header byte pair when reading
the stream of data to be inflated.
The number of window bits to use. If you need to ask what that is,
then you shouldn't be calling this initializer.
Z_OK if everything goes well.
Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
AvailableBytesOut before calling this method.
private void InflateBuffer()
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec decompressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
MemoryStream ms = new MemoryStream(DecompressedBytes);
int rc = decompressor.InitializeInflate();
decompressor.InputBuffer = CompressedBytes;
decompressor.NextIn = 0;
decompressor.AvailableBytesIn = CompressedBytes.Length;
decompressor.OutputBuffer = buffer;
// pass 1: inflate
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("inflating: " + decompressor.Message);
ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("inflating: " + decompressor.Message);
if (buffer.Length - decompressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
decompressor.EndInflate();
}
The flush to use when inflating.
Z_OK if everything goes well.
Ends an inflation session.
Call this after successively calling Inflate(). This will cause all buffers to be flushed.
After calling this you cannot call Inflate() without a intervening call to one of the
InitializeInflate() overloads.
Z_OK if everything goes well.
I don't know what this does!
Z_OK if everything goes well.
Initialize the ZlibCodec for deflation operation.
The codec will use the MAX window bits and the default level of compression.
int bufferSize = 40000;
byte[] CompressedBytes = new byte[bufferSize];
byte[] DecompressedBytes = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
compressor.InitializeDeflate(CompressionLevel.Default);
compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
compressor.NextIn = 0;
compressor.AvailableBytesIn = compressor.InputBuffer.Length;
compressor.OutputBuffer = CompressedBytes;
compressor.NextOut = 0;
compressor.AvailableBytesOut = CompressedBytes.Length;
while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
{
compressor.Deflate(FlushType.None);
}
while (true)
{
int rc= compressor.Deflate(FlushType.Finish);
if (rc == ZlibConstants.Z_STREAM_END) break;
}
compressor.EndDeflate();
Z_OK if all goes well. You generally don't need to check the return code.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
The codec will use the maximum window bits (15) and the specified
CompressionLevel. It will emit a ZLIB stream as it compresses.
The compression level for the codec.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
and the explicit flag governing whether to emit an RFC1950 header byte pair.
The codec will use the maximum window bits (15) and the specified CompressionLevel.
If you want to generate a zlib stream, you should specify true for
wantRfc1950Header. In this case, the library will emit a ZLIB
header, as defined in RFC
1950, in the compressed stream.
The compression level for the codec.
whether to emit an initial RFC1950 byte pair in the compressed stream.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
and the specified number of window bits.
The codec will use the specified number of window bits and the specified CompressionLevel.
The compression level for the codec.
the number of window bits to use. If you don't know what this means, don't use this method.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified
CompressionLevel, the specified number of window bits, and the explicit flag
governing whether to emit an RFC1950 header byte pair.
The compression level for the codec.
whether to emit an initial RFC1950 byte pair in the compressed stream.
the number of window bits to use. If you don't know what this means, don't use this method.
Z_OK if all goes well.
Deflate one batch of data.
You must have set InputBuffer and OutputBuffer before calling this method.
private void DeflateBuffer(CompressionLevel level)
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
MemoryStream ms = new MemoryStream();
int rc = compressor.InitializeDeflate(level);
compressor.InputBuffer = UncompressedBytes;
compressor.NextIn = 0;
compressor.AvailableBytesIn = UncompressedBytes.Length;
compressor.OutputBuffer = buffer;
// pass 1: deflate
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("deflating: " + compressor.Message);
ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
compressor.EndDeflate();
ms.Seek(0, SeekOrigin.Begin);
CompressedBytes = new byte[compressor.TotalBytesOut];
ms.Read(CompressedBytes, 0, CompressedBytes.Length);
}
whether to flush all data as you deflate. Generally you will want to
use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
flush everything.
Z_OK if all goes well.
End a deflation session.
Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
Z_OK if all goes well.
Reset a codec for another deflation session.
Call this to reset the deflation state. For example if a thread is deflating
non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
block and before the next Deflate(None) of the second block.
Z_OK if all goes well.
Set the CompressionStrategy and CompressionLevel for a deflation session.
the level of compression to use.
the strategy to use for compression.
Z_OK if all goes well.
Set the dictionary to be used for either Inflation or Deflation.
The dictionary bytes to use.
Z_OK if all goes well.
A bunch of constants used in the Zlib interface.
The maximum number of window bits for the Deflate algorithm.
The default number of window bits for the Deflate algorithm.
indicates everything is A-OK
Indicates that the last operation reached the end of the stream.
The operation ended in need of a dictionary.
There was an error with the stream - not enough data, not open and readable, etc.
There was an error with the data - not enough data, bad data, etc.
There was an error with the working buffer.
The size of the working buffer used in the ZlibCodec class. Defaults to 8192 bytes.
The minimum size of the working buffer used in the ZlibCodec class. Currently it is 128 bytes.
Map from a distance to a distance code.
No side effects. _dist_code[256] and _dist_code[257] are never used.
Loads the first content from the metadata indexes.
Loads the content from the metadata index.
Loads all content from the metadatas.
Loads all content from the metadata indexes.
Sum size of the cached contents
Implements most common list functions. With best case (no or only one item) it doesn't do any allocation.
Depth of the node.
Difference between LeftDepth and RightDepth.
Left node's Depth, or -1 if it's null.
Right node's Depth, or -1 if it's null.
Removes node and reparent any child it has.
Index newly added metadata
Remove metadata from all indexes.
Clear all indexes
Get indexes in an optimized order. This is usually one of the indexes' WalkHorizontal() call.
Called when metadata loaded from file
Called by a concrete MetadataService implementation to create a new metadata
On WP8 platform there are no ASCII encoding.
On WP8 platform there are no ASCII encoding.
Returns true if the Uri's host is a valid IPv4 or IPv6 address.
Validates an IPv4 address.
Validates an IPv6 address.
Will fill the entire buffer from the stream. Will throw an exception when the underlying stream is closed.
Will parse a comma-separeted header value
Used in string parsers. Its Value is optional.
A manager class that can handle subscribing and unsubscribeing in the same update.
Base class for specialized parsers
Create a new TimerData but the Created field will be set to the current time.
Global entry point to access and manage main services of the plugin.
Static constructor. Setup default values.
Delegate for the setup finished event.
Instance of the per-host settings manager.
Cached DateTime value for cases where high resolution isn't needed.
Warning!! It must be used only on the main update thread!
By default the plugin will save all cache and cookie data under the path returned by Application.persistentDataPath.
You can assign a function to this delegate to return a custom root path to define a new path.
This delegate will be called on a non Unity thread!
The global, default proxy for all HTTPRequests. The HTTPRequest's Proxy still can be changed per-request. Default value is null.
Heartbeat manager to use less threads in the plugin. The heartbeat updates are called from the OnUpdate function.
A basic Best.HTTP.Logger.ILogger implementation to be able to log intelligently additional informations about the plugin's internal mechanism.
An IIOService implementation to handle filesystem operations.
User-agent string that will be sent with each requests.
It's true if the application is quitting and the plugin is shutting down itself.
The local content cache, maintained by the plugin. When set to a non-null value, Maintain called immediately on the cache.
Initializes the HTTPManager with default settings. This method should be called on Unity's main thread before using the HTTP plugin. By default it gets called by .
Will return where the various caches should be saved.
Updates the HTTPManager. This method should be called regularly from a Unity event (e.g., Update, LateUpdate).
It processes various events and callbacks and manages internal tasks.
Shuts down the HTTPManager and performs cleanup operations. This method should be called when the application is quitting.
Aborts all ongoing HTTP requests and performs an immediate shutdown of the HTTPManager.
Threading mode the plugin will use to call HTTPManager.OnUpdate().
HTTPManager.OnUpdate() is called from the HTTPUpdateDelegator's Update functions (Unity's main thread).
The plugin starts a dedicated thread to call HTTPManager.OnUpdate() periodically.
HTTPManager.OnUpdate() will not be called automatically.
Will route some U3D calls to the HTTPManager.
The singleton instance of the HTTPUpdateDelegator
True, if the Instance property should hold a valid value.
It's true if the dispatch thread running.
The current threading mode the plugin is in.
How much time the plugin should wait between two update call. Its default value 100 ms.
Called in the OnApplicationQuit function. If this function returns False, the plugin will not start to
shut down itself.
Called when the Unity application's foreground state changed.
Called after scene loaded to support Configurable Enter Play Mode (https://docs.unity3d.com/2019.3/Documentation/Manual/ConfigurableEnterPlayMode.html)
Will create the HTTPUpdateDelegator instance and set it up.
Return true if the call happens on the Unity main thread. Setup must be called before to save the thread id!
Set directly the threading mode to use.
Swaps threading mode between Unity's Update function or a distinct thread.
Pings the update thread to call HTTPManager.OnUpdate immediately.
Works only when the current threading mode is Threaded!
Provides an implementation of that writes log messages to a file.
Gets a value indicating whether this log output accepts color codes. Always returns false.
Initializes a new instance of the FileOutput class with the specified file name.
The name of the file to write log messages to.
Writes a log message to the file.
The log level of the message.
The log message to write.
Flushes any buffered log messages to the file.
Releases any resources used by the FileOutput instance.
Available logging levels.
All message will be logged.
Only Informations and above will be logged.
Only Warnings and above will be logged.
Only Errors and above will be logged.
Only Exceptions will be logged.
No logging will occur.
Represents an output target for log messages.
This interface defines methods for writing log messages to an output target.
Implementations of this interface are used to configure where log messages
should be written.
Two of its out-of-the-box implementations are
- UnityOutput
- FileOutput
Gets a value indicating whether the log output supports colored text.
Writes a log entry to the output.
The logging level of the entry.
The log message to write.
Flushes any buffered log entries to the output.
Represents a filter for further sort out what log entries to include in the final log output.
Return true if the division must be included in the output.
Represents a logger for recording log messages.
Gets or sets the minimum severity level for logging.
Gets or sets the output target for log messages.
The instance used to write log messages.
Gets or sets an output filter to decide what messages are included or not.
The instance used for filtering.
Property indicating whether the logger's internal queue is empty or not.
Gets a value indicating whether diagnostic logging is enabled.
Diagnostic logging is enabled when is set to .
Logs a message with level.
The division or category of the log message.
The verbose log message.
The optional for additional context.
Logs a message with level.
The division or category of the log message.
The verbose log message.
The optional for additional context.
Logs a message with level.
The division or category of the log message.
The verbose log message.
The optional for additional context.
Logs a message with level.
The division or category of the log message.
The verbose log message.
The optional for additional context.
Logs a message with level.
The division or category of the log message.
The verbose log message.
The optional for additional context.
Represents a logging context for categorizing and organizing log messages.
The LoggingContext class is used to provide additional context information
to log messages, allowing for better categorization and organization of log output. It can be
associated with specific objects or situations to enrich log entries with context-specific data.
Gets the unique hash value of this logging context.
Initializes a new instance of the LoggingContext class associated with the specified object.
The object to associate the context with.
Adds a long value to the logging context.
The key to associate with the value.
The long value to add.
Adds a bool value to the logging context.
The key to associate with the value.
The bool value to add.
Adds a string value to the logging context.
The key to associate with the value.
The string value to add.
Adds a LoggingContext value to the logging context.
The key to associate with the value.
The LoggingContext value to add.
Gets the string field with the specified name from the logging context.
The name of the string field to retrieve.
The value of the string field or null if not found.
Removes a field from the logging context by its key.
The key of the field to remove.
Converts the logging context and its associated fields to a JSON string representation.
A instance to which the JSON string is appended.
This method serializes the logging context and its associated fields into a JSON format
for structured logging purposes. The resulting JSON string represents the context and its fields, making it
suitable for inclusion in log entries for better analysis and debugging.
implementation to include only one division in the log output.
implementation to allow filtering for multiple divisions.
Provides an implementation of that writes log messages to the Unity Debug Console.
Gets a value indicating whether this log output accepts color codes.
This property returns true when running in the Unity Editor and false otherwise.
Writes a log message to the Unity Debug Console based on the specified log level.
The log level of the message.
The log message to write.
This implementation does nothing.
These are the different modes that the plugin want's to use a filestream.
Create a new file.
Open an existing file for reading.
Open or create a file for read and write.
Open an existing file for writing to the end.
Interface for file-system abstraction.
Create a directory for the given path.
Return true if the directory exists for the given path.
Delete the directory.
Return with the file names for the given path.
Delete the file for the given path.
Return true if the file exists on the given path.
Create a stream that can read and/or write a file on the given path.
The code generation options available for IL to C++ conversion.
Enable or disabled these with caution.
Enable or disable code generation for null checks.
Global null check support is enabled by default when il2cpp.exe
is launched from the Unity editor.
Disabling this will prevent NullReferenceException exceptions from
being thrown in generated code. In *most* cases, code that dereferences
a null pointer will crash then. Sometimes the point where the crash
happens is later than the location where the null reference check would
have been emitted though.
Enable or disable code generation for array bounds checks.
Global array bounds check support is enabled by default when il2cpp.exe
is launched from the Unity editor.
Disabling this will prevent IndexOutOfRangeException exceptions from
being thrown in generated code. This will allow reading and writing to
memory outside of the bounds of an array without any runtime checks.
Disable this check with extreme caution.
Enable or disable code generation for divide by zero checks.
Global divide by zero check support is disabled by default when il2cpp.exe
is launched from the Unity editor.
Enabling this will cause DivideByZeroException exceptions to be
thrown in generated code. Most code doesn't need to handle this
exception, so it is probably safe to leave it disabled.
Use this attribute on a class, method, or property to inform the IL2CPP code conversion utility to override the
global setting for one of a few different runtime checks.
Example:
[Il2CppSetOption(Option.NullChecks, false)]
public static string MethodWithNullChecksDisabled()
{
var tmp = new Object();
return tmp.ToString();
}
https://docs.unity3d.com/Manual/ManagedCodeStripping.html
Light-weight user-mode lock for code blocks that has rare contentions and doesn't take a long time to finish.
The BufferPool is a foundational element of the Best HTTP package, aiming to reduce dynamic memory allocation overheads by reusing byte arrays. The concept is elegantly simple: rather than allocating and deallocating memory for every requirement, byte arrays can be "borrowed" and "returned" within this pool. Once returned, these arrays are retained for subsequent use, minimizing repetitive memory operations.
While the BufferPool is housed within the Best HTTP package, its benefits are not limited to just HTTP operations. All protocols and packages integrated with or built upon the Best HTTP package utilize and benefit from the BufferPool. This ensures that memory is used efficiently and performance remains optimal across all integrated components.
Represents an empty byte array that can be returned for zero-length requests.
Gets or sets a value indicating whether the buffer pooling mechanism is enabled or disabled.
Disabling will also clear all stored entries.
Specifies the duration after which buffer entries, once released back to the pool, are deemed old and will be
considered for removal in the next maintenance cycle.
Specifies how frequently the maintenance cycle should run to manage old buffers.
Specifies the minimum buffer size that will be allocated. If a request is made for a size smaller than this and canBeLarger is true,
this size will be used.
Specifies the maximum size of a buffer that the system will consider storing back into the pool.
Specifies the maximum total size of all stored buffers. When the buffer reach this threshold, new releases will be declined.
Indicates whether to remove buffer stores that don't hold any buffers from the free list.
If set to true, and a byte array is released back to the pool more than once, an error will be logged.
Error checking is expensive and has a very large overhead! Turn it on with caution!
Fetches a byte array from the pool.
Depending on the `canBeLarger` parameter, the returned buffer may be larger than the requested size!
Requested size of the buffer.
If true, the returned buffer can be larger than the requested size.
Optional context for logging purposes.
A byte array from the pool or a newly allocated one if suitable size is not available.
Releases a list of buffer segments back to the pool in a bulk operation.
List of buffer segments to release.
Releases a list of buffer segments back to the pool in a bulk operation.
List of buffer segments to release.
Releases a byte array back to the pool.
Buffer to be released back to the pool.
Resizes a byte array by returning the old one to the pool and fetching (or creating) a new one of the specified size.
Buffer to resize.
New size for the buffer.
If true, the new buffer can be larger than the specified size.
If true, the new buffer will be cleared (set to all zeros).
Optional context for logging purposes.
A resized buffer.
Clears all stored entries in the buffer pool instantly, releasing memory.
Internal method called by the plugin to remove old, non-used buffers.
Represents a segment (a continuous section) of a byte array, providing functionalities to
work with a portion of the data without copying.
Represents an empty buffer segment.
The underlying data of the buffer segment.
The starting offset of the segment within the data.
The number of bytes in the segment that contain valid data.
Initializes a new instance of the BufferSegment struct.
The data for the buffer segment.
The starting offset of the segment.
The number of bytes in the segment.
Converts the buffer segment to an AutoReleaseBuffer to use it in a local using statement.
A new AutoReleaseBuffer instance containing the data of the buffer segment.
Creates a new segment starting from the specified offset.
The new segment will reference the same underlying byte[] as the original, without creating a copy of the data.
The starting offset of the new segment.
A new buffer segment that references the same underlying data.
Creates a new segment with the specified offset and count.
The new segment will reference the same underlying byte[] as the original, without creating a copy of the data.
The starting offset of the new segment.
The number of bytes in the new segment.
A new buffer segment that references the same underlying data.
Copyies the buffer's content to the received array.
The array the data will be copied into.
Private data struct that contains the size - byte arrays mapping.
Size/length of the arrays stored in the buffers.
Create a new store with its first byte[] to store.
Helper struct for .
The actual reference to the stored byte array.
When the buffer is put back to the pool. Based on this value the pool will calculate the age of the buffer.
Represents the result of a DNS query, including the original host name, resolved IP addresses, and any error.
The host name used in the DNS query.
The resolved IP addresses associated with the host name.
Any error that occurred during the DNS query.
Represents an IP address obtained from DNS resolution.
The resolved IP address.
Indicates whether this IP address worked during the last connection attempt.
Represents options for configuring the DNS cache behavior.
The time interval after which DNS cache entries should be refreshed.
The time interval after which DNS cache entries should be removed if not used.
The granularity of cancellation checks for DNS queries.
The frequency of cache maintenance.
Represents parameters for a DNS query, including the host name, address, cancellation token, logging context, callback, and tag.
The hash key associated with the DNS query.
The host name used in the DNS query.
The URI address used in the DNS query.
The cancellation token used to cancel the DNS query.
Optional logging context.
The callback to be invoked upon completion of the DNS query.
An optional object reference associated with the DNS query.
Indicates whether the DNS query is a prefetch query.
The DNSCache class is a static utility that manages DNS caching and queries within the Best HTTP library.
It helps improve network efficiency by caching DNS query results, reducing the need for redundant DNS resolutions.
By utilizing the DNSCache class and its associated features, you can optimize DNS resolution in your network communication, leading to improved performance and reduced latency in your applications.
Its key features include:
-
Improving Network Efficiency
The DNSCache class is designed to enhance network efficiency by caching DNS query results.
When your application needs to resolve hostnames to IP addresses for making network requests, the DNSCache stores previously resolved results.
This reduces the need for redundant DNS resolutions, making network communication faster and more efficient.
-
DNS Prefetching
You can use the DNSCache to initiate DNS prefetch operations.
Prefetching allows you to resolve and cache DNS records for hostnames in advance, reducing latency for future network requests.
This is particularly useful when you expect to make multiple network requests to the same hostnames, as it helps to avoid DNS resolution delays.
-
Marking IP Addresses as Non-Working
In cases where a previously resolved IP address is determined to be non-functional (e.g., due to network issues), you can use the DNSCache to report IP addresses as non-working.
This information helps the cache make better decisions about which IP addresses to use for future network connections. gives higher priority for adresses not marked as non-working.
-
Clearing the DNS Cache
If you need to reset the DNS cache and remove all stored DNS resolutions, you can use the Clear method provided by the DNSCache class.
This operation can be useful in scenarios where you want to start with a fresh cache.
-
Performing DNS Queries
The primary function of the DNSCache class is to perform DNS queries with specified parameters.
It resolves DNS records for a given hostname and caches the results. This can be called directly or used internally by the Best HTTP library for resolving hostnames.
-
Configuring Cache Behavior
You can configure the behavior of the DNS cache using the DNSCacheOptions class.
This includes setting refresh intervals for cache entries, defining the granularity of cancellation checks for DNS queries, and specifying the frequency of cache maintenance.
Options for configuring the DNS cache behavior, including refresh intervals and maintenance frequency.
Initiates a DNS prefetch operation for the specified host name. DNS prefetching is used to resolve and cache
DNS records for host names in advance, reducing latency for future network requests.
The host name to prefetch.
Reports an IP address as non-working for the specified host name. In cases where a previously resolved IP address
is determined to be non-functional, this method updates the cache to mark the IP address as non-working.
The host name associated with the IP address.
The to report as non-working.
Optional logging context for debugging purposes.
Clears the DNS cache, removing all cached DNS records. This operation can be used to reset the cache
and remove all stored DNS resolutions.
Performs a DNS query with the specified parameters. It resolves DNS records for a given host name,
caching the results to reduce the need for redundant DNS resolutions.
The parameters for the DNS query.
It's plan-b for the case where BeginGetHostAddresses take too long and no reply in time. If the query's Token is canceled it will call the callback if it's still available.
Represents a cached entry for DNS query results, including resolved IP addresses and metadata.
Almost immutable, all changes are done in-class in a thread-safe manner.
Gets the 128-bit hash derived from the host name.
Gets the host name this entry stores the IP addresses for.
Gets the timestamp when the entry was last resolved.
Gets the timestamp when the entry was last used by calling .
Resolved IP addresses. It's private, accesible through the call only.
Flag that is set to true when the cache is refreshing this host.
When set to true, will always return as non-stalled.
Initializes a new instance of the DNSCacheEntry class.
The 128-bit hash key derived from the host name.
The host name associated with this entry.
The list of containing the resolved IP addresses.
Called to clone the entry. The new entry will inherit the last used timestamp.
The list of containing the resolved IP addresses.
A new DNSCacheEntry instance with updated resolved addresses.
Checks if the entry is stalled and needs to be refreshed.
The current timestamp.
true if the entry is stalled; otherwise, false.
The entry is considered stalled if it is not currently being refreshed (i.e., is false)
and the time since the last resolution exceeds the refresh interval specified in .
Checks if the entry is ready to be removed from the cache.
The current timestamp.
true if the entry is ready for removal; otherwise, false.
The entry is considered ready for removal if the time since it was last used exceeds the removal interval specified in .
Refreshes the entry by initiating a DNS prefetch (by calling ) for the associated host name.
This method initiates a DNS prefetch operation for the host name associated with this entry.
DNS prefetching is used to resolve and cache DNS records for host names in advance, reducing latency for future network requests.
Gets the resolved IP addresses associated with this entry.
An array of representing resolved IP addresses.
This method returns the resolved IP addresses associated with this entry and updates the last used timestamp.
Reports an IP address as non-working for the specified host name. In cases where a previously resolved IP address
is determined to be non-functional, this method updates the cache to mark the IP address as non-working.
The non-working IP address to report.
Optional logging context for debugging purposes.
This method is used to report an IP address associated with a host name as non-working.
When a previously resolved IP address is determined to be non-functional, this method updates the cache to mark the IP address as non-working.
It can be useful in situations where network errors or issues with specific IP addresses need to be recorded and managed.
The IPeekableContentProvider interface defines an abstraction for providing content to an with the ability to peek at the content without consuming it.
It is an essential part of content streaming over a TCP connection.
Key Functions of IPeekableContentProvider:
-
Content ProvisionIt provides content to an associated without immediately consuming the content. This allows the consumer to examine the data before processing.
-
Two-Way BindingSupports establishing a two-way binding between the and an , enabling bidirectional communication between the provider and consumer.
-
UnbindingProvides methods for unbinding a content consumer, terminating the association between the provider and consumer.
Gets the associated with this content provider, which allows peeking at the content without consuming it.
Gets the implementor that will be notified through calls when new data is available in the TCPStreamer.
Sets up a two-way binding between this content provider and an . This enables bidirectional communication between the provider and consumer.
The to bind to.
Unbinds the content provider from its associated content consumer. This terminates the association between the provider and consumer.
Unbinds the content provider from a specific content consumer if it is currently bound to that consumer.
The to unbind from.
The IContentConsumer interface represents a consumer of content provided by an . It defines methods for handling received content and connection-related events.
Key Functions of IContentConsumer:
-
Content HandlingDefines methods for handling incoming content, allowing consumers to process data as it becomes available.
-
Connection ManagementProvides event methods to notify consumers of connection closure and error conditions, facilitating graceful handling of connection-related issues.
Gets the associated with this content consumer, which allows access to incoming content.
This method should not be called directly. It is used internally to set the binding between the content consumer and its associated content provider.
The to bind to.
This method should not be called directly. It is used internally to unset the binding between the content consumer and its associated content provider.
Called when new content is available from the associated content provider.
Called when the connection is closed by the remote peer. It notifies the content consumer about the connection closure.
Called when an error occurs during content processing or connection handling. It provides the exception that caused the error.
The that represents the error condition.
Represents the different steps of the negotiation process.
Interface for a peer that participates in the negotiation process.
Gets the list of supported ALPN protocol names for negotiation.
The negotiation instance.
A list of supported ALPN protocol names.
Indicates whether the negotiation process must stop advancing to the next step.
The negotiation instance.
The step that has just finished.
The next step in the negotiation process.
An optional error encountered during negotiation.
true if negotiation must stop for any reason advancing to the next step; otherwise, false.
Handles the evaluation of a proxy negotiation failure.
The negotiation instance.
The error encountered during proxy negotiation.
Indicates whether to resend for authentication.
Handles the negotiation failure.
The negotiation instance.
The error encountered during negotiation.
Handles the successful completion of negotiation.
The negotiation instance.
The negotiated stream.
The TCP streamer.
The negotiated protocol.
Represents the parameters for a negotiation.
Optional proxy instance must be used during negotiation.
Sets a value indicating whether to create a proxy tunnel.
Sets the target URI for negotiation.
Sets a value indicating whether to negotiate TLS.
Sets the cancellation token for negotiation.
Sets the that can be used during the negotiation process.
Optional logging context for debugging purposes.
The Negotiator class acts as a central coordinator for the negotiation of network connections, abstracting away the complexities of DNS resolution, TCP socket creation, proxy negotiation, and TLS setup.
It allows for customization and extensibility, making it a versatile tool for establishing network connections in a flexible and controlled manner.
- The Negotiator class represents a component responsible for managing the negotiation process. It helps facilitate communication with various network layers, such as DNS resolution, TCP socket creation, proxy handling, and TLS negotiation.
- The class is designed to be flexible and extensible by allowing developers to define a custom negotiation peer that implements the INegotiationPeer interface. This allows developers to adapt the negotiation process to specific requirements and protocols.
- It orchestrates the negotiation process through a series of steps defined by the NegotiationSteps enum. These steps include DNSQuery, TCPRace, Proxy, TLSNegotiation
- Handles errors and exceptions that may occur during negotiation, ensuring graceful fallback or termination of the negotiation process when necessary.
- When TLS negotiation is required, it selects the appropriate TLS negotiation method based on the configuration and available options, such as BouncyCastle or the system's TLS framework.
- If a proxy is configured, the Negotiator class handles proxy negotiation and tunneling, allowing communication through a proxy server.
- It supports cancellation through a CancellationToken, allowing the negotiation process to be canceled if needed.
- The class uses extensive logging to provide information about the progress and outcomes of the negotiation process, making it easier to diagnose and debug issues.
Gets the negotiation peer associated with this negotiator.
Gets the negotiation parameters for this negotiator.
Gets the TCP streamer associated with this negotiator.
Gets the peekable content provider stream associated with this negotiator.
Initializes a new instance of the Negotiator class.
The negotiation peer for this negotiator.
The negotiation parameters for this negotiator.
Starts the negotiation process.
Handles cancellation requests during negotiation.
A non-blocking-read stream over a TCPStreamer that buffers the received bytes from the network in a Peekable stream.
Contains settings related to TCP Ringmaster, which manages and optimizes TCP connections.
The maximum number of simultaneous TCP racers. Racers are used to establish and manage connections.
Determines whether to shuffle addresses before assigning racing lanes.
Callback to implement a custom address shuffle algorithm. When assigned, no plugin-defined shuffle algorithm will be executed.
It must be thread-safe.
The granularity of cancellation checking for TCP races. It specifies the time interval for checking if a race should be canceled.
Represents the result of a TCP race competition, including the winning socket or an error.
The socket that won the race competition, if available.
The error encountered during the race competition, if any.
Initializes a new instance of the class with the winning socket and an error, if any.
The winning socket of the race competition, if available.
The error encountered during the race competition, if any.
Represents a TCP race competition with parameters and status.
The parameters for the TCP race competition.
The index of the next address to connect to.
The number of running lanes in the competition.
Represents a racing lane in a TCP race competition.
The associated race and its parameters.
The index of the address to connect to.
The index of the racing lane.
The socket used for the racing lane.
Contains parameters and settings for a TCP race competition to establish connections.
An array of DNS IP addresses to be used for racing to establish a connection.
The hostname to connect to.
The port to connect to.
The cancellation token used to cancel the TCP race competition.
A callback function to announce the winner of the TCP race competition.
The TCPRaceParameters used for the race competition.
The result of the race competition, including the winning socket or an error.
Optional context for logging and tracking purposes.
A user-defined tag associated with the TCP race parameters.
TCPRingmaster provides a method called , which is used to initiate a competition among multiple TCP connections.
Each connection attempt races against the others to establish a connection, and the first successful connection is considered the winner.
The class allows to specify a callback function (through ) that gets invoked when a winning connection is established or when the competition is canceled.
This callback can be used to take action based on the competition outcome.
Additionally it includes logic for optimizing the order in which connection attempts are made:
- It can shuffle the order of addresses to improve the chances of quickly finding a working address.
- It handles scenarios where some addresses may not be working and prioritizes working addresses.
Starts a TCP race competition to establish connections based on the provided parameters.
The parameters and settings for the TCP race competition.
Inplace shuffles addresses.
The array of to shuffle.
The ITCPStreamerContentConsumer interface represents a specialized content consumer for use with . It offers methods for writing data to the streamer and handling content-related events.
Key Functions of ITCPStreamerContentConsumer:
-
Data WritingProvides methods to write data to the associated instance, allowing content to be sent over the TCP connection.
-
Content HandlingDefines event methods for notifying consumers when new content is available, the connection is closed, or errors occur during data transfer.
Writes the specified data buffer to the associated instance. The data is copied into a new buffer and passed to the streamer for transmission.
The byte array containing the data to be written.
The zero-based byte offset in the buffer from which to begin writing.
The number of bytes to write from the buffer.
Writes the specified directly to the associated instance. The content of the buffer is passed to the streamer for transmission, and the ownership of the buffer is transferred to the too.
The containing the data to be written.
Called when new content is available from the associated instance.
The instance providing the content.
Called when the connection is closed by the remote peer. It notifies the content consumer about the connection closure.
The instance for which the connection is closed.
Called when an error occurs during content processing or connection handling. It provides the instance and the that caused the error.
The instance where the error occurred.
The that represents the error condition.
The TCPStreamer class is a versatile component that abstracts the complexities of TCP communication, making it easier to handle data streaming between networked applications or devices. It ensures reliable and efficient data transfer while handling various aspects of network communication and error management.
TCPStreamer serves several key functions:
-
Data StreamingIt enables the streaming of data between two endpoints over a TCP connection, ideal for scenarios involving the transfer of large data volumes in manageable chunks.
-
Buffer ManagementThe class efficiently manages buffering for both incoming and outgoing data, ensuring smooth and efficient data transfer.
-
Asynchronous CommunicationUtilizing asynchronous communication patterns, it supports non-blocking operations, essential for applications requiring concurrent data processing.
-
Error HandlingComprehensive error-handling mechanisms address exceptions that may occur during TCP communication, enhancing robustness in the face of network issues or errors.
-
Resource ManagementIt handles memory buffer management and resource disposal when the TCP connection is closed or the class is disposed.
-
Integration with HeartbeatImplementing the interface, it can be seamlessly integrated into systems using heartbeat mechanisms for network connection monitoring and management.
Gets or sets the content consumer that interacts with this instance, allowing data to be written to the streamer for transmission.
Gets the underlying associated with this instance.
Gets the optional associated with this instance, facilitating logging and diagnostics.
Gets a value indicating whether the TCP connection is closed.
Gets the minimum receive buffer size for the TCP socket.
Gets the total length of buffered data for reading from the stream.
Gets or sets the maximum amount of buffered data allowed for reading from the stream.
Gets or sets the maximum amount of buffered data allowed for writing to the stream.
Initializes a new instance of the TCPStreamer class with the specified and parent .
The underlying representing the TCP connection.
The optional parent for logging and diagnostics.
Dequeues received data from the stream's buffer and returns a containing the data.
A containing the received data.
Begins receiving data from the TCP connection asynchronously. This method ensures that only one receive operation happens at a time.
When calling this method, it ensures that there is only one active receive operation at a time, preventing overlapping receives. This optimization helps prevent data loss and improves the reliability of the receive process.
Enqueues data to be sent over the TCP connection. The data is added to the stream's outgoing buffer for transmission.
The containing the data to be sent.
Disposes of the instance, releasing associated resources.
Closes the TCP connection gracefully and performs cleanup operations.
Implements pooling logic for instances.
Setting this property to false the pooling mechanism can be disabled.
Buffer entries that released back to the pool and older than this value are moved when next maintenance is triggered.
How often pool maintenance must run.
This is a modified MemoryStream class to use VariableSizedBufferPool
A PeekableStream implementation that also implements the interface too.
This will set Consumer to null.
Set Consumer to null if the current one is the one passed in the parameter.
Wrapper of multiple streams. Writes and reads are both supported. Read goes trough all the streams.
A custom buffer stream implementation that will not close the underlying stream.
TCPConnector has to know what protocol got negotiated
an implementation of the AES (Rijndael), from FIPS-197.
For further details see: http://csrc.nist.gov/encryption/aes/.
This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
http://fp.gladman.plus.com/cryptography_technology/rijndael/
There are three levels of tradeoff of speed vs memory
Because java has no preprocessor, they are written as three separate classes from which to choose
The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
and 4 for decryption.
The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
adding 12 rotate operations per round to compute the values contained in the other tables from
the contents of the first.
The slowest version uses no static tables at all and computes the values in each round.
This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
Calculate the necessary round keys
The number of calculations depends on key size and block size
AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
This code is written assuming those are the only possible values
default constructor - 128 bit block size.
initialise an AES cipher.
@param forEncryption whether or not we are for encryption.
@param parameters the parameters required to set up the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
NIST Special Publication 800-38C.
Note: this mode is a packet mode - it needs all the data up front.
Basic constructor.
@param cipher the block cipher to be used.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Returns a byte array containing the mac calculated as part of the
last encrypt or decrypt operation.
@return the last mac calculated.
Process a packet of data for either CCM decryption or encryption.
@param in data for processing.
@param inOff offset at which data starts in the input array.
@param inLen length of the data in the input array.
@return a byte array containing the processed input..
@throws IllegalStateException if the cipher is not appropriately set up.
@throws InvalidCipherTextException if the input data is truncated or the mac check fails.
Process a packet of data for either CCM decryption or encryption.
@param in data for processing.
@param inOff offset at which data starts in the input array.
@param inLen length of the data in the input array.
@param output output array.
@param outOff offset into output array to start putting processed bytes.
@return the number of bytes added to output.
@throws IllegalStateException if the cipher is not appropriately set up.
@throws InvalidCipherTextException if the input data is truncated or the mac check fails.
@throws DataLengthException if output buffer too short.
Implementation of Daniel J. Bernstein's ChaCha stream cipher.
Creates a 20 rounds ChaCha engine.
Implementation of Daniel J. Bernstein's ChaCha stream cipher.
Creates a 20 rounds ChaCha engine.
Creates a ChaCha engine with a specific number of rounds.
the number of rounds (must be an even number).
Implements the Galois/Counter mode (GCM) detailed in NIST Special Publication 800-38D.
MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits.
Sizes less than 96 are not recommended, but are supported for specialized applications.
Poly1305 message authentication code, designed by D. J. Bernstein.
Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
effective key bits) used in the authenticator.
The polynomial calculation in this implementation is adapted from the public domain poly1305-donna-unrolled C implementation
by Andrew M (@floodyberry).
Polynomial key
Polynomial key
Polynomial key
Polynomial key
Polynomial key
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Precomputed 5 * r[1..4]
Encrypted nonce
Encrypted nonce
Encrypted nonce
Encrypted nonce
Current block of buffered input
Current offset in input buffer
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Polynomial accumulator
Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
Constructs a Poly1305 MAC, using a 128 bit block cipher.
Initialises the Poly1305 MAC.
a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.
Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
Constants
Creates a 20 round Salsa20 engine.
Creates a Salsa20 engine with a specific number of rounds.
the number of rounds (must be an even number).
Implements the Segmented Integer Counter (SIC) mode on top of a simple
block cipher.
Basic constructor.
@param c the block cipher to be used.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
A generic TLS 1.2 AEAD cipher.
A generic TLS 1.0-1.2 block cipher. This can be used for AES or 3DES for example.
implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
Basic constructor.
@param cipher the block cipher to be used as the basis of chaining.
return the underlying block cipher that we are wrapping.
@return the underlying block cipher that we are wrapping.
Initialise the cipher and, possibly, the initialisation vector (IV).
If an IV isn't passed as part of the parameter, the IV will be all zeros.
@param forEncryption if true the cipher is initialised for
encryption, if false for decryption.
@param param the key and other data required by the cipher.
@exception ArgumentException if the parameters argument is
inappropriate.
return the algorithm name and mode.
@return the name of the underlying algorithm followed by "/CBC".
return the block size of the underlying cipher.
@return the block size of the underlying cipher.
reset the chaining vector back to the IV and reset the underlying
cipher.
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
Based on the download from http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-%28for-json%29.html
This class encodes and decodes JSON strings.
Spec. details, see http://www.json.org/
JSON uses Arrays and Objects. These correspond here to the datatypes List and Dictionary.
All numbers are parsed to doubles.
Parses the string json into a value
A JSON string.
A List, a Dictionary, a double, a string, null, true, or false
Parses the string json into a value; and fills 'success' with the successfullness of the parse.
A JSON string.
Successful parse?
A List, a Dictionary, a double, a string, null, true, or false
Converts a Dictionary / List object into a JSON string
A Dictionary / List
A JSON encoded string, or null if object 'json' is not serializable
Determines whether the json contains an element that has the specified key.
The key to locate in the json.
true if the json contains an element that has the specified key; otherwise, false.
A builder struct for constructing an instance of the HTTPCache class with optional configuration options and callbacks.
Sets the configuration options for the HTTP cache.
The containing cache configuration settings.
The current instance for method chaining.
Sets the configuration options for the HTTP cache using an .
An for building cache configuration settings.
The current instance for method chaining.
Sets a callback delegate to be executed before caching of an entity begins.
The delegate to be executed before caching starts.
The current instance for method chaining.
Builds and returns an instance of the with the specified configuration options and callback delegate.
An instance configured with the specified options and callback.
A builder struct for constructing an instance of with optional configuration settings.
Sets the maximum cache size for the HTTP cache.
The maximum size, in bytes, that the cache can reach.
The current instance for method chaining.
Sets the maximum duration for which cached entries will be retained.
By default all entities (even stalled ones) are kept cached until they are evicted to make room for new, fresh ones.
The maximum age for cached entries to be retained.
The current instance for method chaining.
Builds and returns an instance of with the specified configuration settings.
An instance configured with the specified settings.
Types of errors that can occur during cache validation.
Indicates that no error has occurred during validation.
Indicates a server error has occurred during validation.
Indicates a connection error has occurred during validation.
Represents a delegate that can be used to perform actions before caching of an entity begins.
The HTTP method used in the request.
The URI of the HTTP request.
The HTTP status code of the response.
The HTTP response headers.
An optional logging context for debugging.
Represents a delegate that can be used to handle cache size change events.
Manages caching of HTTP responses and associated metadata.
The `HTTPCache` class provides a powerful caching mechanism for HTTP responses in Unity applications.
It allows you to store and retrieve HTTP responses efficiently, reducing network requests and improving
the performance of your application. By utilizing HTTP caching, you can enhance user experience, reduce
bandwidth usage, and optimize loading times.
Key features:
- Optimal User ExperienceUsers experience faster load times and smoother interactions, enhancing user satisfaction.
- Efficient CachingIt enables efficient caching of HTTP responses, reducing the need to fetch data from the network repeatedly.
- Improved PerformanceCaching helps improve the performance of your Unity application by reducing latency and decreasing loading times.
- Bandwidth OptimizationBy storing and reusing cached responses, you can minimize bandwidth usage, making your application more data-friendly.
- Offline AccessCached responses allow your application to function even when the device is offline or has limited connectivity.
- Reduced Server LoadFewer network requests mean less load on your server infrastructure, leading to cost savings and improved server performance.
- Manual Cache ControlYou can also manually control caching by adding, removing, or updating cached responses.
Constants defining folder and file names used in the HTTP cache storage.
This is the reversed domain the plugin uses for file paths when it have to load content from the local cache.
Event that is triggered when the size of the cache changes.
Gets the options that define the behavior of the HTTP cache.
Gets the current size of the HTTP cache in bytes.
Called before the plugin calls to decide whether the content will be cached or not.
Initializes a new instance of the HTTPCache class with the specified cache options.
The HTTP cache options specifying cache size and deletion policy.
Calculates a unique hash identifier based on the HTTP method and URI.
The HTTP method used in the request.
The URI of the HTTP request.
A unique hash identifier for the combination of method and URI.
Generates the directory path based on the given hash where cached content is stored.
A unique hash identifier for the cached content, returned by .
The directory path for the cached content associated with the given hash.
Generates the file path for the header cache associated with the given hash.
A unique hash identifier for the cached content, returned by .
The file path for the header cache associated with the given hash.
Generates the file path for the content cache associated with the given hash.
A unique hash identifier for the cached content, returned by .
The file path for the content cache associated with the given hash.
Checks whether cache files (header and content) associated with the given hash exist.
A unique hash identifier for the cached content.
true if both header and content cache files exist, otherwise false.
Sets up validation headers on an HTTP request if a locally cached response exists.
The to which validation headers will be added.
If necessary tries to make enough space in the cache by calling Maintain.
Initiates the caching process for an HTTP response, creating an if caching is enabled and all predconditions are met.
The method used to fetch the response.
The URI for the response.
The HTTP status code of the response.
The HTTP headers of the response.
An optional logging context for debugging.
An instance for writing the response content to the cache, or null if caching is not enabled or not possible.
Finalizes the caching process and takes appropriate actions based on the completion status.
The instance representing the caching operation.
A boolean indicating whether the caching process completed without issues.
An optional logging context for debugging.
Initiates the process of reading cached content associated with a given hash. Call BeginReadContent to acquire a Stream object that points to the cached resource.
A hash from identifying the resource.
An optional
A stream for reading the cached content, or null if the content could not be read (the resource isn't cached or currently downloading).
Finalizes the process of reading cached content associated with a given hash.
The unique hash identifier for the cached content.
An optional logging context for debugging.
Deletes a cached entry identified by the given hash, including its associated header and content files.
The unique hash identifier for the cached entry to be deleted.
An optional logging context for debugging.
Refreshes the headers of a cached HTTP response with new headers.
A unique hash identifier for the cached response from a call.
A dictionary of new headers to replace or merge with existing headers.
Used by the plugin to add an addition logging context for debugging. It can be null.
true if the headers were successfully refreshed; otherwise, false.
Checks whether the caches resource identified by the hash is can be served from the local store with the given error conditions.
This check reflects the very current state, even if it returns true, a request might just executing to get a write lock on it to refresh the content.
hash returned by identifying a resource.
Possible error condition that can occur during validation. Servers can provision that certain stalled resources can be served if revalidation fails.
Used by the plugin to add an addition logging context for debugging. It can be null.
true if the cached response can be served without validating it with the origin server; otherwise, false
Redirects a request to a cached entity.
The that will be redirected.
Hash obtained from .
Clears the HTTP cache by removing all cached entries and associated metadata.
Represents a writer for caching HTTP response content.
Gets the parent HTTPCache instance associated with this content writer.
Hash identifying the resource. If fails, it becomes an invalid one.
Expected length of the content. Has a non-zero value only when the server is sending a "content-length" header.
Number of bytes written to the cache.
Context of this cache writer used for logging.
Underlying stream the download bytes are written into.
Writes content to the underlying stream.
holding a reference to the data and containing information about the offset and count of the valid range of data.
Close the underlying stream and invalidate the hash.
Possible lock-states a cache-content can be in.
No reads or writes are happening on the cached content.
There's one writer operating on the cached content. No other writes or reads allowed while this lock is held on the content.
There's at least one read operation happening on the cached content. No writes allowed while this lock is held on the content.
Metadata stored for every cached content. It contains only limited data about the content to help early cache decision making and cache management.
Unique hash of the cached content, generated by .
Size of the stored content in bytes.
When the last time the content is accessed. Also initialized when the initial download completes.
What kind of lock the content is currently in.
Number of readers.
Possible caching flags that a `Cache-Control` header can send.
No special treatment required.
Indicates whether the entity must be revalidated with the server or can be serverd directly from the cache without touching the server when the content is considered stale.
More details can be found here:
If it's true, the client always have to revalidate the cached content when it's stale.
More details can be found here:
Cached content associated with a .
This is NOT the cached content received from the server! It's for storing caching values to decide on how the content can be used.
ETag of the entity.
More details can be found here:
LastModified date of the entity. Use ToString("r") to convert it to the format defined in RFC 1123.
When the cache will expire.
More details can be found here:
The age that came with the response
More details can be found here:
Maximum how long the entry should served from the cache without revalidation.
More details can be found here:
The Date that came with the response.
More details can be found here:
It's a grace period to serve staled content without revalidation.
More details can be found here:
Allows the client to serve stale content if the server responds with an 5xx error.
More details can be found here:
bool values packed into one single flag.
The value of the clock at the time of the request that resulted in the stored response.
More details can be found here:
The value of the clock at the time the response was received.
Represents the configuration options for the HTTP cache.
Gets or sets the maximum duration for which cached entries will be retained.
Gets or sets the maximum size, in bytes, that the cache can reach.
Initializes a new instance of the class with default settings.
Initializes a new instance of the class with custom settings.
The maximum age for cached entries to be retained.
The maximum size, in bytes, that the cache can reach.
The Cookie implementation based on RFC-6265.
The name of the cookie.
The value of the cookie.
The Date when the Cookie is registered.
When this Cookie last used in a request.
The Expires attribute indicates the maximum lifetime of the cookie, represented as the date and time at which the cookie expires.
The user agent is not required to retain the cookie until the specified date has passed.
In fact, user agents often evict cookies due to memory pressure or privacy concerns.
The Max-Age attribute indicates the maximum lifetime of the cookie, represented as the number of seconds until the cookie expires.
The user agent is not required to retain the cookie for the specified duration.
In fact, user agents often evict cookies due to memory pressure or privacy concerns.
If a cookie has neither the Max-Age nor the Expires attribute, the user agent will retain the cookie until "the current session is over".
The Domain attribute specifies those hosts to which the cookie will be sent.
For example, if the value of the Domain attribute is "example.com", the user agent will include the cookie
in the Cookie header when making HTTP requests to example.com, www.example.com, and www.corp.example.com.
If the server omits the Domain attribute, the user agent will return the cookie only to the origin server.
The scope of each cookie is limited to a set of paths, controlled by the Path attribute.
If the server omits the Path attribute, the user agent will use the "directory" of the request-uri's path component as the default value.
The Secure attribute limits the scope of the cookie to "secure" channels (where "secure" is defined by the user agent).
When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is
transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS)).
The HttpOnly attribute limits the scope of the cookie to HTTP requests.
In particular, the attribute instructs the user agent to omit the cookie when providing access to
cookies via "non-HTTP" APIs (such as a web browser API that exposes cookies to scripts).
SameSite prevents the browser from sending this cookie along with cross-site requests.
The main goal is mitigate the risk of cross-origin information leakage.
It also provides some protection against cross-site request forgery attacks.
Possible values for the flag are lax or strict.
More details can be found here:
- SameSite cookies explained
Guess the storage size of the cookie.
The Cookie Jar implementation based on RFC 6265.
Maximum size of the Cookie Jar in bytes. It's default value is 10485760 (10 MB).
Returns true if File apis are supported.
The plugin will delete cookies that are accessed this threshold ago. Its default value is 7 days.
If this property is set to true, then new cookies treated as session cookies and these cookies are not saved to disk. Its default value is false.
Enabled or disables storing and handling of cookies. If set to false, HTTPRequests aren't searched for cookies and no cookies will be set for s.
List of the Cookies
Synchronization object for thread safety.
Will set or update all cookies from the response object.
Deletes all expired or 'old' cookies, and will keep the sum size of cookies under the given size.
Saves the Cookie Jar to a file.
Not implemented under Unity WebPlayer
Load previously persisted cookie library from the file.
Returns all Cookies that corresponds to the given Uri.
Will add a new, or overwrite an old cookie if already exists.
Will add a new, or overwrite an old cookie if already exists.
Deletes all cookies from the Jar.
Removes cookies that older than the given parameter.
Removes cookies that matches to the given domain.
Find and return a Cookie and his index in the list.
Abstract base class for concrete connection implementation (HTTP/1, HTTP/2, WebGL, File).
The address of the server that this connection is bound to.
The state of this connection.
If the State is HTTPConnectionStates.Processing, then it holds a HTTPRequest instance. Otherwise it's null.
How much the connection kept alive after its last request processing.
Number of assigned requests to process.
Maximum number of assignable requests.
When we start to process the current request. It's set after the connection is established.
Called when the plugin shuts down immediately.
https://tools.ietf.org/html/draft-thomson-hybi-http-timeout-03
Test servers: http://tools.ietf.org/ http://nginx.org/
A host sets the value of the "timeout" parameter to the time that the host will allow an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The "max" parameter has been used to indicate the maximum number of requests that would be made on the connection.This parameter is deprecated.Any limit on requests can be enforced by sending "Connection: close" and closing the connection.
Static helper class to handle cases where the plugin has to do additional logic based on the received response. These are like connection management, handling redirections, loading from local cache, authentication challanges, etc.
Called when the whole response received
Number of assigned requests to process.
Maximum number of assignable requests
An HTTP 1.1 response implementation that can utilize a peekable stream.
Its main entry point is the ProcessPeekable method that should be called after every chunk of data downloaded.
Settings for HTTP/2 connections when the Connect protocol is available.
Set it to false to disable Websocket Over HTTP/2 (RFC 8441). It's true by default.
Set it to disable fallback logic from the Websocket Over HTTP/2 implementation to the 'old' HTTP/1 implementation when it fails to connect.
Settings for HTTP/2 connections.
When set to false, the plugin will not try to use HTTP/2 connections.
Maximum size of the HPACK header table.
Maximum concurrent http2 stream on http2 connection will allow. Its default value is 128;
Initial window size of a http2 stream. Its default value is 65535, can be controlled through the HTTPRequest's DownloadSettings object.
Global window size of a http/2 connection. Its default value is the maximum possible value on 31 bits.
Maximum size of a http2 frame.
Not used.
With HTTP/2 only one connection will be open so we can keep it open longer as we hope it will be reused more.
Time between two ping messages.
Timeout to receive a ping acknowledgement from the server. If no ack reveived in this time the connection will be treated as broken.
Set to true to enable RFC 8441 "Bootstrapping WebSockets with HTTP/2" (https://tools.ietf.org/html/rfc8441).
Settings for WebSockets over HTTP/2 (RFC 8441)
https://tools.ietf.org/html/rfc7838#section-4
Settings Registry
Allows the sender to inform the remote endpoint of the maximum size of the
header compression table used to decode header blocks, in octets.
The encoder can select any size equal to or less than this value
by using signaling specific to the header compression format inside a header block (see [COMPRESSION]).
The initial value is 4,096 octets.
This setting can be used to disable server push (Section 8.2).
An endpoint MUST NOT send a PUSH_PROMISE frame if it receives this parameter set to a value of 0.
An endpoint that has both set this parameter to 0 and had it acknowledged MUST treat the receipt of a
PUSH_PROMISE frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
The initial value is 1, which indicates that server push is permitted.
Any value other than 0 or 1 MUST be treated as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
Indicates the maximum number of concurrent streams that the sender will allow. This limit is directional:
it applies to the number of streams that the sender permits the receiver to create.
Initially, there is no limit to this value. It is recommended that this value be no smaller than 100,
so as to not unnecessarily limit parallelism.
A value of 0 for SETTINGS_MAX_CONCURRENT_STREAMS SHOULD NOT be treated as special by endpoints.
A zero value does prevent the creation of new streams;
however, this can also happen for any limit that is exhausted with active streams.
Servers SHOULD only set a zero value for short durations; if a server does not wish to accept requests,
closing the connection is more appropriate.
Indicates the sender's initial window size (in octets) for stream-level flow control.
The initial value is 2^16-1 (65,535) octets.
This setting affects the window size of all streams (see Section 6.9.2).
Values above the maximum flow-control window size of 2^31-1 MUST be treated as a connection error
(Section 5.4.1) of type FLOW_CONTROL_ERROR.
Indicates the size of the largest frame payload that the sender is willing to receive, in octets.
The initial value is 2^14 (16,384) octets.
The value advertised by an endpoint MUST be between this initial value and the maximum allowed frame size
(2^24-1 or 16,777,215 octets), inclusive.
Values outside this range MUST be treated as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
This advisory setting informs a peer of the maximum size of header list that the sender is prepared to accept, in octets.
The value is based on the uncompressed size of header fields,
including the length of the name and value in octets plus an overhead of 32 octets for each header field.
For any given request, a lower limit than what is advertised MAY be enforced. The initial value of this setting is unlimited.
https://tools.ietf.org/html/rfc8441
Upon receipt of SETTINGS_ENABLE_CONNECT_PROTOCOL with a value of 1, a client MAY use the Extended CONNECT as defined in this document when creating new streams.
Receipt of this parameter by a server does not have any impact.
A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter with the value of 0 after previously sending a value of 1.
Allow endpoints to omit or ignore HTTP/2 priority signals.
Extensible Prioritization Scheme for HTTP
Represents a registry for HTTP/2 settings.
Gets a value indicating whether the registry is read-only.
Event triggered when a setting changes.
Indexer to get or set values based on an key.
The setting key.
The value associated with the given setting key.
Gets a value indicating whether any setting has changed.
Initializes a new instance of the HTTP2SettingsRegistry class.
The parent .
Whether this registry is read-only.
Whether to treat the registry as if a setting has already changed.
Merges the specified settings into the current registry.
The settings to merge.
Merges settings from another HTTP2SettingsRegistry into the current registry.
The registry to merge settings from.
Creates a new HTTP/2 frame based on the current registry settings.
The logging context.
A new HTTP/2 frame.
Class to manager local and remote HTTP/2 settings.
This is the ACKd or default settings that we sent to the server.
This is the setting that can be changed. It will be sent to the server ASAP, and when ACKd, it will be copied
to MySettings.
Settings of the remote peer
Implements an HTTP/2 logical stream.
This flag is checked by the connection to decide whether to do a new processing-frame sending round before sleeping until new data arrives
Next interaction scheduled by the stream relative to *now*. Its default is TimeSpan.MaxValue == no interaction.
Constructor to create a client stream.
A pre-generated table entry in a Huffman-Tree.
It must return 0 or 1 at bit index. Indexing will be relative to the Bits representing the current code. Idx grows from left to right. Idx must be between [1..Bits].
Possible states of a Http Connection.
The ideal lifecycle of a connection that has KeepAlive is the following: Initial => [Processing => WaitForRecycle => Free] => Closed.
This Connection instance is just created.
This Connection is processing a request
Wait for the upgraded protocol to shut down.
The Connection is finished processing the request, it's waiting now to deliver it's result.
The request result's delivered, it's now up to processing again.
If it's not a KeepAlive connection, or something happened, then we close this connection and remove from the pool.
Same as the Closed state, but processing this request requires resending the last processed request too.
Represents and manages a connection to a server.
Number of assigned requests to process.
Maximum number of assignable requests.
Returns true if an error state is set to the request and the connection is closing.
Defines an interface for notifying connections when space becomes available in a buffer for downloading data.
Connections implementating of this interface are used to signal their internal logic that they can transfer data into the available buffer space.
Notifies a connection that space has become available in the buffer for downloading data.
When invoked, this method indicates to a connection that it can transfer additional data into the buffer for further processing.
The instance associated with the buffer.
Common interface for implementations that will coordinate request processing inside a connection.
Number of assigned requests to process.
Maximum number of assignable requests.
An immediate shutdown request that called only on application closure.
Interface for signaling upload threads.
A instance for debugging purposes.
To help implementors log in the IThreadSignaler's context,
the interface implementors must make their logging context accessible.
Signals the associated thread to resume or wake up.
Moves any added asterisk(*) to the end of the list.
Delegate for creating a TLS 1.3 client instance.
The URI of the request.
A list of supported TLS ALPN protocols.
The logging context for the operation.
A TLS 1.3 client instance.
Settings for HTTP requests.
The timeout for establishing a connection.
The maximum time allowed for the request to complete.
Settings for HTTP/1 connections.
Indicates whether the connection should be open after receiving the response.
If set to true, internal TCP connections will be reused whenever possible.
If making rare requests to the server, it's recommended to change this to false.
The maximum time a connection can remain idle before being closed.
Indicates whether the upload thread should use a ThreadPool thread instead of creating and using a Thread.
The plugin tries to use ThreadPool threads for known short-living uploads like requests without upload body. With ForceUseThreadPool all HTTP/1 requests, including long uploads or downloads can be forced to use ThreadPool threads.
Delegate for selecting a client certificate.
The target host.
A collection of local certificates.
The remote certificate.
An array of acceptable certificate issuers.
The selected X.509 certificate.
Available TLS handlers.
To use the 3rd party BouncyCastle implementation.
To use .net's SslStream.
Settings for Bouncy Castle TLS.
Delegate for creating a TLS 1.3 client instance using Bouncy Castle.
The default TLS 1.3 client factory.
The URI of the request.
A list of supported TLS ALPN protocols.
The logging context for the operation.
A TLS 1.3 client instance.
Settings for .NET's SslStream based handler.
The supported TLS versions.
Indicates whether to check certificate revocation.
The default certification validator.
Delegate for providing a client certificate.
Settings for TLS.
The selected TLS handler.
Settings for Bouncy Castle.
.NET's SslStream settings.
Settings for s.
The maximum number of connections allowed per host variant.
Factor used when calculations are made whether to open a new connection to the server or not.
It has an effect on HTTP/2 connections only.
Higher values (gte 1.0f) delay, lower values (lte 1.0f) bring forward creation of new connections.
Factory function to generate HostVariant or descendent instances.
Factory function to generate custom connection implementations.
Represents the low-level TCP buffer settings for connections.
Gets or sets the size of the TCP write buffer in bytes.
Default value is 1 MiB.
This determines the maximum amount of data that that the class can buffer up if it's already in a write operation.
Increasing this value can potentially improve write performance, especially for large messages or data streams.
However, setting it too high might consume a significant amount of memory, especially if there are many active connections.
The size of the TCP write buffer in bytes.
Gets or sets the size of the read buffer in bytes.
The size of the read buffer in bytes.
Default value is 1 MiB.
This determines the maximum amount of data that low level streams and the can buffer up for consuming by higher level layers.
Adjusting this value can affect the read performance of the application.
Like the write buffer, setting this too high might be memory-intensive, especially with many connections.
It's advised to find a balance that suits the application's needs and resources.
Contains settings that can be associated with a specific host or host variant.
Gets or sets the low-level TCP buffer settings for connections associated with the host or host variant.
The low-level TCP buffer settings.
These settings determine the buffer sizes for reading from and writing to TCP connections,
which can impact performance and memory usage.
Settings related to HTTP requests made to this host or host variant.
Settings related to HTTP/1.x connection behavior.
Settings related to TCP Ringmaster used in non-webgl platforms.
Settings related to HTTP/2 connection behavior.
Settings related to TLS (Transport Layer Security) behavior.
Settings related to behavior.
Host Settings Hierarchy for the following hosts, settings are stored as leafs:
*.com
*.example.com
example.com
'*' matches one or more subdomains so *.example.com
- matches a.example.com and a.b.example.com
- but doesn't match example.com!
[com] [localhost] [org] [*]
+------+------+ | | |
| | [setting] [*] [setting]
[example] [*] |
/ \ | [setting]
[b] [setting] [setting]
|
[a]
|
[setting]
Manages host-specific settings for HTTP requests based on hostnames.
The HostSettingsManager is a powerful tool for fine-tuning HTTP request and connection behaviors
on a per-host basis. It enables you to define custom settings for specific hostnames
while maintaining default settings for all other hosts. This level of granularity allows you to
optimize and customize HTTP requests for different endpoints within your application.
When host-specific settings are not found for a given host variant, the default
associated with the "*" host will be returned.
Initializes a new instance of the class with default settings for all hosts ("*").
Adds default settings for the host part of the specified URI. This is equivalent to calling with the a new .
The URI for which default settings should be applied. Only the host part of the URI will be used.
A instance with default values.
Adds default settings for the the specified host name. This is equivalent to calling with the a new .
The hostname for which default settings should be applied.
A instance with default values.
Adds host-specific settings for the host part of the specified URI.
The URI for which settings should be applied. Only the host part of the URI will be used.
The to apply.
Adds host-specific settings for the specified hostname.
The hostname for which settings should be applied.
The to apply.
Thrown when either the hostname or settings is null.
Thrown when the hostname contains more than one asterisk ('*').
Gets for the host part of the specified . Returns the default settings associated with "*" when not found.
The for which settings should be retrieved. Only the host part of the variant will be used.
The host settings for the specified host variant or the default settings for "*" if not found.
Gets for the host part of the specified . Returns the default settings associated with "*" when not found.
The for which settings should be retrieved. Only the host part of the host key will be used.
The host settings for the specified host key or the default settings for "*" if not found.
Gets for the host part of the specified . Returns the default settings associated with "*" when not found.
The for which settings should be retrieved. Only the host part of the URI will be used.
The host settings for the specified URI or the default settings for "*" if not found.
Gets for the host part of the specified hostname. Returns the default settings associated with "*" when not found.
The hostname for which settings should be retrieved. Only the host part of the hostname will be used.
The host settings for the specified hostname or the default settings for "*" if not found.
Thrown when the hostname is null.
Clears all host-specific settings and resetting the default ("*") with default values.
The struct represents a unique key for identifying hosts based on their and .
The struct is designed to uniquely identify a host based on its URI (Uniform Resource Identifier) and optional proxy settings.
It provides a way to create, compare, and hash host keys, enabling efficient host variant management in the .
Key features of the struct include:
-
Uniqueness
Each is guaranteed to be unique for a specific host, considering both the URI and proxy settings.
-
Hashing
The struct provides a method to calculate a hash code for a , making it suitable for use as a dictionary key.
-
Creation
You can create a instance from a and optional .
Usage of the struct is typically handled internally by the BestHTTP library to manage unique hosts and optimize resource usage.
Developers can use it when dealing with host-specific operations or customization of the library's behavior.
Gets the URI (Uniform Resource Identifier) associated with the host.
Gets the proxy settings associated with the host.
Gets the unique hash key for the host.
Gets the host name from the URI or "file" if the URI is a file URI.
Initializes a new instance of the struct with the specified URI and proxy settings.
The URI of the host.
The proxy settings associated with the host, or null if no proxy is used.
Creates a instance from an HTTP request.
The HTTP request from which to extract the current URI and proxy settings.
A representing the host of the HTTP request.
Creates a instance from a URI and proxy settings.
The URI of the host.
The proxy settings associated with the host, or null if no proxy is used.
A representing the host with the given URI and proxy settings.
The class provides centralized management for objects associated with HTTP requests and connections.
The class acts as a central registry for managing objects, each associated with a unique .
It facilitates the creation, retrieval, and management of instances based on HTTP requests and connections.
A represents a specific host and port combination (e.g., "http://example.com:80" or "https://example.com:443") and
manages the connections and request queues for that host. The class ensures that a single instance is used for
each unique host, helping optimize resource usage and connection pooling.
Key features of the class include:
-
Creation and Retrieval
The class allows you to create and retrieve instances based on HTTP requests, connections, or .
It ensures that a single is used for each unique host.
-
Queue Management
The manages the queue of pending requests for each , ensuring efficient request processing.
-
Connection Management
The class handles the management of connections associated with objects, including recycling idle connections,
removing idle connections, and shutting down connections when needed.
Usage of the class is typically transparent to developers and is handled internally by the Best HTTP library. However,
it provides a convenient and efficient way to manage connections and requests when needed.
Dictionary to store - mappings.
Gets the associated with an HTTP request.
The HTTP request.
The for the request's host.
Gets the associated with a connection.
The HTTP connection.
The for the connection's host.
Gets the associated with a HostKey.
The HostKey for which to get the HostVariant.
The for the specified HostKey.
Removes all idle connections for all hosts.
Tries to send queued requests for all hosts.
Shuts down all connections for all hosts.
Clears all hosts and their associated variants.
An enumeration representing the protocol support for a host.
Protocol support is unknown or undetermined.
The host supports HTTP/1.
The host supports HTTP/2.
This is a file-based host.
The HostVariant class is a critical component in managing HTTP connections and handling HTTP requests for a specific host. It maintains a queue of requests and a list of active connections associated with the host, ensuring efficient utilization of available resources. Additionally, it supports protocol version detection (HTTP/1 or HTTP/2) for optimized communication with the host.
- It maintains a queue of requests to ensure efficient and controlled use of available connections.
- It supports HTTP/1 and HTTP/2 protocol versions, allowing requests to be sent using the appropriate protocol based on the host's protocol support.
- Provides methods for sending requests, recycling connections, managing connection state, and handling the shutdown of connections and the host variant itself.
- It includes logging for diagnostic purposes, helping to monitor and debug the behavior of connections and requests.
In summary, the HostVariant class plays a central role in managing HTTP connections and requests for a specific host, ensuring efficient and reliable communication with that host while supporting different protocol versions.
Represents the HTTP methods used in HTTP requests.
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the
entity in the response and not the source text of the process, unless that text happens to be the output of the process.
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.
This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself.
This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
- Providing a block of data, such as the result of submitting a form, to a data-handling process;
- Extending a database through an append operation.
The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI.
The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it,
a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be identified by a URI. In this case,
either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.
The PUT method requests that the enclosed entity be stored under the supplied Request-URI.
If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.
If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent,
the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response.
If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.
If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem.
The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server.
The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully.
However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content)
if the action has been enacted but the response does not include an entity.
The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI.
The set of changes is represented in a format called a "patchdocument" identified by a media type. If the Request-URI does not point to an existing resource,
the server MAY create a new resource, depending on the patch document type (whether it can logically modify a null resource) and permissions, etc.
More details can be found here:
- RFC-5789
- When should we use the PATCH HTTP method?
The HTTP TRACE method is used to perform a message loop-back test along the path to the target resource.
The HTTP MERGE method is used to apply modifications to an existing resource.
The MERGE HTTP method is not as commonly used as other methods like GET, POST, or PUT.
It's often used in specific WebDAV (Web Distributed Authoring and Versioning) scenarios.
The HTTP OPTIONS method requests permitted communication options for a given URL or server.
A client can specify a URL with this method, or an asterisk (*) to refer to the entire server.
More details can be found here:
- Mozilla Developer Networks - OPTIONS
The CONNECT method is primarily used in the context of HTTP proxies to establish a network connection through the proxy to a target host.
It is used in the context of the HTTP CONNECT tunneling method.
More details can be found here:
- RFC-2616
- RFC-8441
The HTTP QUERY method is used to retrieve data based on a query parameter or search criteria.
The QUERY method is not a standard HTTP method, and its usage may vary depending on the specific application or API you are working with.
It might be used for querying data or resources with specific parameters.
Details about the QUERY method would depend on the API or service you are interacting with.
You should refer to the documentation or specifications provided by the API/service provider.
More details can be found here:
- HTTP's New Method For Data APIs: HTTP QUERY
- The HTTP QUERY Method (Draft)
Represents an HTTP range that specifies the byte range of a response content, received as an answer for a range-request.
Gets the position of the first byte in the range that the server sent.
Gets the position of the last byte in the range that the server sent.
Gets the total length of the full entity-body on the server. Returns -1 if this length is unknown or difficult to determine.
Gets a value indicating whether the HTTP range is valid.
Delegate for a callback function that is called after the request is fully processed.
Delegate for enumerating headers during request preparation.
The header name.
A list of header values.
Represents an HTTP request that allows you to send HTTP requests to remote servers and receive responses asynchronously.
- Asynchronous HTTP requestsUtilize a Task-based API for performing HTTP requests asynchronously.
- Unity coroutine supportSeamlessly integrate with Unity's coroutine system for coroutine-based request handling.
- HTTP method supportSupport for various HTTP methods including GET, POST, PUT, DELETE, and more.
- Compression and decompressionAutomatic request and response compression and decompression for efficient data transfer.
- Timing informationCollect detailed timing information about the request for performance analysis.
- Upload and download supportSupport for uploading and downloading files with progress tracking.
- CustomizableExtensive options for customizing request headers, handling cookies, and more.
- Redirection handlingAutomatic handling of request redirections for a seamless experience.
- Proxy server supportAbility to route requests through proxy servers for enhanced privacy and security.
- AuthenticationAutomatic authentication handling using authenticators for secure communication.
- Cancellation supportAbility to cancel requests to prevent further processing and release resources.
Creates an HTTP GET request with the specified URL.
The URL of the request.
An HTTPRequest instance for the GET request.
Creates an HTTP GET request with the specified URI.
The URI of the request.
An HTTPRequest instance for the GET request.
Creates an HTTP GET request with the specified URL and registers a callback function to be called
when the request is fully processed.
The URL of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the GET request.
Creates an HTTP GET request with the specified URI and registers a callback function to be called
when the request is fully processed.
The URI of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the GET request.
Creates an HTTP POST request with the specified URL.
The URL of the request.
An HTTPRequest instance for the POST request.
Creates an HTTP POST request with the specified URI.
The URI of the request.
An HTTPRequest instance for the POST request.
Creates an HTTP POST request with the specified URL and registers a callback function to be called
when the request is fully processed.
The URL of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the POST request.
Creates an HTTP POST request with the specified URI and registers a callback function to be called
when the request is fully processed.
The URI of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the POST request.
Creates an HTTP PUT request with the specified URL.
The URL of the request.
An HTTPRequest instance for the PUT request.
Creates an HTTP PUT request with the specified URI.
The URI of the request.
An HTTPRequest instance for the PUT request.
Creates an HTTP PUT request with the specified URL and registers a callback function to be called
when the request is fully processed.
The URL of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the PUT request.
Creates an HTTP PUT request with the specified URI and registers a callback function to be called
when the request is fully processed.
The URI of the request.
A callback function to be called when the request is finished.
An HTTPRequest instance for the PUT request.
Cached uppercase values to save some cpu cycles and GC alloc per request.
The method that how we want to process our request the server.
The original request's Uri.
If redirected it contains the RedirectUri.
A host-key that can be used to find the right host-variant for the request.
The response received from the server.
If an exception occurred during reading of the response stream or can't connect to the server, this will be null!
Download related options and settings.
Upload related options and settings.
Timeout settings for the request.
Retry settings for the request.
Proxy settings for the request.
Redirect settings for the request.
The callback function that will be called after the request is fully processed.
Indicates if is called on this request.
Gets the cancellation token source for this request.
Action called when function is invoked.
Stores any exception that occurs during processing of the request or response.
This property if for debugging purposes as seen here!
Any user-object that can be passed with the request.
Current state of this request.
Timing information about the request.
An IAuthenticator implementation that can be used to authenticate the request.
Out-of-the-box included authenticators are and .
Logging context of the request.
Creates an HTTP GET request with the specified URL.
The URL of the request.
Creates an HTTP GET request with the specified URL and registers a callback function to be called
when the request is fully processed.
The URL of the request.
A callback function to be called when the request is finished.
Creates an HTTP GET request with the specified URL and HTTP method type.
The URL of the request.
The HTTP method type for the request (e.g., GET, POST, PUT).
Creates an HTTP request with the specified URL, HTTP method type, and registers a callback function to be called
when the request is fully processed.
The URL of the request.
The HTTP method type for the request (e.g., GET, POST, PUT).
A callback function to be called when the request is finished.
Creates an HTTP GET request with the specified URI.
The URI of the request.
Creates an HTTP GET request with the specified URI and registers a callback function to be called
when the request is fully processed.
The URI of the request.
A callback function to be called when the request is finished.
Creates an HTTP request with the specified URI and HTTP method type.
The URI of the request.
The HTTP method type for the request (e.g., GET, POST, PUT).
Creates an HTTP request with the specified URI, HTTP method type, and registers a callback function
to be called when the request is fully processed.
The URI of the request.
The HTTP method type for the request (e.g., GET, POST, PUT).
A callback function to be called when the request is finished.
Adds a header-value pair to the Headers. Use it to add custom headers to the request.
AddHeader("User-Agent', "FooBar 1.0")
For the given header name, removes any previously added values and sets the given one.
Removes the specified header and all of its associated values. Returns true, if the header found and succesfully removed.
Returns true if the given head name is already in the .
Returns the first header or null for the given header name.
Returns all header values for the given header or null.
Removes all headers.
Sets the Range header to download the content from the given byte position. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
Start position of the download.
Sets the Range header to download the content from the given byte position to the given last position. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
Start position of the download.
The end position of the download.
Starts processing the request.
Cancels any further processing of the HTTP request.
Resets the request for a state where switching MethodType is possible.
implementation, required for support.
implementation, required for support.
true if the request isn't finished yet.
implementation throwing , required for support.
Disposes of resources used by the HTTPRequest instance.
Represents an exception thrown during or as a result of a Task-based asynchronous HTTP operations.
Gets the status code of the server's response.
Gets the content sent by the server. This is usually an error page for 4xx or 5xx responses.
A collection of extension methods for working with HTTP requests asynchronously using .
Asynchronously sends an HTTP request and retrieves the response as an .
The to send.
A cancellation token that can be used to cancel the operation.
A Task that represents the asynchronous operation. The Task will complete with the retrieved AssetBundle
if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
Asynchronously sends an HTTP request and retrieves the raw .
This method is particularly useful when you want to access the raw response without any specific processing
like converting the data into a string, texture, or other formats. It provides flexibility in handling
the response for custom or advanced use cases.
The to send.
An optional that can be used to cancel the operation.
A that represents the asynchronous operation. The value of TResult is the raw .
If the request completes successfully, the task will return the HTTPResponse. If there's an error during the request or if
the request gets canceled, the task will throw an exception, which can be caught and processed by the calling method.
Thrown if there's an error in the request or if the server returns an error status code.
Asynchronously sends an and retrieves the response content as a string.
The to send.
A cancellation token that can be used to cancel the operation.
A Task that represents the asynchronous operation. The Task will complete with the retrieved string content
if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
Asynchronously sends an and retrieves the response content as a .
The to send.
A cancellation token that can be used to cancel the operation.
A Task that represents the asynchronous operation. The Task will complete with the retrieved
if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
Asynchronously sends an and retrieves the response content as a byte[].
The to send.
A cancellation token that can be used to cancel the operation.
A Task that represents the asynchronous operation. The Task will complete with the retrieved byte[]
if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
Asynchronously sends an and deserializes the response content into an object of type T using JSON deserialization.
The type to deserialize the JSON content into.
The to send.
A cancellation token that can be used to cancel the operation.
A Task that represents the asynchronous operation. The Task will complete with the deserialized object
if the request succeeds and the response content can be deserialized. If the request fails, is canceled, or
the response cannot be deserialized, the Task will complete with an exception.
Possible logical states of a HTTTPRequest object.
Initial status of a request. No callback will be called with this status.
The request queued for processing.
Processing of the request started. In this state the client will send the request, and parse the response. No callback will be called with this status.
The request finished without problem. Parsing the response done, the result can be used. The user defined callback will be called with a valid response object. The request’s Exception property will be null.
The request finished with an unexpected error. The user defined callback will be called with a null response object. The request's Exception property may contain more info about the error, but it can be null.
The request aborted by the client(HTTPRequest’s Abort() function). The user defined callback will be called with a null response. The request’s Exception property will be null.
Connecting to the server timed out. The user defined callback will be called with a null response. The request’s Exception property will be null.
The request didn't finished in the given time. The user defined callback will be called with a null response. The request’s Exception property will be null.
Based on 's "Environment Variables" section.
This is a detector using the .net framework's implementation. It might work not just under Windows but MacOS and Linux too.
More details can be found here:
- HttpClient.DefaultProxy Property
This one just returns with HTTPManager.Proxy,
so when ProgrammaticallyAddedProxyDetector is used in the first place for the ProxyDetector,
HTTPManager.Proxy gets the highest priority.
Interface for custom proxy-detection logic.
Receives the instance this detector has to try to find a proxy.
instance to find a proxy for
A concrete implementation, or null if no proxy could be found.
Possible detection modes the can be in.
In Continuous mode the ProxyDetector will check for a proxy for every request.
This mode will cache the first Proxy found and use it for consecutive requests.
Helper class to contain, manage and execute logic to detect available proxy on the network. It's a wrapper class to execute the various s.
Call Detach() to disable ProxyDetector's logic to find and set a proxy.
Represents an HTTP proxy server that can be used to route HTTP requests through.
The HTTPProxy class is an implementation of the base class, specifically designed for
HTTP proxy servers. It provides features such as transparent proxy support, sending the entire URI, and handling proxy
authentication. This class is used to configure and manage HTTP proxy settings for HTTP requests.
Gets or sets whether the proxy can act as a transparent proxy. Default value is true.
A transparent proxy forwards client requests without modifying them. When set to true, the proxy behaves as a transparent
proxy, meaning it forwards requests as-is. If set to false, it may modify requests, and this can be useful for certain
advanced proxy configurations.
Gets or sets whether the proxy - when it's in non-transparent mode - excepts only the path and query of the request URI. Default value is true.
Gets or sets whether the plugin will use the proxy as an explicit proxy for secure protocols (HTTPS://, WSS://).
When set to true, the plugin will issue a CONNECT request to the proxy for secure protocols, even if the proxy is
marked as transparent. This is commonly used for ensuring proper handling of encrypted traffic through the proxy.
Creates a new instance of the HTTPProxy class with the specified proxy address.
The address of the proxy server.
Creates a new instance of the HTTPProxy class with the specified proxy address and credentials.
The address of the proxy server.
The credentials for proxy authentication.
Creates a new instance of the HTTPProxy class with the specified proxy address, credentials, and transparency settings.
The address of the proxy server.
The credentials for proxy authentication.
Specifies whether the proxy can act as a transparent proxy (true) or not (false).
Creates a new instance of the HTTPProxy class with the specified proxy address, credentials, transparency settings, and URI handling.
The address of the proxy server.
The credentials for proxy authentication.
Specifies whether the proxy can act as a transparent proxy (true) or not (false).
Specifies whether the proxy should send the entire URI (true) or just the path and query (false) for non-transparent proxies.
Creates a new instance of the class with the specified proxy address, credentials, transparency settings, URI handling, and HTTPS behavior.
The address of the proxy server.
The credentials for proxy authentication.
Specifies whether the proxy can act as a transparent proxy (true) or not (false).
Specifies whether the proxy should send the entire URI (true) or just the path and query (false) for non-transparent proxies.
Specifies whether the plugin should use the proxy as an explicit proxy for secure protocols (HTTPS://, WSS://) (true) or not (false).
https://tools.ietf.org/html/rfc1928
The values currently defined for METHOD are:
o X'00' NO AUTHENTICATION REQUIRED
o X'01' GSSAPI
o X'02' USERNAME/PASSWORD
o X'03' to X'7F' IANA ASSIGNED
o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
o X'FF' NO ACCEPTABLE METHODS
Represents parameters used when connecting through a proxy server.
The ProxyConnectParameters struct defines the parameters required when initiating a connection
through a proxy server. It includes information about the proxy, target URI, and callbacks for success and error handling.
This struct is commonly used during the negotiation steps in the class.
The maximum number of authentication attempts allowed during proxy connection.
The proxy server through which the connection is established.
The stream used for communication with the proxy server.
The target URI to reach through the proxy server.
A cancellation token that allows canceling the proxy connection operation.
The number of authentication attempts made during proxy connection.
Gets or sets a value indicating whether to create a proxy tunnel.
A proxy tunnel, also known as a TCP tunnel, is established when communication between the client and the target server
needs to be relayed through the proxy without modification. Setting this field to true indicates the intention
to create a tunnel, allowing the data to pass through the proxy without interpretation or alteration by the proxy.
This is typically used for protocols like HTTPS, where end-to-end encryption is desired, and the proxy should act as a
pass-through conduit.
The logging context for debugging purposes.
A callback to be executed upon successful proxy connection.
A callback to be executed upon encountering an error during proxy connection.
The callback includes parameters for the current connection parameters, the encountered exception,
and a flag indicating whether the connection should be retried for authentication.
Base class for proxy implementations, providing common proxy configuration and behavior.
The Proxy class serves as the base class for various proxy client implementations,
such as and . It provides a foundation for configuring proxy settings and handling
proxy-related functionality common to all proxy types, like connecting to a proxy, setting up a request to go through the proxy
and deciding whether an address is usable with the proxy or the plugin must connect directly.
Address of the proxy server. It has to be in the http://proxyaddress:port form.
Credentials for authenticating with the proxy server.
List of exceptions for which the proxy should not be used. Elements of this list are compared to the Host (DNS or IP address) part of the uri.
Initializes a new instance of the Proxy class with the specified proxy address and credentials.
The address of the proxy server.
The credentials for proxy authentication.
Initiates a connection through the proxy server. Used during the negotiation steps.
Parameters for the proxy connection.
Gets the request path to be used for proxy communication. In some cases with HTTPProxy, the request must send the whole uri as the request path.
The target URI.
The request path for proxy communication.
Sets up an HTTP request to use the proxy as needed.
The HTTP request to set up.
true if the request should use the proxy; otherwise, false.
Determines whether the proxy should be used for a specific address based on the configured exceptions.
The address to check for proxy usage.
true if the proxy should be used for the address; otherwise, false.
Represents a SOCKS proxy used for making HTTP requests, supporting SOCKS version 5 (v5).
Initializes a new instance of the SOCKSProxy class with the specified proxy address and credentials.
The address of the SOCKS proxy server.
The credentials for proxy authentication (if required).
Authentication types that supported by Best.HTTP.
The authentication is defined by the server, so the Basic and Digest are not interchangeable. If you don't know what to use, the preferred way is to choose Unknow.
If the authentication type is not known this will do a challenge turn to receive what methode should be choosen.
The most basic authentication type. It's easy to do, and easy to crack, don't use it with plain http://
HTTP Digest authentication
Hold all information that required to authenticate to a remote server.
The type of the Authentication. If you don't know what to use, the preferred way is to choose Unknow.
The username to authenticate on the remote server.
The password to use in the authentication process. The password will be stored only in this class.
Set up the authentication credentials with the username and password. The Type will be set to Unknown.
Set up the authentication credentials with the given authentication type, username and password.
Internal class that stores all information that received from a server in a WWW-Authenticate and need to construct a valid Authorization header. Based on rfc 2617 (http://tools.ietf.org/html/rfc2617).
Used only internally by the plugin.
The Uri that this Digest is bound to.
A string to be displayed to users so they know which username and password to use.
This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access.
A flag, indicating that the previous request from the client was rejected because the nonce value was stale.
If stale is TRUE (case-insensitive), the client may wish to simply retry the request with a new encrypted response, without the user for a new username and password.
The server should only set stale to TRUE if it receives a request for which the nonce is invalid but with a valid digest for that nonce
(indicating that the client knows the correct username/password).
If stale is FALSE, or anything other than TRUE, or the stale directive is not present, the username and/or password are invalid, and new values must be obtained.
A server-specified data string which should be uniquely generated each time a 401 response is made.
Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space.
It is recommended that this string be base64 or data.
A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be "MD5".
If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one).
List of URIs, as specified in RFC XURI, that define the protection space.
If a URI is an abs_path, it is relative to the canonical root URL (see section 1.2 above) of the server being accessed.
An absoluteURI in this list may refer to a different server than the one being accessed.
The client can use this list to determine the set of URIs for which the same authentication information may be sent:
any URI that has a URI in this list as a prefix (after both have been made absolute) may be assumed to be in the same protection space.
If this directive is omitted or its value is empty, the client should assume that the protection space consists of all URIs on the responding server.
If present, it is a quoted string of one or more tokens indicating the "quality of protection" values supported by the server.
The value "auth" indicates authentication. The value "auth-int" indicates authentication with integrity protection.
his MUST be specified if a qop directive is sent (see above), and MUST NOT be specified if the server did not send a qop directive in the WWW-Authenticate header field.
The nc-value is the hexadecimal count of the number of requests (including the current request) that the client has sent with the nonce value in this request.
Used to store the last HA1 that can be used in the next header generation when Algorithm is set to "md5-sess".
Parses a WWW-Authenticate header's value to retrive all information.
Generates a string that can be set to an Authorization header.
Stores and manages already received digest infos.
Array of algorithms that the plugin supports. It's in the order of priority(first has the highest priority).
It will retrieve or create a new Digest for the given Uri.
Used for parsing WWW-Authenticate headers:
`Digest realm="my realm", nonce="4664b327a2963503ba58bbe13ad672c0", qop=auth, opaque="f7e38bdc1c66fce214f9019ffe43117c"`
An implementation for Bearer Token authentication.
Bearer Token authentication is a method used to access protected resources on a server.
It involves including a bearer token in the Authorization header of an HTTP request to prove the identity of the requester.
Initializes a new instance of the BearerTokenAuthenticator class with the specified Bearer Token.
The Bearer Token to use for authentication.
Sets up the required Authorization header with the Bearer Token for the HTTP request.
The HTTP request for which the Authorization header should be added.
When sending an HTTP request to a server that requires Bearer Token authentication,
this method sets the Authorization header with the Bearer Token to prove the identity of the requester.
This allows the requester to access protected resources on the server.
Handles the server response with a 401 (Unauthorized) status code and a WWW-Authenticate header.
This authenticator does not handle challenges and always returns false.
The HTTP request that received the 401 response.
The HTTP response containing the 401 (Unauthorized) status.
false, as this authenticator does not handle challenges.
Bearer Token authentication typically does not require handling challenges,
as the Bearer Token is included directly in the Authorization header of the request.
This method always returns false, as no additional challenge processing is needed.
An implementation for HTTP Basic or Digest authentication.
Gets or sets the associated with this authenticator.
Initializes a new instance of the CrendetialAuthenticator class with the specified .
The to use for authentication.
Thrown if is null.
Sets up the required headers for the HTTP request based on the provided credentials.
The HTTP request for which headers should be added.
Handles the server response with a 401 (Unauthorized) status code and a WWW-Authenticate header.
The authenticator might determine the authentication method to use and initiate authentication if needed.
The HTTP request that received the 401 response.
The HTTP response containing the 401 (Unauthorized) status.
true if the challenge is handled by the authenticator and the request can be resent with authentication; otherwise, false.
Represents an interface for various authentication implementations used in HTTP requests.
Set required headers or content for the HTTP request. Called right before the request is sent out.
The SetupRequest method will be called every time the request is redirected or retried.
The HTTP request to which headers or content will be added.
Called when the server is sending a 401 (Unauthorized) response with an WWW-Authenticate header.
The authenticator might find additional knowledge about the authentication requirements (like what auth method it should use).
If the authenticator is confident it can successfully (re)authenticate the request it can return true and the request will be resent to the server.
More details can be found here:
- RFC-9110 - 401 Unauthorized
- RFC-9110 - WWW-Authenticate header
The HTTP request that received the 401 response.
The HTTP response containing the 401 (Unauthorized) status.
true if the challange is handled by the authenticator and the request can be re-sent with authentication.
Delegate for handling the event when headers are received in a response.
The object.
The object.
The headers received from the server.
Delegate for handling progress during the download.
The object.
The number of bytes downloaded so far.
The total length of the content being downloaded, or -1 if the length cannot be determined.
Delegate for handling the event when the download of content starts.
The object.
The object.
The used for receiving downloaded content.
Delegate for creating a new object.
The object.
The object.
An interface for notifying connections that the buffer has free space for downloading data.
The newly created .
Delegate for handling the event when a response is upgraded.
The object.
The object.
A stream that provides content for the upgraded response.
true to keep the underlying connection open; otherwise, false.
Represents settings for configuring an HTTP request's download behavior.
Gets or sets the maximum number of bytes the will buffer before pausing the download until its buffer has free space again.
When the download content stream buffers data up to this specified limit, it will temporarily pause downloading until it has free space in its buffer.
Increasing this value may help reduce the frequency of pauses during downloads, but it also increases memory usage.
Gets or sets a value indicating whether caching should be enabled for this request.
Gets or sets a value indicating whether the response's should be populated with downloaded data or if the content should be written only to the local cache when available.
If set to true and the content isn't cacheable (e.g., it doesn't have any cache-related headers), the content will be downloaded but will be lost.
Gets or sets a value indicating whether the response's should be populated with downloaded data or if the content should be written only to the local cache when available.
If set to true and the content isn't cacheable (e.g., it doesn't have any cache-related headers), the content will be downloaded but will be lost.
This is because the downloaded data would be written exclusively to the local cache and will not be stored in memory or the response's for further use.
This event is called when the plugin received and parsed all headers.
Represents a function that creates a new object when needed for downloading content.
Event for handling the start of the download process for 2xx status code responses.
The object.
The object representing the response.
The containing the downloaded data. It might already be populated with some content.
This event is called when the plugin expects the server to send content. When called, the
might already be populated with some content. It is specifically meant for responses with 2xx status codes.
Gets or sets the event that is called when new data is downloaded from the server.
The first parameter is the original object itself, the second parameter is the downloaded bytes, and the third parameter is the content length.
There are download modes where we can't figure out the exact length of the final content. In these cases, we guarantee that the third parameter will be at least the size of the second one.
Called when a response with status code 101 (upgrade), "connection: upgrade" header and value or an "upgrade" header received.
This callback might be called on a thread other than the main one!
Isn't available under WebGL!
Represents settings related to using a proxy server for HTTP requests.
Checks if there is a proxy configured for the given URI.
The URI to check for proxy usage.
true if a proxy is configured and should be used for the URI; otherwise, false.
Gets or sets the proxy object used for the request.
Sets up the HTTP request for passing through a proxy server.
The HTTP request to set up.
Handles the proxy's response with status code 407.
The HTTP request that received a 407 response.
true to resend the request through the proxy; otherwise, false.
Adds the proxy address to a hash for the given request URI.
The request URI for which the proxy address is added to the hash.
The hash to which the proxy address is added.
Represents settings related to handling HTTP request redirection.
Indicates whether the request has been redirected.
A request's IsRedirected might be true while is zero if the redirection is made to the local cache.
The Uri that the request is redirected to.
How many redirection is supported for this request. The default is 10. Zero or a negative value means no redirections are supported.
Gets or sets the maximum number of redirections supported for this request. The default is 10.
A value of zero or a negative value means no redirections are supported.
Gets the number of times the request has been redirected.
Occurs before the plugin makes a new request to the new URI during redirection.
The return value of this event handler controls whether the redirection is aborted (false) or allowed (true).
This event is called on a thread other than the main Unity thread.
Initializes a new instance of the RedirectSettings class with the specified maximum redirections.
The maximum number of redirections allowed.
Resets and to their default values.
Represents settings related to request retry behavior.
Gets the number of times that the plugin has retried the request.
Gets or sets the maximum number of retry attempts allowed. To disable retries, set this value to 0.
The default value is 1 for GET requests, otherwise 0.
Initializes a new instance of the RetrySettings class with the specified maximum retry attempts.
The maximum number of retry attempts allowed.
Represents settings related to connection-timeouts and processing duration.
Gets the timestamp when the request was queued for processing.
Gets the timestamp when the processing of the request started by a connection.
Gets or sets the maximum time to wait for establishing the connection to the target server.
If set to TimeSpan.Zero or lower, no connect timeout logic is executed. Default value is 20 seconds.
Gets or sets the maximum time to wait for the request to finish after the connection is established.
Returns true if the request has been stuck in the connection phase for too long.
The current timestamp.
true if the connection has timed out; otherwise, false.
Returns true if the time has passed the specified Timeout setting since processing started or if the connection has timed out.
The current timestamp.
true if the request has timed out; otherwise, false.
Initializes a new instance of the TimeoutSettings class for a specific .
The associated with these timeout settings.
Options for sending the request headers and content, including upload progress monitoring.
might be called when redirected or retried!
Size of the internal buffer, and upload progress will be fired when this size of data sent to the wire. Its default value is 4 KiB.
The stream that the plugin will use to send data to the server.
The stream can be any regular implementation or a specialized one inheriting from :
- A specialized for data generated on-the-fly or periodically. The request remains active until the method is invoked, ensuring continuous data feed even during temporary empty states.
- An implementation to convert and upload the object as JSON data. It sets the "Content-Type" header to "application/json; charset=utf-8".
- An implementation representing a stream that prepares and sends data as URL-encoded form data in an HTTP request.
- An based implementation of the multipart/form-data Content-Type. It's very memory-effective, streams are read into memory in chunks.
Set to false if the plugin MUST NOT dispose after the request is finished.
Called periodically when data sent to the server.
This event is fired after the headers are sent to the server.
Called every time the request is sent out (redirected or retried).
The being prepared.
true if the can be fired.
Dispose of resources used by the UploadSettings instance.
Helper class to store, calculate and manage request related events and theirs duration, referenced by field.
When the TimingCollector instance created.
When the closing Finish event is sent.
List of added events.
Finish the last event.
Abort the currently running event.
When the event happened and for how long.
Struct to hold information about one timing event recorded for a . Timing events are managed by the .
Name of the event
Duration of the event.
When the event occurred.
Provides constants representing different, special body lengths for HTTP requests with upload streams.
The 's length is unknown and the plugin have to send data with 'chunked' transfer-encoding.
The 's length is unknown and the plugin have to send data as-is, without any encoding.
No content to send.
A specialized upload stream designed to handle data that's generated on-the-fly or periodically.
This implementation is designed to handle scenarios where data may not always be immediately available for upload.
The request will remain active until the method is invoked, ensuring that data can continue to be fed into the stream even if it's temporarily empty during a Read operation.
Gets the length of the upload stream.
This implementation returns a constant value of -1, indicating that the length of the data to be uploaded is unknown. When the processing connection encounters this value, it should utilize chunked uploading to handle the data transfer.
The constant value of -1, representing unknown length.
Gets the length of data currently buffered and ready for upload.
The length of buffered data in bytes.
Initializes a new instance of the DynamicUploadStream class with an optional content type.
The MIME type of the content to be uploaded. Defaults to "application/octet-stream" if not specified.
This constructor allows the caller to specify the content type of the data to be uploaded. If not provided, it defaults to a general binary data type.
Sets the necessary headers before sending the request.
Prepares the stream before the request body is sent.
Reads data from the stream to be uploaded.
The returned value indicates the state of the stream:
- -1More data is expected in the future, but isn't currently available. When new data is ready, the IThreadSignaler must be notified.
- 0The stream has been closed and no more data will be provided.
- Otherwise it returns with the number bytes copied to the buffer.
Note: A zero return value can come after a -1 return, indicating a transition from waiting to completion.
Writes data to the stream, making it available for upload.
After writing data to the stream using this method, the connection is signaled that data is available to send.
The array of unsigned bytes from which to copy count bytes to the current stream.
The zero-based byte offset in buffer at which to begin copying bytes to the current stream.
The number of bytes to be written to the current stream.
Thrown when trying to write after the stream has been marked as complete.
Writes a segment of data to the stream, making it available for upload.
A segment of data to be written to the stream.
Thrown when trying to write after the stream has been marked as complete.
After writing a segment to the stream using this method, the connection is signaled that data is available to send.
Marks the stream as complete, signaling that no more data will be added.
All remaining buffered data will be sent to the server.
An based implementation of the multipart/form-data Content-Type. It's very memory-effective, streams are read into memory in chunks.
The return value of is treated specially in the plugin:
-
Less than zero(-1) value
indicates that no data is currently available but more is expected in the future. In this case, when new data becomes available the IThreadSignaler object must be signaled.
-
Zero (0)
means that the stream is closed, no more data can be expected.
A zero value to signal stream closure can follow a less than zero value.
Gets the length of this multipart/form-data stream.
A random boundary generated in the constructor.
Initializes a new instance of the MultipartFormDataStream class.
Initializes a new instance of the MultipartFormDataStream class with a custom boundary.
Adds a textual field to the multipart/form-data stream.
The name of the field.
The textual value of the field.
The MultipartFormDataStream instance for method chaining.
Adds a textual field to the multipart/form-data stream.
The name of the field.
The textual value of the field.
The encoding to use for the value.
The MultipartFormDataStream instance for method chaining.
Adds a stream field to the multipart/form-data stream.
The name of the field.
The data containing the field data.
The MultipartFormDataStream instance for method chaining.
Adds a stream field to the multipart/form-data stream.
The stream containing the field data.
The name of the field.
The MultipartFormDataStream instance for method chaining.
Adds a stream field to the multipart/form-data stream.
The stream containing the field data.
The name of the field.
The name of the file, if applicable.
The MultipartFormDataStream instance for method chaining.
Adds a stream field to the multipart/form-data stream.
The stream containing the field data.
The name of the field.
The name of the file, if applicable.
The MIME type of the content.
The MultipartFormDataStream instance for method chaining.
Adds the final boundary to the multipart/form-data stream before sending the request body.
The HTTP request.
The thread signaler for handling asynchronous operations.
Reads data from the multipart/form-data stream into the provided buffer.
The buffer to read data into.
The starting offset in the buffer.
The maximum number of bytes to read.
The number of bytes read into the buffer.
Readonly struct to hold key -> value pairs, where the value is either textual or binary.
An implementation representing a stream that prepares and sends data as URL-encoded form data in an HTTP request.
This stream is used to send data as URL-encoded form data in an HTTP request. It sets the "Content-Type" header to "application/x-www-form-urlencoded".
URL-encoded form data is typically used for submitting form data to a web server. It is commonly used in HTTP POST requests to send data to a server, such as submitting HTML form data.
The return value of is treated specially in the plugin:
-
Less than zero(-1) value
indicates that no data is currently available but more is expected in the future. In this case, when new data becomes available the IThreadSignaler object must be signaled.
-
Zero (0)
means that the stream is closed, no more data can be expected.
A zero value to signal stream closure can follow a less than zero value.
While it's possible, it's not advised to send binary data url-encoded!
Gets the length of the stream.
A list that holds the form's fields.
Sets up the HTTP request by adding the "Content-Type" header as "application/x-www-form-urlencoded".
The HTTP request.
Adds binary data to the form. It is not advised to send binary data with an URL-encoded form due to the conversion cost of binary to text conversion.
The name of the field.
The binary data content.
The UrlEncodedStream instance for method chaining.
An implementation to convert and upload the object as JSON data. It sets the "Content-Type" header to "application/json; charset=utf-8".
The type of the object to be converted to JSON.
This stream keeps a reference to the object until the preparation in . This means, changes to the object after passing it to the constructor will be reflected in the sent data too.
The return value of is treated specially in the plugin:
-
Less than zero(-1) value
indicates that no data is currently available but more is expected in the future. In this case, when new data becomes available the IThreadSignaler object must be signaled.
-
Zero (0)
means that the stream is closed, no more data can be expected.
A zero value to signal stream closure can follow a less than zero value.
Initializes a new instance of the class with the specified object.
The object to be converted to JSON and uploaded.
Called before sending out the request's headers. It sets the "Content-Type" header to "application/json; charset=utf-8".
The HTTP request.
Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source.
The zero-based byte offset in at which to begin storing the data read from the current stream.
The maximum number of bytes to be read from the current stream.
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
Releases the unmanaged resources used by the and optionally releases the managed resources.
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Abstract class to serve as a base for non-conventional streams used in HTTP requests.
The return value of is treated specially in the plugin:
-
Less than zero(-1)
indicates that no data is currently available but more is expected in the future. In this case, when new data becomes available the IThreadSignaler object must be signaled.
-
Zero (0)
means that the stream is closed, no more data can be expected.
- Otherwise it must return with the number bytes copied to the buffer.
A zero value to signal stream closure can follow a less than zero value.
Gets the object for signaling when new data is available.
Length in bytes that the stream will upload.
The return value of Length is treated specially in the plugin:
- -2The stream's length is unknown and the plugin have to send data with 'chunked' transfer-encoding.
- -1The stream's length is unknown and the plugin have to send data as-is, without any encoding.
- 0No content to send. The content-length header will contain zero (0).
- >0Length of the content is known, will be sent as-is, without any encoding. The content-length header will contain zero (0).
Constants for the first three points can be found in .
Called before sending out the request's headers. Perform content processing to calculate the final length if possible.
In this function the implementor can set headers and other parameters to the request.
Typically called on a thread.
The associated with the stream.
Called just before sending out the request's body, and saves the for signaling when new data is available.
The HTTPRequest associated with the stream.
The object to be used for signaling.
Typically called on a separate thread.
Called just before sending out the request's body, saves the that can be used for signaling when new data is available.
The HTTPRequest associated with the stream.
The object to be used for signaling.
Typically called on a separate thread.
A blocking variant of the that allows clients to wait for downloaded data when the buffer is empty but not completed.
The BlockingDownloadContentStream is a specialized variant of the designed to provide a blocking mechanism for clients waiting for downloaded data.
This class is particularly useful when clients need to read from the stream, but the buffer is temporarily empty due to ongoing downloads.
Key Features:
-
Blocking Data Retrieval
Provides a blocking method that allows clients to wait for data if the buffer is empty but not yet completed.
-
Timeout Support
The method accepts a timeout parameter, allowing clients to set a maximum wait time for data availability.
-
Exception Handling
Handles exceptions and errors that occur during download, ensuring that clients receive any relevant exception information.
Clients can use the method to retrieve data from the stream, and if the buffer is empty, the method will block until new data is downloaded or a timeout occurs.
This blocking behavior is particularly useful in scenarios where clients need to consume data sequentially but can't proceed until data is available.
When the download is completed or if an error occurs during download, this stream allows clients to inspect the completion status and any associated exceptions, just like the base .
Initializes a new instance of the class.
The HTTP response associated with this download stream.
The maximum size of the internal buffer.
Handler for notifying when buffer space becomes available.
Attempts to retrieve a downloaded content-segment from the stream, blocking if necessary until a segment is available.
When this method returns, contains the instance representing the data, if available; otherwise, contains the value of . This parameter is passed uninitialized.
true if a segment could be retrieved; otherwise, false.
The TryTake function provides a blocking approach to retrieve data from the stream.
If the stream has data available, it immediately returns the data.
If there's no data available, the method will block until new data is downloaded or the buffer is marked as completed.
This method is designed for scenarios where clients need to read from the stream sequentially and are willing to wait until data is available.
It ensures that clients receive data as soon as it becomes available, without having to repeatedly check or poll the stream.
Returns with a download content-segment. If the stream is currently empty but not completed the execution is blocked until new data downloaded.
A segment is an arbitrary length array of bytes the plugin could read in one operation, it can range from couple of bytes to kilobytes.
A BufferSegment holding a reference to the byte[] containing the downloaded data, offset and count of bytes in the array.
The stream is disposed.
The stream is empty and marked as completed.
Returns with a download content-segment. If the stream is currently empty but not completed the execution is blocked until new data downloaded or the timeout is reached.
A segment is an arbitrary length array of bytes the plugin could read in one operation, it can range from couple of bytes to kilobytes.
A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.
A BufferSegment holding a reference to the byte[] containing the downloaded data, offset and count of bytes in the array. In case of a timeout, BufferSegment.Empty returned.
The stream is disposed.
The stream is empty and marked as completed.
Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
This override of the method provides blocking behavior, meaning if there are no bytes available in the stream, the method will block until new data is downloaded or until the stream completes. Once data is available, or if the stream completes, the method will return with the number of bytes read.
This behavior ensures that consumers of the stream can continue reading data sequentially, even if the stream's internal buffer is temporarily empty due to ongoing downloads.
An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source.
The zero-based byte offset in at which to begin storing the data read from the current stream.
The maximum number of bytes to be read from the current stream.
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream is reached.
Instead of calling WaitOne once for the total duration of the timeout,
periodically check whether we are disposed or not.
A read-only stream that the plugin uses to store the downloaded content. This stream is designed to buffer downloaded data efficiently and provide it to consumers.
The DownloadContentStream serves as a storage medium for content downloaded during HTTP requests.
It buffers the downloaded data in segments and allows clients to read from the buffer as needed.
This buffering mechanism is essential for optimizing download performance, especially in scenarios where the download rate may vary or be faster than the rate at which data is consumed.
The stream operates in conjunction with the interface, which is used to signal connections when buffer space becomes available.
Connections can then transfer additional data into the buffer for processing.
-
Efficient Buffering
The stream efficiently buffers downloaded content, ensuring that data is readily available for reading without extensive delays.
-
Dynamic Resizing
The internal buffer dynamically resizes to accommodate varying amounts of downloaded data, optimizing memory usage.
-
Asynchronous Signal Handling
Asynchronous signaling mechanisms are used to notify connections when buffer space is available, enabling efficient data transfer.
-
Error Handling
The stream captures and propagates errors that occur during download, allowing clients to handle exceptions gracefully.
-
Blocking Variant
A blocking variant, , allows clients to wait for data when the buffer is empty but not completed.
Clients can read from this stream using standard stream reading methods, and the stream will release memory segments as data is read.
When the download is completed or if an error occurs during download, this stream allows clients to inspect the completion status and any associated exceptions.
Gets the HTTP response from which this download stream originated.
Gets a value indicating whether the download is completed, and there's no more data buffered in the stream to read.
Gets a reference to an exception if the download completed with an error.
Gets the length of the buffered data. Because downloads happen in parallel, a call can return with more data after checking Length.
Gets the maximum size of the internal buffer of this stream.
In some cases, the plugin may put more data into the stream than the specified size.
Gets a value indicating whether the internal buffer holds at least the amount of data.
Gets or sets whether the stream is detached from the / when is used before the request is finished.
When the stream is detached from the response object, their lifetimes are not bound together,
meaning that the stream isn't disposed automatically, and the client code is responsible for calling the stream's function.
There are cases where the plugin have to put more data into the buffer than its previously set maximum.
For example when the underlying connection is closed, but the content provider still have buffered data,
in witch case we have to push all processed data to the user facing download stream.
Count of consecutive calls with DoFullCheck that found the stream fully buffered.
Initializes a new instance of the DownloadContentStream class.
The HTTP response associated with this download stream.
The maximum size of the internal buffer.
Handler for notifying when buffer space becomes available.
Completes the download stream with an optional error. Called when the download is finished.
The exception that occurred during download, if any.
Tries to remove a downloaded segment from the stream. If the stream is empty, it returns immediately with false.
A containing the reference to a byte[] and the offset and count of the data in the array.
true if a downloaded segment was available and could return with, otherwise false
A non-blocking Read function. When it returns 0, it doesn't mean the download is complete. If the download interrupted before completing, the next Read call can throw an exception.
The buffer to read data into.
The zero-based byte offset in the buffer at which to begin copying bytes.
The maximum number of bytes to read.
The number of bytes copied to the buffer, or zero if no downloaded data is available at the time of the call.
If the stream is already disposed.
Writes a downloaded data segment to the stream.
The downloaded data segment to write.
Checks whether the stream is fully buffered and increases a counter if it's full, resetting it otherwise.
The limit for the full check counter.
true if the counter is equal to or larger than the limit parameter; otherwise false.
Disposes of the stream, releasing any resources held by it.
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Provides constants representing various HTTP status codes.
Represents an HTTP response received from a remote server, containing information about the response status, headers, and data.
The HTTPResponse class represents an HTTP response received from a remote server. It contains information about the response status, headers, and the data content.
Key Features:
-
Response Properties
Provides access to various properties such as , , , and more, to inspect the response details.
-
Data Access
Allows access to the response data in various forms, including raw bytes, UTF-8 text, and as a for image data.
-
Header Management
Provides methods to add, retrieve, and manipulate HTTP headers associated with the response, making it easy to inspect and work with header information.
-
Caching Support
Supports response caching, enabling the storage of downloaded data in local cache storage for future use.
-
Stream Management
Manages the download process and data streaming through a () to optimize memory usage and ensure efficient handling of large response bodies.
Gets the version of the HTTP protocol with which the response was received. Typically, this is HTTP/1.1 for local file and cache responses, even if the original response received with a different version.
Gets the HTTP status code sent from the server, indicating the outcome of the HTTP request.
Gets the message sent along with the status code from the server. This message can add some details, but it's empty for HTTP/2 responses.
Gets a value indicating whether the response represents a successful HTTP request. Returns true if the status code is in the range of [200..300[ or 304 (Not Modified).
Gets a value indicating whether the response body is read from the cache.
Gets the headers sent from the server as key-value pairs. You can use additional methods to manage and retrieve header information.
The Headers property provides access to the headers sent by the server in the HTTP response. You can use the following methods to work with headers:
- Adds an HTTP header with the specified name and value to the response headers.
- Retrieves the list of values for a given header name as received from the server.
- Retrieves the first value for a given header name as received from the server.
- Checks if a header with the specified name and value exists in the response headers.
- Checks if a header with the specified name exists in the response headers.
- Parses the 'Content-Range' header's value and returns a object representing the byte range of the response content.
The data that downloaded from the server. All Transfer and Content encodings decoded if any(eg. chunked, gzip, deflate).
The normal HTTP protocol is upgraded to an other.
Cached, converted data.
The data converted to an UTF8 string.
Cached converted data.
The data loaded to a Texture2D.
Reference to the instance that contains the downloaded data.
IProtocol.LoggingContext implementation.
The original request that this response is created for.
Adds an HTTP header with the specified name and value to the response headers.
The name of the header.
The value of the header.
Retrieves the list of values for a given header name as received from the server.
The name of the header.
A list of header values if the header exists and contains values; otherwise, returns null.
Retrieves the first value for a given header name as received from the server.
The name of the header.
The first header value if the header exists and contains values; otherwise, returns null.
Checks if a header with the specified name and value exists in the response headers.
The name of the header to check.
The value to check for in the header.
true if a header with the given name and value exists in the response headers; otherwise, false.
Checks if a header with the specified name exists in the response headers.
The name of the header to check.
true if a header with the given name exists in the response headers; otherwise, false.
Parses the 'Content-Range' header's value and returns a object representing the byte range of the response content.
If the server ignores a byte-range-spec because it is syntactically invalid, the server SHOULD treat the request as if the invalid Range header field did not exist.
(Normally, this means return a 200 response containing the full entity). In this case because there are no 'Content-Range' header values, this function will return null.
A object representing the byte range of the response content, or null if no 'Content-Range' header is found.
Add data to the fragments list.
The buffer to be added.
The position where we start copy the data.
How many data we want to copy.
IDisposable implementation.
Describes the state of a future.
The future hasn't begun to resolve a value.
The future is working on resolving a value.
The future has a value ready.
The future failed to resolve a value.
Defines the interface of an object that can be used to track a future value.
The type of object being retrieved.
Gets the state of the future.
Gets the value if the State is Success.
Gets the failure exception if the State is Error.
Adds a new callback to invoke when an intermediate result is known.
The callback to invoke.
The future so additional calls can be chained together.
Adds a new callback to invoke if the future value is retrieved successfully.
The callback to invoke.
The future so additional calls can be chained together.
Adds a new callback to invoke if the future has an error.
The callback to invoke.
The future so additional calls can be chained together.
Adds a new callback to invoke if the future value is retrieved successfully or has an error.
The callback to invoke.
The future so additional calls can be chained together.
Defines the signature for callbacks used by the future.
The future.
An implementation of that can be used internally by methods that return futures.
Methods should always return the interface when calling code requests a future.
This class is intended to be constructed internally in the method to provide a simple implementation of
the interface. By returning the interface instead of the class it ensures the implementation can change
later on if requirements change, without affecting the calling code.
The type of object being retrieved.
Gets the state of the future.
Gets the value if the State is Success.
Gets the failure exception if the State is Error.
Initializes a new instance of the class.
Adds a new callback to invoke if the future value is retrieved successfully.
The callback to invoke.
The future so additional calls can be chained together.
Adds a new callback to invoke if the future has an error.
The callback to invoke.
The future so additional calls can be chained together.
Adds a new callback to invoke if the future value is retrieved successfully or has an error.
The callback to invoke.
The future so additional calls can be chained together.
Begins running a given function on a background thread to resolve the future's value, as long
as it is still in the Pending state.
The function that will retrieve the desired value.
Allows manually assigning a value to a future, as long as it is still in the pending state.
There are times where you may not need to do background processing for a value. For example,
you may have a cache of values and can just hand one out. In those cases you still want to
return a future for the method signature, but can just call this method to fill in the future.
The value to assign the future.
Allows manually failing a future, as long as it is still in the pending state.
As with the Assign method, there are times where you may know a future value is a failure without
doing any background work. In those cases you can simply fail the future manually and return it.
The exception to use to fail the future.
This enum describes the action that caused a CollectionChanged event.
One or more items were added to the collection.
One or more items were removed from the collection.
One or more items were replaced in the collection.
One or more items were moved within the collection.
The contents of the collection changed dramatically.
Arguments for the CollectionChanged event.
A collection that supports INotifyCollectionChangedThis raises this event
whenever an item is added or removed, or when the contents of the collection
changes dramatically.
Construct a NotifyCollectionChangedEventArgs that describes a reset change.
The action that caused the event (must be Reset).
Construct a NotifyCollectionChangedEventArgs that describes a one-item change.
The action that caused the event; can only be Reset, Add or Remove action.
The item affected by the change.
Construct a NotifyCollectionChangedEventArgs that describes a one-item change.
The action that caused the event.
The item affected by the change.
The index where the change occurred.
Construct a NotifyCollectionChangedEventArgs that describes a multi-item change.
The action that caused the event.
The items affected by the change.
Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset).
The action that caused the event.
The items affected by the change.
The index where the change occurred.
Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event.
Can only be a Replace action.
The new item replacing the original item.
The original item that is replaced.
Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event.
Can only be a Replace action.
The new item replacing the original item.
The original item that is replaced.
The index of the item being replaced.
Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event.
Can only be a Replace action.
The new items replacing the original items.
The original items that are replaced.
Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event.
Can only be a Replace action.
The new items replacing the original items.
The original items that are replaced.
The starting index of the items being replaced.
Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event.
Can only be a Move action.
The item affected by the change.
The new index for the changed item.
The old index for the changed item.
Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event.
The action that caused the event.
The items affected by the change.
The new index for the changed items.
The old index for the changed items.
Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling.
The action that caused the event.
The items affected by the change.
The old items affected by the change (for Replace events).
The index where the change occurred.
The old index where the change occurred (for Move events).