github.com/microsoft/moc@v0.17.1/pkg/certs/cert_utils.go (about) 1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the Apache v2.0 license. 3 4 package certs 5 6 import ( 7 "fmt" 8 "time" 9 10 "github.com/microsoft/moc/pkg/errors" 11 ) 12 13 const ( 14 // formatSHA256 is the prefix for pins that are full-length SHA-256 hashes encoded in base 16 (hex) 15 formatSHA256 = "sha256" 16 ) 17 18 type backOffFactor struct { 19 renewBackoffFactor float64 20 errorBackoffFactor float64 21 } 22 23 type backOffDuration struct { 24 RenewBackoffDuration time.Duration 25 ErrorBackoffDuration time.Duration 26 } 27 28 func NewBackOffFactor(renewBackoffFactor, errorBackoffFactor float64) (factor *backOffFactor, err error) { 29 if renewBackoffFactor <= 0 { 30 return nil, errors.Wrapf(errors.InvalidInput, "Factor renewBackoffFactor(%f) cannot be <= 0.0", renewBackoffFactor) 31 } 32 if errorBackoffFactor <= 0 { 33 return nil, errors.Wrapf(errors.InvalidInput, "Factor errorBackoffFactor(%f) cannot be <= 0.0", errorBackoffFactor) 34 } 35 return &backOffFactor{renewBackoffFactor: renewBackoffFactor, errorBackoffFactor: errorBackoffFactor}, nil 36 } 37 38 func calculateTime(before, after, now time.Time, factor *backOffFactor) (duration *backOffDuration) { 39 validity := after.Sub(before) 40 41 errorBackoff := time.Duration(float64(validity.Nanoseconds()) * factor.errorBackoffFactor) 42 43 tresh := time.Duration(float64(validity.Nanoseconds()) * factor.renewBackoffFactor) 44 45 treshNotAfter := after.Add(-tresh) 46 return &backOffDuration{RenewBackoffDuration: treshNotAfter.Sub(now), ErrorBackoffDuration: errorBackoff} 47 } 48 49 func CalculateRenewTime(certificate string, factor *backOffFactor) (duration *backOffDuration, err error) { 50 51 x509Cert, err := DecodeCertPEM([]byte(certificate)) 52 if err != nil { 53 return 54 } 55 fmt.Println("factor", factor) 56 return calculateTime(x509Cert.NotBefore, x509Cert.NotAfter, time.Now(), factor), nil 57 } 58 59 func IsCertificateExpired(certificate string) (bool, error) { 60 x509Cert, err := DecodeCertPEM([]byte(certificate)) 61 if err != nil { 62 return false, err 63 } 64 return x509Cert.NotAfter.Before(time.Now()), nil 65 }