Skip to content

crypto ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793783302/FIN+5.3.1+crypto 中文整理基于 FIN 5.3.1

导读: 非对称密钥对中的一个密钥

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • mixins
  • classes
  • Slot Details
    • keySize
    • toStr
    • certType
    • encoded
    • isCA
    • isSelfSigned
    • issuer
    • pub
    • subject
    • authKeyId
    • basicConstraints
    • ca
    • extendedKeyUsage
    • keyUsage
    • notAfter
    • notBefore
    • sign
    • signWith
    • subjectAltName
    • subjectKeyId
    • certSigner
    • cur
    • digest
    • genCsr
    • genKeyPair
    • loadCertsForUri
    • loadJwk
    • loadJwksForUri
    • loadKeyStore
    • loadPem
    • loadX509
    • opts
    • algorithm
    • digestSize
    • reset
    • update
    • updateAscii
    • updateByte
    • updateI4
    • updateI8
    • key
    • meta
    • alg
    • aud
    • claims
    • decode
    • encode
    • exp
    • header
    • iat
    • iss
    • jti
    • kid
    • make
    • nbf
    • sub
    • verifyClaim
    • format
    • priv
    • aliases
    • containsAlias
    • get
    • getPrivKey
    • getTrust
    • remove
    • save
    • set
    • setPrivKey
    • setTrust
    • size
    • attrs
    • decrypt
    • cert
    • certChain
    • keyPair
    • encrypt
    • verify

概述(中译) ​

const 混入 AsymKey : Key

非对称密钥对中的一个密钥

方法

插槽详情


API 正文(英文) ​

keySize ​

abstract Int keySize()

Gets the size, in bits, of the key modulus used by the asymmetric algorithm.


toStr ​

abstract override Str toStr()

Get the PEM encoding of the key.


Cert ​

const mixin Cert

Cert defines the api for an identity certificate. An identity certificate binds a subject to a public key. The certificate is signed by an issuer.

Methods

certTypeGet the type of certificate (e.g.
encodedGet the encoded form of the certificate.
isCAReturn true if certificate is a Certificate Authority
isSelfSignedReturn true if certificate is self signed
issuerGet the issuer DN from the certificate.
pubGet the public key from the certificate.
subjectGet the subject DN from the certificate.
toStrGet the PEM encoding of the certificate

Slot Details ​


certType ​

abstract Str certType()

Get the type of certificate (e.g. X.509)


encoded ​

abstract Buf encoded()

Get the encoded form of the certificate.


isCA ​

abstract Bool isCA()

Return true if certificate is a Certificate Authority


isSelfSigned ​

abstract Bool isSelfSigned()

Return true if certificate is self signed


issuer ​

abstract Str issuer()

Get the issuer DN from the certificate.


pub ​

abstract PubKey pub()

Get the public key from the certificate.


subject ​

abstract Str subject()

Get the subject DN from the certificate.


toStr ​

abstract override Str toStr()

Get the PEM encoding of the certificate


CertSigner ​

mixin CertSigner

The CertSigner allows you to configure various options for signing a certificate from a CSR to generate a signed certifcate.

See RFC5280 for more information on configuring v3 extension values.

Methods

authKeyIdConfigure the Authority Key Identifier V3 extension
basicConstraintsConfigure the Basic Constraints V3 extension
caConfigure the CA private key and public certificate.
extendedKeyUsageConfigure the Extended Key Usage V3 extension.
keyUsageConfigure the Key Usage V3 extension
notAfterConfigure the end date for the certificate validity period.
notBeforeConfigure the start date for the certificate valdity period.
signGenerate the signed certificate based on the current configuration.
signWithConfigure the signature algorithm to sign the certificate with.
subjectAltNameAdd a Subject Alternative Name to the certificate.
subjectKeyIdConfigure the Subject Key Identifier V3 extenstion

Slot Details ​


authKeyId ​

abstract This authKeyId(Buf buf)

Configure the Authority Key Identifier V3 extension


basicConstraints ​

abstract This basicConstraints(Bool ca := false, Int? pathLenConstraint := null)

Configure the Basic Constraints V3 extension


ca ​

abstract This ca(PrivKey caPrivKey, Cert caCert)

Configure the CA private key and public certificate. If this method is not called, then a self-signed certificate will be generated.


extendedKeyUsage ​

abstract This extendedKeyUsage(Str[] oids)

Configure the Extended Key Usage V3 extension.


keyUsage ​

abstract This keyUsage(Buf bits)

Configure the Key Usage V3 extension


notAfter ​

abstract This notAfter(Date date)

Configure the end date for the certificate validity period. The default value is 365 days from today.


notBefore ​

abstract This notBefore(Date date)

Configure the start date for the certificate valdity period. The default value is today.


sign ​

abstract Cert sign()

Generate the signed certificate based on the current configuration.


signWith ​

abstract This signWith(Str:Obj opts)

Configure the signature algorithm to sign the certificate with. This map is configured the same as a Crypto.genCsr. By default, an implementation should choose a "strong" signing algorithm.


subjectAltName ​

abstract This subjectAltName(Obj name)

Add a Subject Alternative Name to the certificate. This method may be called multiple times to add different SANs. The name may be one of the following types:

  • Str: a DNS name
  • Uri: a Uniform Resource Identifier name
  • IpAddr: an IP address name

subjectKeyId ​

abstract This subjectKeyId(Buf buf)

Configure the Subject Key Identifier V3 extenstion


Crypto ​

const mixin Crypto

Crypto defines a pluggable mixin for cryptography capabilities in Fantom. Use cur to access the current Crypto instance.

Fields

curGet the installed crypto implementation for this runtime.

Methods

certSignerObtain a builder that can be used to configure signing options for generating a signed certificate from a CSR.
digestGet a Digest for the given algorithm.
genCsrGenerate a Certificate Signing Request (CSR).
genKeyPairGenerate an asymmetric key pair with the given algorithm and key size (in bits).
loadCertsForUriAttempt to load the full certificate chain for the given uri.
loadJwkLoad a JSON Web Key (Jwk) from a Map.
loadJwksForUriImport JSON Web Key Set from a Uri
loadKeyStoreLoad a KeyStore from the given file.
loadPemLoad the next PEM-encoded object from the input stream.
loadX509Load all X.509 certificates from the given input stream.

Slot Details ​


certSigner ​

abstract CertSigner certSigner(Csr csr)

Obtain a builder that can be used to configure signing options for generating a signed certificate from a CSR.

cert := Crypto.cur.certSigner(csr)
  .ca(caKeys, "cn=example,ou=example.org,o=Example Inc,c=US")
  .notAfter(Date.today + 365day)
  .sign

cur ​

const static Crypto cur

Get the installed crypto implementation for this runtime.


digest ​

abstract Digest digest(Str algorithm)

Get a Digest for the given algorithm.

buf := Crypto.cur.digest("SHA-256").update("foo".toBuf).digest

genCsr ​

abstract Csr genCsr(KeyPair keys, Str subjectDn, Str:Obj opts := [:])

Generate a Certificate Signing Request (CSR). The subjectDn must be a valid X.500 distinguised name as defined in RFC4514.

By default, the implementation should choose a "strong" signing algorithm for signing the CSR. All implementations must support the algorithm option with one of the following values:

  • sha256WithRSAEncryption
  • sha512WithRSAEncryption
// Generate a csr signed with the default algorithm
csr := Crypto.cur.genCsr(pair, "cn=test")

// Generate a csr signed with SHA-512
csr := Crypto.cru.genCsr(pair, "cn=test", ["algorithm": "sha512WithRSAEncryption"])

genKeyPair ​

abstract KeyPair genKeyPair(Str algorithm, Int bits)

Generate an asymmetric key pair with the given algorithm and key size (in bits). Throws Err if the algorithm or key size is not supported.

pair := Crypto.cur.genKeyPair("RSA", 2048)

loadCertsForUri ​

virtual Cert[] loadCertsForUri(Uri uri)

Attempt to load the full certificate chain for the given uri. If the certificate chain cannot be obtained, throw an Err.

This is an optional operation and implementations may throw UnsupportedErr.

certs := Crypto.cur.loadCertForUri(`https://my.server.com/`)

loadJwk ​

abstract Jwk? loadJwk(Str:Obj map)

Load a JSON Web Key (Jwk) from a Map.

Throws an error if unable to determine the JWK type.

jwkRsa  := Crypto.cur.loadJwk(["kty":"RSA", "alg":"RS256", ...])
jwkEc   := Crypto.cur.loadJwk(["kty":"EC", "alg":"ES256", ...])
jwkHmac := Crypto.cur.loadJwk(["kty":"oct", "alg":"HS256", ...])

loadJwksForUri ​

abstract Jwk[] loadJwksForUri(Uri uri, Int maxKeys := 10)

Import JSON Web Key Set from a Uri

jwks := Crypto.cur.loadJwksForUri(`https://example.com/jwks.json`)

loadKeyStore ​

abstract KeyStore loadKeyStore(File? file := null, Str:Obj opts := [:])

Load a KeyStore from the given file. If file is null, then a new, empty keystore in the PKCS12 format will be returned. The keystore format is determined by the file extension:

  • .p12, .pfx: PKCS12 format
  • .jks: Java KeyStore (JAVA only)

If the file does not have an extension, then PKCS12 format will be assumed. Other formats may be supported depending on the runtime implementation. Throws an Err if the format is not supported or there is a problem loading the keystore.

The following options may be supported by the implementation:

  • password: (Str) - the password used to unlock the keystore or perform integrity checks.
ks := Crypto.cur.loadKeyStore(`keystore.p12`, ["password":"changeit"])

loadPem ​

abstract Obj? loadPem(InStream in, Str algorithm := "RSA")

Load the next PEM-encoded object from the input stream. Returns one of the following depending on the PEM encoding:

  • PrivKey
  • Cert
  • Csr

For PKCS#8, the algorithm argument will be used for decoding. This argument is ignored for PKCS#1 where the alogithm is inferred.

Returns null if there are no more PEM objects to decode. The input stream will be closed in this case.

key  := Crypto.cur.loadPem(`server.key`) as PrivKey
cert := Crypto.cur.loadPem(`server.pem`) as Cert

loadX509 ​

abstract Cert[] loadX509(InStream in)

Load all X.509 certificates from the given input stream.

The stream will be closed after reading the certificates.

cert := Crypto.cur.loadX509(`server.cert`).first

Csr ​

const mixin Csr

A Certificate Signing Request (CSR)

Methods

optsGet the immutable signing options
pubGet the public key for the CSR
subjectGet the subject dn

Slot Details ​


opts ​

abstract Str:Obj opts()

Get the immutable signing options


pub ​

abstract PubKey pub()

Get the public key for the CSR


subject ​

abstract Str subject()

Get the subject dn


Digest ​

const mixin Digest

A message digest algorithm

Methods

algorithmGet the digest algorithm name
digestComplete the digest computation and return the hash.
digestSizeGet the computed digest size in bytes
resetReset the digest.
updateUpdate the digest using all the bytes in the buf (regardless of current position).
updateAsciiUpdate the digest using only the 8-bit characters in given string.
updateByteUpdate the digest with one byte / 8-bit integer.
updateI4Update the digest with four byte / 32-bit integer.
updateI8Update the digest with eight byte / 64-bit integer.

Slot Details ​


algorithm ​

abstract Str algorithm()

Get the digest algorithm name


digest ​

abstract Buf digest()

Complete the digest computation and return the hash. The digest is reset after this method is called.


digestSize ​

abstract Int digestSize()

Get the computed digest size in bytes


reset ​

abstract This reset()

Reset the digest. Return this.


update ​

abstract This update(Buf buf)

Update the digest using all the bytes in the buf (regardless of current position). Return this.


updateAscii ​

abstract This updateAscii(Str str)

Update the digest using only the 8-bit characters in given string. Return this.


updateByte ​

abstract This updateByte(Int i)

Update the digest with one byte / 8-bit integer. Return this.


updateI4 ​

abstract This updateI4(Int i)

Update the digest with four byte / 32-bit integer. Return this.


updateI8 ​

abstract This updateI8(Int i)

Update the digest with eight byte / 64-bit integer. Return this.


Jwk ​

const mixin Jwk

Models a JSON Web Key (JWK) as specified by RFC7517

JWKs wrap a Key[Key] object with additional metadata

Methods

keyKey
metaJwk

Slot Details ​


key ​

abstract Key key()

Key


meta ​

abstract Str:Obj meta()

Jwk


Jwt ​

const class Jwt : Obj

Models a JSON Web Token (JWT) as specified by RFC7519

A JWT includes three sections:

  1. Javascript Object Signing and Encryption (JOSE) Header
  2. Claims
  3. Signature

11111111111.22222222222.33333333333

These sections are encoded as base64url strings and are separated by dot (.) characters.

The (alg) parameter must be set to a supported JWS algorithm.

The following JWS algorithms are supported:

  • HS256 - HMAC using SHA-256
  • HS384 - HMAC using SHA-384
  • HS512 - HMAC using SHA-512
  • RS256 - RSASSA-PKCS1-v1_5 using SHA-256
  • RS384 - RSASSA-PKCS1-v1_5 using SHA-384
  • RS512 - RSASSA-PKCS1-v1_5 using SHA-512
  • ES256 - ECDSA using P-256 and SHA-256
  • ES384 - ECDSA using P-256 and SHA-384
  • ES512 - ECDSA using P-256 and SHA-512
  • none - No digital signature or MAC performed

Constructors

decodeDecode a Jwt from an encoded Str
makeIt-block constructor

Fields

algAlgorithm header
audAudience claim for this token (Str or Str[])
claimsJWT Claims
expExpiration claim for this token
headerJOSE Header
iatIssued at claim for this token
issIssuer claim for this token
jtiJWT ID claim for this token
kidKey ID header
nbfNot before claim for this token
subSubject claim for this token

Methods

encodeProvide a Key (PrivKey or SymKey) to sign and return the base64 encoded Jwt
toStr
verifyClaimConvenience function to check the value of a claim

Slot Details ​


alg ​

const Str alg

Algorithm header


aud ​

const Obj? aud

Audience claim for this token (Str or Str[])

If value is a Str it will converted to a Str[] of size 1


claims ​

const Str:Obj claims := [Str:Obj][:]

JWT Claims


decode ​

static new decode(Str encoded, Obj key, Duration clockDrift := 1min)

Decode a Jwt from an encoded Str

The key parameter supports these types to verify the signature:

  • Key (PubKey or SymKey)

  • Jwk[] - An error is thrown if the Jwt kid header parameter

    is missing or no matching kid is found in the list

If the exp and/or nbf claims exist, those will be verified

jwk :=  [
          "kty": "EC",
          "use": "sig",
          "crv": "P-256",
          "kid": "abcd",
          "x": "I59TOAdnJ7uPgPOdIxj-BhWSQBXKS3lsRZJwj5eIYAo",
          "y": "8FJEvVIZDjVBnrBJPRUCwtgS86rHoFl1kBfbjX9rOng",
          "alg": "ES256",
        ]

ecJwk := Crypto.cur.loadJwk(jwk)

jwt   := Jwt.decode("1111.2222.3333", ecJwk.key)

jwks := Crypto.cur.loadJwksForUri(`https://example.com/jwks.json`)

jwt2  := Jwt.decodeJwks("4444.5555.6666", jwks)

encode ​

Str encode(Key? key)

Provide a Key (PrivKey or SymKey) to sign and return the base64 encoded Jwt

Null key will return an unsigned base64 encoded JWT

The alg field must be set to a supported JWS algorithm

The following JWS Algorithms are supported:

  • HS256 - HMAC using SHA-256
  • HS384 - HMAC using SHA-384
  • HS512 - HMAC using SHA-512
  • RS256 - RSASSA-PKCS1-v1_5 using SHA-256
  • RS384 - RSASSA-PKCS1-v1_5 using SHA-384
  • RS512 - RSASSA-PKCS1-v1_5 using SHA-512
  • ES256 - ECDSA using P-256 and SHA-256
  • ES384 - ECDSA using P-256 and SHA-384
  • ES512 - ECDSA using P-256 and SHA-512
  • none - No digital signature or MAC performed
pair   := Crypto.cur.genKeyPair("RSA", 2048)
priv   := pair.priv

jwtStr := Jwt {
             it.alg    = "RS256"
             it.claims = ["myClaim": "ClaimValue"]
             it.exp    = DateTime.nowUtc + 10min
             it.iss    = "https://fantom.accounts.dev"
          }.encode(priv)

exp ​

const DateTime? exp

Expiration claim for this token

When encoded, the value will be converted to TimeZone.utc, the epoch const will be subtracted from this value and it will be converted to seconds

When decoded, the value will be converted to TimeZone.utc


const Str:Obj header := [Str:Obj][:]

JOSE Header


iat ​

const DateTime? iat

Issued at claim for this token

When encoded, the value will be converted to TimeZone.utc, the epoch const will be subtracted from this value and it will be converted to seconds

When decoded, the value will be converted to TimeZone.utc


iss ​

const Str? iss

Issuer claim for this token


jti ​

const Str? jti

JWT ID claim for this token


kid ​

const Str? kid

Key ID header

When encoding this value will take precedent if the kid parameter is also set in the JOSE header


make ​

new make(|This| f)

It-block constructor


nbf ​

const DateTime? nbf

Not before claim for this token

When encoded, the value will be converted to TimeZone.utc, the epoch const will be subtracted from this value and it will be converted to seconds

When decoded, the value will be converted to TimeZone.utc


sub ​

const Str? sub

Subject claim for this token


toStr ​

virtual override Str toStr()


verifyClaim ​

This verifyClaim(Str claim, Obj? expectedValue := null)

Convenience function to check the value of a claim

If value of JWT claim is a List, this function checks that the expectedValue is contained in the List.

If expectedValue is null, just checks if the claim exists

Throws Err if claim does not exist or expectedValue does not match (or is not contained in the List)

jwt := Jwt.decode("1111.2222.3333", pubKey)
          .verifyClaim("iss", "https://fantom.accounts.dev")

Key ​

const mixin Key

Key defines the api for a cryptographic key.

Methods

algorithmThe key's algorithm.
encodedGet the encoded key, or null if the key doesn't support encoding.
formatGet the encoding format of the key, or null if the key doesn't support encoding.

Slot Details ​


algorithm ​

abstract Str algorithm()

The key's algorithm.


encoded ​

abstract Buf? encoded()

Get the encoded key, or null if the key doesn't support encoding.


format ​

abstract Str? format()

Get the encoding format of the key, or null if the key doesn't support encoding.


KeyPair ​

const mixin KeyPair

A KeyPair contains a private key and its corresponding public key in an asymmetric key pair.

Methods

algorithmGet the key pair algorithm
privThe private key for this pair.
pubThe public key for this pair.

Slot Details ​


algorithm ​

virtual Str algorithm()

Get the key pair algorithm


priv ​

abstract PrivKey priv()

The private key for this pair.


pub ​

abstract PubKey pub()

The public key for this pair.


KeyStore ​

const mixin KeyStore

KeyStore stores keys[Key] and certificates[Cert] in an aliased keystore entry. Aliases are case-insensitive.

See Crypto.loadKeyStore

Methods

aliasesGet all the aliases in the key store.
containsAliasReturn ture if the key store has an entry with the given alias.
formatGet the format that this keystore stores entries in.
getGet the entry with the given alias.
getPrivKeyConvenience to get a PrivKeyEntry from the keystore.
getTrustConvenience to get a TrustEntry from the keystore.
removeRemove the entry with the given alias.
saveSave the entries in the keystore to the output stream.
setSet an alias to have the given entry.
setPrivKeyAdds a PrivKeyEntry to the keystore with the given alias and returns it.
setTrustAdds a TrustEntry to the keystore with the given alias and returns it.
sizeGet the number of entries in the key store.

Slot Details ​


aliases ​

abstract Str[] aliases()

Get all the aliases in the key store.


containsAlias ​

virtual Bool containsAlias(Str alias)

Return ture if the key store has an entry with the given alias.


format ​

abstract Str format()

Get the format that this keystore stores entries in.


get ​

abstract KeyStoreEntry? get(Str alias, Bool checked := true)

Get the entry with the given alias.


getPrivKey ​

virtual PrivKeyEntry? getPrivKey(Str alias, Bool checked := true)

Convenience to get a PrivKeyEntry from the keystore.


getTrust ​

virtual TrustEntry? getTrust(Str alias, Bool checked := true)

Convenience to get a TrustEntry from the keystore.


remove ​

abstract Void remove(Str alias)

Remove the entry with the given alias.

Throws Err if the key store is not writable.


save ​

abstract Void save(OutStream out, Str:Obj options := [:])

Save the entries in the keystore to the output stream.


set ​

abstract This set(Str alias, KeyStoreEntry entry)

Set an alias to have the given entry. If the alias already exists, it is overwritten.

Throws Err if the key store is not writable.

Throws Err if the key store doesn't support writing the entry type.


setPrivKey ​

abstract This setPrivKey(Str alias, PrivKey priv, Cert[] chain)

Adds a PrivKeyEntry to the keystore with the given alias and returns it.


setTrust ​

abstract This setTrust(Str alias, Cert cert)

Adds a TrustEntry to the keystore with the given alias and returns it.


size ​

abstract Int size()

Get the number of entries in the key store.


KeyStoreEntry ​

const mixin KeyStoreEntry

Marker mixin for an entry in a keystore

Methods

attrsGet the attributes associated with this entry.

Slot Details ​


attrs ​

abstract Str:Str attrs()

Get the attributes associated with this entry. The attributes are immutable.


PrivKey ​

const mixin PrivKey : AsymKey

A private key in an asymmetric key pair. A private key can be used to sign and decrypt data.

Methods

decryptDecrypt the contents of the data buffer and return the result.
signSign the contents of the data buffer after applying the given digest algorithm and return the signature.

Slot Details ​


decrypt ​

abstract Buf decrypt(Buf data, Str padding := "PKCS1Padding")

Decrypt the contents of the data buffer and return the result. Throws Err if the decryption fails for any reason.

msg := privKey.decrypt(encrypted)

sign ​

abstract Buf sign(Buf data, Str digest)

Sign the contents of the data buffer after applying the given digest algorithm and return the signature. Throws Err if the digest algorithm is not supported.

signature := privKey.sign("Message".toBuf, "SHA512")

PrivKeyEntry ​

const mixin PrivKeyEntry : KeyStoreEntry

A PrivKeyEntry stores a private key and the certificate chain for the corresponding public key.

Methods

certGet the end entity certificate from the certificate chain; this should be the first entry in the certChain.
certChainGet the certificate chain from this entry.
keyPairGet the KeyPair for the entry.
privGet the private key from this entry.
pubConvenience to get the public key from the cert.

Slot Details ​


cert ​

virtual Cert cert()

Get the end entity certificate from the certificate chain; this should be the first entry in the certChain.


certChain ​

abstract Cert[] certChain()

Get the certificate chain from this entry.


keyPair ​

abstract KeyPair keyPair()

Get the KeyPair for the entry. It consists of the priv and pub keys from this entry.


priv ​

abstract PrivKey priv()

Get the private key from this entry.


pub ​

virtual PubKey pub()

Convenience to get the public key from the cert.


PubKey ​

const mixin PubKey : AsymKey

A public key in an asymmetric key pair. A public key can be used to verify and encrypt data.

Methods

encryptEncrypt the contents of the data buffer and return the result.
verifyThrows an Err if the digest algorithm is not supported.

Slot Details ​


encrypt ​

abstract Buf encrypt(Buf data, Str padding := "PKCS1Padding")

Encrypt the contents of the data buffer and return the result.

Throws an Err if the algorithm does not support encryption, or if the padding is not supported for the algorithm.

encrypted := pubKey.encrypt("Message".toBuf)

verify ​

abstract Bool verify(Buf data, Str digest, Buf signature)

Throws an Err if the digest algorithm is not supported.

valid := pubKey.verify("Message".toBuf, "SHA512", signature)

SymKey ​

const mixin SymKey : Key

A symmetric key

Slot Details ​


TrustEntry ​

const mixin TrustEntry : KeyStoreEntry

Keystore entry for a trusted certificate.

Methods

certGet the trusted certificate from this entry.

Slot Details ​


cert ​

abstract Cert cert()

Get the trusted certificate from this entry.