code
stringlengths
11
335k
docstring
stringlengths
20
11.8k
func_name
stringlengths
1
100
language
stringclasses
1 value
repo
stringclasses
245 values
path
stringlengths
4
144
url
stringlengths
43
214
license
stringclasses
4 values
func compareTypes(a cty.Type, b cty.Type) int { // DynamicPseudoType always has lowest preference, because anything can // convert to it (it acts as a placeholder for "any type") and we want // to optimistically assume that any dynamics will converge on matching // their neighbors. if a == cty.DynamicPseudoType || b == cty.DynamicPseudoType { if a != cty.DynamicPseudoType { return -1 } if b != cty.DynamicPseudoType { return 1 } return 0 } if a.IsPrimitiveType() && b.IsPrimitiveType() { // String is a supertype of all primitive types, because we can // represent all primitive values as specially-formatted strings. if a == cty.String || b == cty.String { if a != cty.String { return 1 } if b != cty.String { return -1 } return 0 } } if a.IsListType() && b.IsListType() { return compareTypes(a.ElementType(), b.ElementType()) } if a.IsSetType() && b.IsSetType() { return compareTypes(a.ElementType(), b.ElementType()) } if a.IsMapType() && b.IsMapType() { return compareTypes(a.ElementType(), b.ElementType()) } // From this point on we may have swapped the two items in order to // simplify our cases. Therefore any non-zero return after this point // must be multiplied by "swap" to potentially invert the return value // if needed. swap := 1 switch { case a.IsTupleType() && b.IsListType(): fallthrough case a.IsObjectType() && b.IsMapType(): fallthrough case a.IsSetType() && b.IsTupleType(): fallthrough case a.IsSetType() && b.IsListType(): a, b = b, a swap = -1 } if b.IsSetType() && (a.IsTupleType() || a.IsListType()) { // We'll just optimistically assume that the element types are // unifyable/convertible, and let a second recursive pass // figure out how to make that so. return -1 * swap } if a.IsListType() && b.IsTupleType() { // We'll just optimistically assume that the tuple's element types // can be unified into something compatible with the list's element // type. return -1 * swap } if a.IsMapType() && b.IsObjectType() { // We'll just optimistically assume that the object's attribute types // can be unified into something compatible with the map's element // type. return -1 * swap } // For object and tuple types, comparing two types doesn't really tell // the whole story because it may be possible to construct a new type C // that is the supertype of both A and B by unifying each attribute/element // separately. That possibility is handled by Unify as a follow-up if // type sorting is insufficient to produce a valid result. // // Here we will take care of the simple possibilities where no new type // is needed. if a.IsObjectType() && b.IsObjectType() { atysA := a.AttributeTypes() atysB := b.AttributeTypes() if len(atysA) != len(atysB) { return 0 } hasASuper := false hasBSuper := false for k := range atysA { if _, has := atysB[k]; !has { return 0 } cmp := compareTypes(atysA[k], atysB[k]) if cmp < 0 { hasASuper = true } else if cmp > 0 { hasBSuper = true } } switch { case hasASuper && hasBSuper: return 0 case hasASuper: return -1 * swap case hasBSuper: return 1 * swap default: return 0 } } if a.IsTupleType() && b.IsTupleType() { etysA := a.TupleElementTypes() etysB := b.TupleElementTypes() if len(etysA) != len(etysB) { return 0 } hasASuper := false hasBSuper := false for i := range etysA { cmp := compareTypes(etysA[i], etysB[i]) if cmp < 0 { hasASuper = true } else if cmp > 0 { hasBSuper = true } } switch { case hasASuper && hasBSuper: return 0 case hasASuper: return -1 * swap case hasBSuper: return 1 * swap default: return 0 } } return 0 }
compareTypes implements a preference order for unification. The result of this method is not useful for anything other than unification preferences, since it assumes that the caller will verify that any suggested conversion is actually possible and it is thus able to to make certain optimistic assumptions.
compareTypes
go
integrations/terraform-provider-github
vendor/github.com/zclconf/go-cty/cty/convert/compare_types.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/zclconf/go-cty/cty/convert/compare_types.go
MIT
func unify(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { if len(types) == 0 { // Degenerate case return cty.NilType, nil } // If all of the given types are of the same structural kind, we may be // able to construct a new type that they can all be unified to, even if // that is not one of the given types. We must try this before the general // behavior below because in unsafe mode we can convert an object type to // a subset of that type, which would be a much less useful conversion for // unification purposes. { mapCt := 0 listCt := 0 setCt := 0 objectCt := 0 tupleCt := 0 dynamicCt := 0 for _, ty := range types { switch { case ty.IsMapType(): mapCt++ case ty.IsListType(): listCt++ case ty.IsSetType(): setCt++ case ty.IsObjectType(): objectCt++ case ty.IsTupleType(): tupleCt++ case ty == cty.DynamicPseudoType: dynamicCt++ default: break } } switch { case mapCt > 0 && (mapCt+dynamicCt) == len(types): return unifyCollectionTypes(cty.Map, types, unsafe, dynamicCt > 0) case mapCt > 0 && (mapCt+objectCt+dynamicCt) == len(types): // Objects often contain map data, but are not directly typed as // such due to language constructs or function types. Try to unify // them as maps first before falling back to heterogeneous type // conversion. ty, convs := unifyObjectsAsMaps(types, unsafe) // If we got a map back, we know the unification was successful. if ty.IsMapType() { return ty, convs } case listCt > 0 && (listCt+dynamicCt) == len(types): return unifyCollectionTypes(cty.List, types, unsafe, dynamicCt > 0) case listCt > 0 && (listCt+tupleCt+dynamicCt) == len(types): // Tuples are often lists in disguise, and we may be able to // unify them as such. ty, convs := unifyTuplesAsList(types, unsafe) // if we got a list back, we know the unification was successful. // Otherwise we will fall back to the heterogeneous type codepath. if ty.IsListType() { return ty, convs } case setCt > 0 && (setCt+dynamicCt) == len(types): return unifyCollectionTypes(cty.Set, types, unsafe, dynamicCt > 0) case objectCt > 0 && (objectCt+dynamicCt) == len(types): return unifyObjectTypes(types, unsafe, dynamicCt > 0) case tupleCt > 0 && (tupleCt+dynamicCt) == len(types): return unifyTupleTypes(types, unsafe, dynamicCt > 0) case objectCt > 0 && tupleCt > 0: // Can never unify object and tuple types since they have incompatible kinds return cty.NilType, nil } } prefOrder := sortTypes(types) // sortTypes gives us an order where earlier items are preferable as // our result type. We'll now walk through these and choose the first // one we encounter for which conversions exist for all source types. conversions := make([]Conversion, len(types)) Preferences: for _, wantTypeIdx := range prefOrder { wantType := types[wantTypeIdx] for i, tryType := range types { if i == wantTypeIdx { // Don't need to convert our wanted type to itself conversions[i] = nil continue } if tryType.Equals(wantType) { conversions[i] = nil continue } if unsafe { conversions[i] = GetConversionUnsafe(tryType, wantType) } else { conversions[i] = GetConversion(tryType, wantType) } if conversions[i] == nil { // wantType is not a suitable unification type, so we'll // try the next one in our preference order. continue Preferences } } return wantType, conversions } // If we fall out here, no unification is possible return cty.NilType, nil }
The current unify implementation is somewhat inefficient, but we accept this under the assumption that it will generally be used with small numbers of types and with types of reasonable complexity. However, it does have a "happy path" where all of the given types are equal. This function is likely to have poor performance in cases where any given types are very complex (lots of deeply-nested structures) or if the list of types itself is very large. In particular, it will walk the nested type structure under the given types several times, especially when given a list of types for which unification is not possible, since each permutation will be tried to determine that result.
unify
go
integrations/terraform-provider-github
vendor/github.com/zclconf/go-cty/cty/convert/unify.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/zclconf/go-cty/cty/convert/unify.go
MIT
func unifyTuplesAsList(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { var tuples []cty.Type var tupleIdxs []int for i, t := range types { if t.IsTupleType() { tuples = append(tuples, t) tupleIdxs = append(tupleIdxs, i) } } ty, tupleConvs := unifyTupleTypesToList(tuples, unsafe) if !ty.IsListType() { return cty.NilType, nil } // the tuples themselves unified as a list, get the overall // unification with this list type instead of the tuple. // make a copy of the types, so we can fallback to the standard // codepath if something went wrong listed := make([]cty.Type, len(types)) copy(listed, types) for _, idx := range tupleIdxs { listed[idx] = ty } newTy, convs := unify(listed, unsafe) if !newTy.IsListType() { return cty.NilType, nil } // we have a good conversion, wrap the nested tuple conversions. // We know the tuple conversion is not nil, because we went from tuple to // list for i, idx := range tupleIdxs { listConv := convs[idx] tupleConv := tupleConvs[i] if listConv == nil { convs[idx] = tupleConv continue } convs[idx] = func(in cty.Value) (out cty.Value, err error) { out, err = tupleConv(in) if err != nil { return out, err } return listConv(in) } } return newTy, convs }
unifyTuplesAsList attempts to first see if the tuples unify as lists, then re-unifies the given types with the list in place of the tuples.
unifyTuplesAsList
go
integrations/terraform-provider-github
vendor/github.com/zclconf/go-cty/cty/convert/unify.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/zclconf/go-cty/cty/convert/unify.go
MIT
func unifyObjectsAsMaps(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { var objs []cty.Type var objIdxs []int for i, t := range types { if t.IsObjectType() { objs = append(objs, t) objIdxs = append(objIdxs, i) } } ty, objConvs := unifyObjectTypesToMap(objs, unsafe) if !ty.IsMapType() { return cty.NilType, nil } // the objects themselves unified as a map, get the overall // unification with this map type instead of the object. // Make a copy of the types, so we can fallback to the standard codepath if // something went wrong without changing the original types. mapped := make([]cty.Type, len(types)) copy(mapped, types) for _, idx := range objIdxs { mapped[idx] = ty } newTy, convs := unify(mapped, unsafe) if !newTy.IsMapType() { return cty.NilType, nil } // we have a good conversion, so wrap the nested object conversions. // We know the object conversion is not nil, because we went from object to // map. for i, idx := range objIdxs { mapConv := convs[idx] objConv := objConvs[i] if mapConv == nil { convs[idx] = objConv continue } convs[idx] = func(in cty.Value) (out cty.Value, err error) { out, err = objConv(in) if err != nil { return out, err } return mapConv(in) } } return newTy, convs }
unifyObjectsAsMaps attempts to first see if the objects unify as maps, then re-unifies the given types with the map in place of the objects.
unifyObjectsAsMaps
go
integrations/terraform-provider-github
vendor/github.com/zclconf/go-cty/cty/convert/unify.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/zclconf/go-cty/cty/convert/unify.go
MIT
func sortTypes(tys []cty.Type) []int { l := len(tys) // First we build a graph whose edges represent "more general than", // which we will then do a topological sort of. edges := make([][]int, l) for i := 0; i < (l - 1); i++ { for j := i + 1; j < l; j++ { cmp := compareTypes(tys[i], tys[j]) switch { case cmp < 0: edges[i] = append(edges[i], j) case cmp > 0: edges[j] = append(edges[j], i) } } } // Compute the in-degree of each node inDegree := make([]int, l) for _, outs := range edges { for _, j := range outs { inDegree[j]++ } } // The array backing our result will double as our queue for visiting // the nodes, with the queue slice moving along this array until it // is empty and positioned at the end of the array. Thus our visiting // order is also our result order. result := make([]int, l) queue := result[0:0] // Initialize the queue with any item of in-degree 0, preserving // their relative order. for i, n := range inDegree { if n == 0 { queue = append(queue, i) } } for len(queue) != 0 { i := queue[0] queue = queue[1:] for _, j := range edges[i] { inDegree[j]-- if inDegree[j] == 0 { queue = append(queue, j) } } } return result }
sortTypes produces an ordering of the given types that serves as a preference order for the result of unification of the given types. The return value is a slice of indices into the given slice, and will thus always be the same length as the given slice. The goal is that the most general of the given types will appear first in the ordering. If there are uncomparable pairs of types in the list then they will appear in an undefined order, and the unification pass will presumably then fail.
sortTypes
go
integrations/terraform-provider-github
vendor/github.com/zclconf/go-cty/cty/convert/sort_types.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/zclconf/go-cty/cty/convert/sort_types.go
MIT
func GfnDouble(input []byte) []byte { if len(input) != 16 { panic("Doubling in GFn only implemented for n = 128") } // If the first bit is zero, return 2L = L << 1 // Else return (L << 1) xor 0^120 10000111 shifted := ShiftBytesLeft(input) shifted[15] ^= ((input[0] >> 7) * 0x87) return shifted }
GfnDouble computes 2 * input in the field of 2^n elements. The irreducible polynomial in the finite field for n=128 is x^128 + x^7 + x^2 + x + 1 (equals 0x87) Constant-time execution in order to avoid side-channel attacks
GfnDouble
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func ShiftBytesLeft(x []byte) []byte { l := len(x) dst := make([]byte, l) for i := 0; i < l-1; i++ { dst[i] = (x[i] << 1) | (x[i+1] >> 7) } dst[l-1] = x[l-1] << 1 return dst }
ShiftBytesLeft outputs the byte array corresponding to x << 1 in binary.
ShiftBytesLeft
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func ShiftNBytesLeft(dst, x []byte, n int) { // Erase first n / 8 bytes copy(dst, x[n/8:]) // Shift the remaining n % 8 bits bits := uint(n % 8) l := len(dst) for i := 0; i < l-1; i++ { dst[i] = (dst[i] << bits) | (dst[i+1] >> uint(8-bits)) } dst[l-1] = dst[l-1] << bits // Append trailing zeroes dst = append(dst, make([]byte, n/8)...) }
ShiftNBytesLeft puts in dst the byte array corresponding to x << n in binary.
ShiftNBytesLeft
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func XorBytesMut(X, Y []byte) { for i := 0; i < len(X); i++ { X[i] ^= Y[i] } }
XorBytesMut assumes equal input length, replaces X with X XOR Y
XorBytesMut
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func XorBytes(Z, X, Y []byte) { for i := 0; i < len(X); i++ { Z[i] = X[i] ^ Y[i] } }
XorBytes assumes equal input length, puts X XOR Y into Z
XorBytes
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func RightXor(X, Y []byte) []byte { offset := len(X) - len(Y) xored := make([]byte, len(X)) copy(xored, X) for i := 0; i < len(Y); i++ { xored[offset+i] ^= Y[i] } return xored }
RightXor XORs smaller input (assumed Y) at the right of the larger input (assumed X)
RightXor
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func SliceForAppend(in []byte, n int) (head, tail []byte) { if total := len(in) + n; cap(in) >= total { head = in[:total] } else { head = make([]byte, total) copy(head, in) } tail = head[len(in):] return }
SliceForAppend takes a slice and a requested number of bytes. It returns a slice with the contents of the given slice followed by that many bytes and a second slice that aliases into it and contains only the extra bytes. If the original slice has sufficient capacity then no allocation is performed.
SliceForAppend
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go
MIT
func (bitCurve *BitCurve) Params() (cp *elliptic.CurveParams) { cp = new(elliptic.CurveParams) cp.Name = bitCurve.Name cp.P = bitCurve.P cp.N = bitCurve.N cp.Gx = bitCurve.Gx cp.Gy = bitCurve.Gy cp.BitSize = bitCurve.BitSize return cp }
Params returns the parameters of the given BitCurve (see BitCurve struct)
Params
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y) //y² y2.Mod(y2, bitCurve.P) //y²%P x3 := new(big.Int).Mul(x, x) //x² x3.Mul(x3, x) //x³ x3.Add(x3, bitCurve.B) //x³+B x3.Mod(x3, bitCurve.P) //(x³+B)%P return x3.Cmp(y2) == 0 }
IsOnCurve returns true if the given (x,y) lies on the BitCurve.
IsOnCurve
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { if z.Cmp(big.NewInt(0)) == 0 { panic("bitcurve: Can't convert to affine with Jacobian Z = 0") } // x = YZ^2 mod P zinv := new(big.Int).ModInverse(z, bitCurve.P) zinvsq := new(big.Int).Mul(zinv, zinv) xOut = new(big.Int).Mul(x, zinvsq) xOut.Mod(xOut, bitCurve.P) // y = YZ^3 mod P zinvsq.Mul(zinvsq, zinv) yOut = new(big.Int).Mul(y, zinvsq) yOut.Mod(yOut, bitCurve.P) return xOut, yOut }
affineFromJacobian reverses the Jacobian transform. See the comment at the top of the file.
affineFromJacobian
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { z := new(big.Int).SetInt64(1) x, y, z := bitCurve.addJacobian(x1, y1, z, x2, y2, z) return bitCurve.affineFromJacobian(x, y, z) }
Add returns the sum of (x1,y1) and (x2,y2)
Add
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) z1z1.Mod(z1z1, bitCurve.P) z2z2 := new(big.Int).Mul(z2, z2) z2z2.Mod(z2z2, bitCurve.P) u1 := new(big.Int).Mul(x1, z2z2) u1.Mod(u1, bitCurve.P) u2 := new(big.Int).Mul(x2, z1z1) u2.Mod(u2, bitCurve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { h.Add(h, bitCurve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) j := new(big.Int).Mul(h, i) s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) s1.Mod(s1, bitCurve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) s2.Mod(s2, bitCurve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { r.Add(r, bitCurve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) x3 := new(big.Int).Set(r) x3.Mul(x3, x3) x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) x3.Mod(x3, bitCurve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) y3.Mul(y3, v) s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) y3.Mod(y3, bitCurve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { z3.Add(z3, bitCurve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { z3.Add(z3, bitCurve.P) } z3.Mul(z3, h) z3.Mod(z3, bitCurve.P) return x3, y3, z3 }
addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and (x2, y2, z2) and returns their sum, also in Jacobian form.
addJacobian
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { z1 := new(big.Int).SetInt64(1) return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) }
Double returns 2*(x,y)
Double
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l a := new(big.Int).Mul(x, x) //X1² b := new(big.Int).Mul(y, y) //Y1² c := new(big.Int).Mul(b, b) //B² d := new(big.Int).Add(x, b) //X1+B d.Mul(d, d) //(X1+B)² d.Sub(d, a) //(X1+B)²-A d.Sub(d, c) //(X1+B)²-A-C d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C) e := new(big.Int).Mul(big.NewInt(3), a) //3*A f := new(big.Int).Mul(e, e) //E² x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D x3.Sub(f, x3) //F-2*D x3.Mod(x3, bitCurve.P) y3 := new(big.Int).Sub(d, x3) //D-X3 y3.Mul(e, y3) //E*(D-X3) y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C y3.Mod(y3, bitCurve.P) z3 := new(big.Int).Mul(y, z) //Y1*Z1 z3.Mul(big.NewInt(2), z3) //3*Y1*Z1 z3.Mod(z3, bitCurve.P) return x3, y3, z3 }
doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and returns its double, also in Jacobian form.
doubleJacobian
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { // We have a slight problem in that the identity of the group (the // point at infinity) cannot be represented in (x, y) form on a finite // machine. Thus the standard add/double algorithm has to be tweaked // slightly: our initial state is not the identity, but x, and we // ignore the first true bit in |k|. If we don't find any true bits in // |k|, then we return nil, nil, because we cannot return the identity // element. Bz := new(big.Int).SetInt64(1) x := Bx y := By z := Bz seenFirstTrue := false for _, byte := range k { for bitNum := 0; bitNum < 8; bitNum++ { if seenFirstTrue { x, y, z = bitCurve.doubleJacobian(x, y, z) } if byte&0x80 == 0x80 { if !seenFirstTrue { seenFirstTrue = true } else { x, y, z = bitCurve.addJacobian(Bx, By, Bz, x, y, z) } } byte <<= 1 } } if !seenFirstTrue { return nil, nil } return bitCurve.affineFromJacobian(x, y, z) }
TODO: double check if it is okay ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
ScalarMult
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) }
ScalarBaseMult returns k*G, where G is the base point of the group and k is an integer in big-endian form.
ScalarBaseMult
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) { byteLen := (bitCurve.BitSize + 7) >> 3 priv = make([]byte, byteLen) for x == nil { _, err = io.ReadFull(rand, priv) if err != nil { return } // We have to mask off any excess bits in the case that the size of the // underlying field is not a whole number of bytes. priv[0] &= mask[bitCurve.BitSize%8] // This is because, in tests, rand will return all zeros and we don't // want to get the point at infinity and loop forever. priv[1] ^= 0x42 x, y = bitCurve.ScalarBaseMult(priv) } return }
TODO: double check if it is okay GenerateKey returns a public/private key pair. The private key is generated using the given reader, which must return random data.
GenerateKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) Marshal(x, y *big.Int) []byte { byteLen := (bitCurve.BitSize + 7) >> 3 ret := make([]byte, 1+2*byteLen) ret[0] = 4 // uncompressed point xBytes := x.Bytes() copy(ret[1+byteLen-len(xBytes):], xBytes) yBytes := y.Bytes() copy(ret[1+2*byteLen-len(yBytes):], yBytes) return ret }
Marshal converts a point into the form specified in section 4.3.6 of ANSI X9.62.
Marshal
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func (bitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { byteLen := (bitCurve.BitSize + 7) >> 3 if len(data) != 1+2*byteLen { return } if data[0] != 4 { // uncompressed form return } x = new(big.Int).SetBytes(data[1 : 1+byteLen]) y = new(big.Int).SetBytes(data[1+byteLen:]) return }
Unmarshal converts a point, serialised by Marshal, into an x, y pair. On error, x = nil.
Unmarshal
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func S160() *BitCurve { initonce.Do(initAll) return secp160k1 }
S160 returns a BitCurve which implements secp160k1 (see SEC 2 section 2.4.1)
S160
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func S192() *BitCurve { initonce.Do(initAll) return secp192k1 }
S192 returns a BitCurve which implements secp192k1 (see SEC 2 section 2.5.1)
S192
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func S224() *BitCurve { initonce.Do(initAll) return secp224k1 }
S224 returns a BitCurve which implements secp224k1 (see SEC 2 section 2.6.1)
S224
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func S256() *BitCurve { initonce.Do(initAll) return secp256k1 }
S256 returns a BitCurve which implements bitcurves (see SEC 2 section 2.7.1)
S256
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go
MIT
func NewOCB(block cipher.Block) (cipher.AEAD, error) { return NewOCBWithNonceAndTagSize(block, defaultNonceSize, defaultTagSize) }
NewOCB returns an OCB instance with the given block cipher and default tag and nonce sizes.
NewOCB
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
MIT
func NewOCBWithNonceAndTagSize( block cipher.Block, nonceSize, tagSize int) (cipher.AEAD, error) { if block.BlockSize() != 16 { return nil, ocbError("Block cipher must have 128-bit blocks") } if nonceSize < 1 { return nil, ocbError("Incorrect nonce length") } if nonceSize >= block.BlockSize() { return nil, ocbError("Nonce length exceeds blocksize - 1") } if tagSize > block.BlockSize() { return nil, ocbError("Custom tag length exceeds blocksize") } return &ocb{ block: block, tagSize: tagSize, nonceSize: nonceSize, mask: initializeMaskTable(block), reusableKtop: reusableKtop{ noncePrefix: nil, Ktop: nil, }, }, nil }
NewOCBWithNonceAndTagSize returns an OCB instance with the given block cipher, nonce length, and tag length. Panics on zero nonceSize and exceedingly long tag size. It is recommended to use at least 12 bytes as tag length.
NewOCBWithNonceAndTagSize
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
MIT
func (o *ocb) crypt(instruction int, Y, nonce, adata, X []byte) []byte { // // Consider X as a sequence of 128-bit blocks // // Note: For encryption (resp. decryption), X is the plaintext (resp., the // ciphertext without the tag). blockSize := o.block.BlockSize() // // Nonce-dependent and per-encryption variables // // Zero out the last 6 bits of the nonce into truncatedNonce to see if Ktop // is already computed. truncatedNonce := make([]byte, len(nonce)) copy(truncatedNonce, nonce) truncatedNonce[len(truncatedNonce)-1] &= 192 var Ktop []byte if bytes.Equal(truncatedNonce, o.reusableKtop.noncePrefix) { Ktop = o.reusableKtop.Ktop } else { // Nonce = num2str(TAGLEN mod 128, 7) || zeros(120 - bitlen(N)) || 1 || N paddedNonce := append(make([]byte, blockSize-1-len(nonce)), 1) paddedNonce = append(paddedNonce, truncatedNonce...) paddedNonce[0] |= byte(((8 * o.tagSize) % (8 * blockSize)) << 1) // Last 6 bits of paddedNonce are already zero. Encrypt into Ktop paddedNonce[blockSize-1] &= 192 Ktop = paddedNonce o.block.Encrypt(Ktop, Ktop) o.reusableKtop.noncePrefix = truncatedNonce o.reusableKtop.Ktop = Ktop } // Stretch = Ktop || ((lower half of Ktop) XOR (lower half of Ktop << 8)) xorHalves := make([]byte, blockSize/2) byteutil.XorBytes(xorHalves, Ktop[:blockSize/2], Ktop[1:1+blockSize/2]) stretch := append(Ktop, xorHalves...) bottom := int(nonce[len(nonce)-1] & 63) offset := make([]byte, len(stretch)) byteutil.ShiftNBytesLeft(offset, stretch, bottom) offset = offset[:blockSize] // // Process any whole blocks // // Note: For encryption Y is ciphertext || tag, for decryption Y is // plaintext || tag. checksum := make([]byte, blockSize) m := len(X) / blockSize for i := 0; i < m; i++ { index := bits.TrailingZeros(uint(i + 1)) if len(o.mask.L)-1 < index { o.mask.extendTable(index) } byteutil.XorBytesMut(offset, o.mask.L[bits.TrailingZeros(uint(i+1))]) blockX := X[i*blockSize : (i+1)*blockSize] blockY := Y[i*blockSize : (i+1)*blockSize] byteutil.XorBytes(blockY, blockX, offset) switch instruction { case enc: o.block.Encrypt(blockY, blockY) byteutil.XorBytesMut(blockY, offset) byteutil.XorBytesMut(checksum, blockX) case dec: o.block.Decrypt(blockY, blockY) byteutil.XorBytesMut(blockY, offset) byteutil.XorBytesMut(checksum, blockY) } } // // Process any final partial block and compute raw tag // tag := make([]byte, blockSize) if len(X)%blockSize != 0 { byteutil.XorBytesMut(offset, o.mask.lAst) pad := make([]byte, blockSize) o.block.Encrypt(pad, offset) chunkX := X[blockSize*m:] chunkY := Y[blockSize*m : len(X)] byteutil.XorBytes(chunkY, chunkX, pad[:len(chunkX)]) // P_* || bit(1) || zeroes(127) - len(P_*) switch instruction { case enc: paddedY := append(chunkX, byte(128)) paddedY = append(paddedY, make([]byte, blockSize-len(chunkX)-1)...) byteutil.XorBytesMut(checksum, paddedY) case dec: paddedX := append(chunkY, byte(128)) paddedX = append(paddedX, make([]byte, blockSize-len(chunkY)-1)...) byteutil.XorBytesMut(checksum, paddedX) } byteutil.XorBytes(tag, checksum, offset) byteutil.XorBytesMut(tag, o.mask.lDol) o.block.Encrypt(tag, tag) byteutil.XorBytesMut(tag, o.hash(adata)) copy(Y[blockSize*m+len(chunkY):], tag[:o.tagSize]) } else { byteutil.XorBytes(tag, checksum, offset) byteutil.XorBytesMut(tag, o.mask.lDol) o.block.Encrypt(tag, tag) byteutil.XorBytesMut(tag, o.hash(adata)) copy(Y[blockSize*m:], tag[:o.tagSize]) } return Y }
On instruction enc (resp. dec), crypt is the encrypt (resp. decrypt) function. It returns the resulting plain/ciphertext with the tag appended.
crypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
MIT
func (o *ocb) hash(adata []byte) []byte { // // Consider A as a sequence of 128-bit blocks // A := make([]byte, len(adata)) copy(A, adata) blockSize := o.block.BlockSize() // // Process any whole blocks // sum := make([]byte, blockSize) offset := make([]byte, blockSize) m := len(A) / blockSize for i := 0; i < m; i++ { chunk := A[blockSize*i : blockSize*(i+1)] index := bits.TrailingZeros(uint(i + 1)) // If the mask table is too short if len(o.mask.L)-1 < index { o.mask.extendTable(index) } byteutil.XorBytesMut(offset, o.mask.L[index]) byteutil.XorBytesMut(chunk, offset) o.block.Encrypt(chunk, chunk) byteutil.XorBytesMut(sum, chunk) } // // Process any final partial block; compute final hash value // if len(A)%blockSize != 0 { byteutil.XorBytesMut(offset, o.mask.lAst) // Pad block with 1 || 0 ^ 127 - bitlength(a) ending := make([]byte, blockSize-len(A)%blockSize) ending[0] = 0x80 encrypted := append(A[blockSize*m:], ending...) byteutil.XorBytesMut(encrypted, offset) o.block.Encrypt(encrypted, encrypted) byteutil.XorBytesMut(sum, encrypted) } return sum }
This hash function is used to compute the tag. Per design, on empty input it returns a slice of zeros, of the same length as the underlying block cipher block size.
hash
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
MIT
func (m *mask) extendTable(limit int) { for i := len(m.L); i <= limit; i++ { m.L = append(m.L, byteutil.GfnDouble(m.L[i-1])) } }
Extends the L array of mask m up to L[limit], with L[i] = GfnDouble(L[i-1])
extendTable
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go
MIT
func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { block, err := armor.Decode(r) if err != nil { return } if block.Type != expectedType { return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) } return block.Body, nil }
readArmored reads an armored block with the given type.
readArmored
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { var p packet.Packet var symKeys []*packet.SymmetricKeyEncrypted var pubKeys []keyEnvelopePair // Integrity protected encrypted packet: SymmetricallyEncrypted or AEADEncrypted var edp packet.EncryptedDataPacket packets := packet.NewReader(r) md = new(MessageDetails) md.IsEncrypted = true // The message, if encrypted, starts with a number of packets // containing an encrypted decryption key. The decryption key is either // encrypted to a public key, or with a passphrase. This loop // collects these packets. ParsePackets: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.SymmetricKeyEncrypted: // This packet contains the decryption key encrypted with a passphrase. md.IsSymmetricallyEncrypted = true symKeys = append(symKeys, p) case *packet.EncryptedKey: // This packet contains the decryption key encrypted to a public key. md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) switch p.Algo { case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH, packet.PubKeyAlgoX25519, packet.PubKeyAlgoX448: break default: continue } if keyring != nil { var keys []Key if p.KeyId == 0 { keys = keyring.DecryptionKeys() } else { keys = keyring.KeysById(p.KeyId) } for _, k := range keys { pubKeys = append(pubKeys, keyEnvelopePair{k, p}) } } case *packet.SymmetricallyEncrypted: if !p.IntegrityProtected && !config.AllowUnauthenticatedMessages() { return nil, errors.UnsupportedError("message is not integrity protected") } edp = p break ParsePackets case *packet.AEADEncrypted: edp = p break ParsePackets case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: // This message isn't encrypted. if len(symKeys) != 0 || len(pubKeys) != 0 { return nil, errors.StructuralError("key material not followed by encrypted message") } packets.Unread(p) return readSignedMessage(packets, nil, keyring, config) } }
ReadMessage parses an OpenPGP message that may be signed and/or encrypted. The given KeyRing should contain both public keys (for signature verification) and, possibly encrypted, private keys for decrypting. If config is nil, sensible defaults will be used.
ReadMessage
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing, config *packet.Config) (md *MessageDetails, err error) { if mdin == nil { mdin = new(MessageDetails) } md = mdin var p packet.Packet var h hash.Hash var wrappedHash hash.Hash var prevLast bool FindLiteralData: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.Compressed: if err := packets.Push(p.Body); err != nil { return nil, err } case *packet.OnePassSignature: if prevLast { return nil, errors.UnsupportedError("nested signature packets") } if p.IsLast { prevLast = true } h, wrappedHash, err = hashForSignature(p.Hash, p.SigType, p.Salt) if err != nil { md.SignatureError = err } md.IsSigned = true if p.Version == 6 { md.SignedByFingerprint = p.KeyFingerprint } md.SignedByKeyId = p.KeyId if keyring != nil { keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign) if len(keys) > 0 { md.SignedBy = &keys[0] } } case *packet.LiteralData: md.LiteralData = p break FindLiteralData } }
readSignedMessage reads a possibly signed message if mdin is non-zero then that structure is updated and returned. Otherwise a fresh MessageDetails is used.
readSignedMessage
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func hashForSignature(hashFunc crypto.Hash, sigType packet.SignatureType, sigSalt []byte) (hash.Hash, hash.Hash, error) { if _, ok := algorithm.HashToHashIdWithSha1(hashFunc); !ok { return nil, nil, errors.UnsupportedError("unsupported hash function") } if !hashFunc.Available() { return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashFunc))) } h := hashFunc.New() if sigSalt != nil { h.Write(sigSalt) } wrappedHash, err := wrapHashForSignature(h, sigType) if err != nil { return nil, nil, err } switch sigType { case packet.SigTypeBinary: return h, wrappedHash, nil case packet.SigTypeText: return h, wrappedHash, nil } return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) }
hashForSignature returns a pair of hashes that can be used to verify a signature. The signature may specify that the contents of the signed message should be preprocessed (i.e. to normalize line endings). Thus this function returns two hashes. The second should be used to hash the message itself and performs any needed preprocessing.
hashForSignature
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func VerifyDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) { return verifyDetachedSignature(keyring, signed, signature, nil, false, config) }
VerifyDetachedSignature takes a signed file and a detached signature and returns the signature packet and the entity the signature was signed by, if any, and a possible signature verification error. If the signer isn't known, ErrUnknownIssuer is returned.
VerifyDetachedSignature
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func VerifyDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) { return verifyDetachedSignature(keyring, signed, signature, expectedHashes, true, config) }
VerifyDetachedSignatureAndHash performs the same actions as VerifyDetachedSignature and checks that the expected hash functions were used.
VerifyDetachedSignatureAndHash
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) { _, signer, err = verifyDetachedSignature(keyring, signed, signature, nil, false, config) return }
CheckDetachedSignature takes a signed file and a detached signature and returns the entity the signature was signed by, if any, and a possible signature verification error. If the signer isn't known, ErrUnknownIssuer is returned.
CheckDetachedSignature
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (signer *Entity, err error) { _, signer, err = verifyDetachedSignature(keyring, signed, signature, expectedHashes, true, config) return }
CheckDetachedSignatureAndHash performs the same actions as CheckDetachedSignature and checks that the expected hash functions were used.
CheckDetachedSignatureAndHash
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) { body, err := readArmored(signature, SignatureType) if err != nil { return } return CheckDetachedSignature(keyring, signed, body, config) }
CheckArmoredDetachedSignature performs the same actions as CheckDetachedSignature but expects the signature to be armored.
CheckArmoredDetachedSignature
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func checkSignatureDetails(key *Key, signature *packet.Signature, config *packet.Config) error { now := config.Now() primarySelfSignature, primaryIdentity := key.Entity.PrimarySelfSignature() signedBySubKey := key.PublicKey != key.Entity.PrimaryKey sigsToCheck := []*packet.Signature{signature, primarySelfSignature} if signedBySubKey { sigsToCheck = append(sigsToCheck, key.SelfSignature, key.SelfSignature.EmbeddedSignature) } for _, sig := range sigsToCheck { for _, notation := range sig.Notations { if notation.IsCritical && !config.KnownNotation(notation.Name) { return errors.SignatureError("unknown critical notation: " + notation.Name) } } } if key.Entity.Revoked(now) || // primary key is revoked (signedBySubKey && key.Revoked(now)) || // subkey is revoked (primaryIdentity != nil && primaryIdentity.Revoked(now)) { // primary identity is revoked for v4 return errors.ErrKeyRevoked } if key.Entity.PrimaryKey.KeyExpired(primarySelfSignature, now) { // primary key is expired return errors.ErrKeyExpired } if signedBySubKey { if key.PublicKey.KeyExpired(key.SelfSignature, now) { // subkey is expired return errors.ErrKeyExpired } } for _, sig := range sigsToCheck { if sig.SigExpired(now) { // any of the relevant signatures are expired return errors.ErrSignatureExpired } } return nil }
checkSignatureDetails returns an error if: - The signature (or one of the binding signatures mentioned below) has a unknown critical notation data subpacket - The primary key of the signing entity is revoked - The primary identity is revoked - The signature is expired - The primary key of the signing entity is expired according to the primary identity binding signature ... or, if the signature was signed by a subkey and: - The signing subkey is revoked - The signing subkey is expired according to the subkey binding signature - The signing subkey binding signature is expired - The signing subkey cross-signature is expired NOTE: The order of these checks is important, as the caller may choose to ignore ErrSignatureExpired or ErrKeyExpired errors, but should never ignore any other errors.
checkSignatureDetails
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go
MIT
func (e *Entity) PrimaryIdentity() *Identity { var primaryIdentity *Identity for _, ident := range e.Identities { if shouldPreferIdentity(primaryIdentity, ident) { primaryIdentity = ident } } return primaryIdentity }
PrimaryIdentity returns an Identity, preferring non-revoked identities, identities marked as primary, or the latest-created identity, in that order.
PrimaryIdentity
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) EncryptionKey(now time.Time) (Key, bool) { // Fail to find any encryption key if the... primarySelfSignature, primaryIdentity := e.PrimarySelfSignature() if primarySelfSignature == nil || // no self-signature found e.PrimaryKey.KeyExpired(primarySelfSignature, now) || // primary key has expired e.Revoked(now) || // primary key has been revoked primarySelfSignature.SigExpired(now) || // user ID or or direct self-signature has expired (primaryIdentity != nil && primaryIdentity.Revoked(now)) { // user ID has been revoked (for v4 keys) return Key{}, false } // Iterate the keys to find the newest, unexpired one candidateSubkey := -1 var maxTime time.Time for i, subkey := range e.Subkeys { if subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications && subkey.PublicKey.PubKeyAlgo.CanEncrypt() && !subkey.PublicKey.KeyExpired(subkey.Sig, now) && !subkey.Sig.SigExpired(now) && !subkey.Revoked(now) && (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { candidateSubkey = i maxTime = subkey.Sig.CreationTime } } if candidateSubkey != -1 { subkey := e.Subkeys[candidateSubkey] return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Revocations}, true } // If we don't have any subkeys for encryption and the primary key // is marked as OK to encrypt with, then we can use it. if primarySelfSignature.FlagsValid && primarySelfSignature.FlagEncryptCommunications && e.PrimaryKey.PubKeyAlgo.CanEncrypt() { return Key{e, e.PrimaryKey, e.PrivateKey, primarySelfSignature, e.Revocations}, true } return Key{}, false }
EncryptionKey returns the best candidate Key for encrypting a message to the given Entity.
EncryptionKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) CertificationKey(now time.Time) (Key, bool) { return e.CertificationKeyById(now, 0) }
CertificationKey return the best candidate Key for certifying a key with this Entity.
CertificationKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) CertificationKeyById(now time.Time, id uint64) (Key, bool) { return e.signingKeyByIdUsage(now, id, packet.KeyFlagCertify) }
CertificationKeyById return the Key for key certification with this Entity and keyID.
CertificationKeyById
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) SigningKey(now time.Time) (Key, bool) { return e.SigningKeyById(now, 0) }
SigningKey return the best candidate Key for signing a message with this Entity.
SigningKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) SigningKeyById(now time.Time, id uint64) (Key, bool) { return e.signingKeyByIdUsage(now, id, packet.KeyFlagSign) }
SigningKeyById return the Key for signing a message with this Entity and keyID.
SigningKeyById
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) Revoked(now time.Time) bool { return revoked(e.Revocations, now) }
Revoked returns whether the entity has any direct key revocation signatures. Note that third-party revocation signatures are not supported. Note also that Identity and Subkey revocation should be checked separately.
Revoked
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) EncryptPrivateKeys(passphrase []byte, config *packet.Config) error { var keysToEncrypt []*packet.PrivateKey // Add entity private key to encrypt. if e.PrivateKey != nil && !e.PrivateKey.Dummy() && !e.PrivateKey.Encrypted { keysToEncrypt = append(keysToEncrypt, e.PrivateKey) } // Add subkeys to encrypt. for _, sub := range e.Subkeys { if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && !sub.PrivateKey.Encrypted { keysToEncrypt = append(keysToEncrypt, sub.PrivateKey) } } return packet.EncryptPrivateKeys(keysToEncrypt, passphrase, config) }
EncryptPrivateKeys encrypts all non-encrypted keys in the entity with the same key derived from the provided passphrase. Public keys and dummy keys are ignored, and don't cause an error to be returned.
EncryptPrivateKeys
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (e *Entity) DecryptPrivateKeys(passphrase []byte) error { var keysToDecrypt []*packet.PrivateKey // Add entity private key to decrypt. if e.PrivateKey != nil && !e.PrivateKey.Dummy() && e.PrivateKey.Encrypted { keysToDecrypt = append(keysToDecrypt, e.PrivateKey) } // Add subkeys to decrypt. for _, sub := range e.Subkeys { if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && sub.PrivateKey.Encrypted { keysToDecrypt = append(keysToDecrypt, sub.PrivateKey) } } return packet.DecryptPrivateKeys(keysToDecrypt, passphrase) }
DecryptPrivateKeys decrypts all encrypted keys in the entity with the given passphrase. Avoids recomputation of similar s2k key derivations. Public keys and dummy keys are ignored, and don't cause an error to be returned.
DecryptPrivateKeys
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (i *Identity) Revoked(now time.Time) bool { return revoked(i.Revocations, now) }
Revoked returns whether the identity has been revoked by a self-signature. Note that third-party revocation signatures are not supported.
Revoked
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (s *Subkey) Revoked(now time.Time) bool { return revoked(s.Revocations, now) }
Revoked returns whether the subkey has been revoked by a self-signature. Note that third-party revocation signatures are not supported.
Revoked
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (key *Key) Revoked(now time.Time) bool { return revoked(key.Revocations, now) }
Revoked returns whether the key or subkey has been revoked by a self-signature. Note that third-party revocation signatures are not supported. Note also that Identity revocation should be checked separately. Normally, it's not necessary to call this function, except on keys returned by KeysById or KeysByIdUsage.
Revoked
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (el EntityList) KeysById(id uint64) (keys []Key) { for _, e := range el { if e.PrimaryKey.KeyId == id { selfSig, _ := e.PrimarySelfSignature() keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, e.Revocations}) } for _, subKey := range e.Subkeys { if subKey.PublicKey.KeyId == id { keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations}) } } } return }
KeysById returns the set of keys that have the given key id.
KeysById
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) { for _, key := range el.KeysById(id) { if requiredUsage != 0 { if key.SelfSignature == nil || !key.SelfSignature.FlagsValid { continue } var usage byte if key.SelfSignature.FlagCertify { usage |= packet.KeyFlagCertify } if key.SelfSignature.FlagSign { usage |= packet.KeyFlagSign } if key.SelfSignature.FlagEncryptCommunications { usage |= packet.KeyFlagEncryptCommunications } if key.SelfSignature.FlagEncryptStorage { usage |= packet.KeyFlagEncryptStorage } if usage&requiredUsage != requiredUsage { continue } } keys = append(keys, key) } return }
KeysByIdAndUsage returns the set of keys with the given id that also meet the key usage given by requiredUsage. The requiredUsage is expressed as the bitwise-OR of packet.KeyFlag* values.
KeysByIdUsage
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func (el EntityList) DecryptionKeys() (keys []Key) { for _, e := range el { for _, subKey := range e.Subkeys { if subKey.PrivateKey != nil && subKey.Sig.FlagsValid && (subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations}) } } } return }
DecryptionKeys returns all private keys that are valid for decryption.
DecryptionKeys
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { block, err := armor.Decode(r) if err == io.EOF { return nil, errors.InvalidArgumentError("no armored data found") } if err != nil { return nil, err } if block.Type != PublicKeyType && block.Type != PrivateKeyType { return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) } return ReadKeyRing(block.Body) }
ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
ReadArmoredKeyRing
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func ReadKeyRing(r io.Reader) (el EntityList, err error) { packets := packet.NewReader(r) var lastUnsupportedError error for { var e *Entity e, err = ReadEntity(packets) if err != nil { // TODO: warn about skipped unsupported/unreadable keys if _, ok := err.(errors.UnsupportedError); ok { lastUnsupportedError = err err = readToNextPublicKey(packets) } else if _, ok := err.(errors.StructuralError); ok { // Skip unreadable, badly-formatted keys lastUnsupportedError = err err = readToNextPublicKey(packets) } if err == io.EOF { err = nil break } if err != nil { el = nil break } } else { el = append(el, e) } } if len(el) == 0 && err == nil { err = lastUnsupportedError } return }
ReadKeyRing reads one or more public/private keys. Unsupported keys are ignored as long as at least a single valid key is found.
ReadKeyRing
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func readToNextPublicKey(packets *packet.Reader) (err error) { var p packet.Packet for { p, err = packets.Next() if err == io.EOF { return } else if err != nil { if _, ok := err.(errors.UnsupportedError); ok { continue } return } if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { packets.Unread(p) return } } }
readToNextPublicKey reads packets until the start of the entity and leaves the first packet of the new entity in the Reader.
readToNextPublicKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func ReadEntity(packets *packet.Reader) (*Entity, error) { e := new(Entity) e.Identities = make(map[string]*Identity) p, err := packets.Next() if err != nil { return nil, err } var ok bool if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { packets.Unread(p) return nil, errors.StructuralError("first packet was not a public/private key") } e.PrimaryKey = &e.PrivateKey.PublicKey } if !e.PrimaryKey.PubKeyAlgo.CanSign() { return nil, errors.StructuralError("primary key cannot be used for signatures") } var revocations []*packet.Signature var directSignatures []*packet.Signature EachPacket: for { p, err := packets.Next() if err == io.EOF { break } else if err != nil { return nil, err } switch pkt := p.(type) { case *packet.UserId: if err := addUserID(e, packets, pkt); err != nil { return nil, err } case *packet.Signature: if pkt.SigType == packet.SigTypeKeyRevocation { revocations = append(revocations, pkt) } else if pkt.SigType == packet.SigTypeDirectSignature { directSignatures = append(directSignatures, pkt) } // Else, ignoring the signature as it does not follow anything // we would know to attach it to. case *packet.PrivateKey: if !pkt.IsSubkey { packets.Unread(p) break EachPacket } err = addSubkey(e, packets, &pkt.PublicKey, pkt) if err != nil { return nil, err } case *packet.PublicKey: if !pkt.IsSubkey { packets.Unread(p) break EachPacket } err = addSubkey(e, packets, pkt, nil) if err != nil { return nil, err } default: // we ignore unknown packets. } }
ReadEntity reads an entity (public key, identities, subkeys etc) from the given Reader.
ReadEntity
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go
MIT
func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return detachSign(w, signer, message, packet.SigTypeBinary, config) }
DetachSign signs message with the private key from signer (which must already have been decrypted) and writes the signature to w. If config is nil, sensible defaults will be used.
DetachSign
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) }
ArmoredDetachSign signs message with the private key from signer (which must already have been decrypted) and writes an armored signature to w. If config is nil, sensible defaults will be used.
ArmoredDetachSign
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return detachSign(w, signer, message, packet.SigTypeText, config) }
DetachSignText signs message (after canonicalising the line endings) with the private key from signer (which must already have been decrypted) and writes the signature to w. If config is nil, sensible defaults will be used.
DetachSignText
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return armoredDetachSign(w, signer, message, packet.SigTypeText, config) }
ArmoredDetachSignText signs message (after canonicalising the line endings) with the private key from signer (which must already have been decrypted) and writes an armored signature to w. If config is nil, sensible defaults will be used.
ArmoredDetachSignText
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { if hints == nil { hints = &FileHints{} } key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) if err != nil { return } var w io.WriteCloser cipherSuite := packet.CipherSuite{ Cipher: config.Cipher(), Mode: config.AEAD().Mode(), } w, err = packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), config.AEAD() != nil, cipherSuite, key, config) if err != nil { return } literalData := w if algo := config.Compression(); algo != packet.CompressionNone { var compConfig *packet.CompressionConfig if config != nil { compConfig = config.CompressionConfig } literalData, err = packet.SerializeCompressed(w, algo, compConfig) if err != nil { return } } var epochSeconds uint32 if !hints.ModTime.IsZero() { epochSeconds = uint32(hints.ModTime.Unix()) } return packet.SerializeLiteral(literalData, hints.IsBinary, hints.FileName, epochSeconds) }
SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
SymmetricallyEncrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { var j int for _, v := range a { for _, v2 := range b { if v == v2 { a[j] = v j++ break } } } return a[:j] }
intersectPreferences mutates and returns a prefix of a that contains only the values in the intersection of a and b. The order of a is preserved.
intersectPreferences
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func intersectCipherSuites(a [][2]uint8, b [][2]uint8) (intersection [][2]uint8) { var j int for _, v := range a { for _, v2 := range b { if v[0] == v2[0] && v[1] == v2[1] { a[j] = v j++ break } } } return a[:j] }
intersectPreferences mutates and returns a prefix of a that contains only the values in the intersection of a and b. The order of a is preserved.
intersectCipherSuites
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func EncryptText(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeText, config) }
EncryptText encrypts a message to a number of recipients and, optionally, signs it. Optional information is contained in 'hints', also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used. The signing is done in text mode.
EncryptText
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeBinary, config) }
Encrypt encrypts a message to a number of recipients and, optionally, signs it. hints contains optional information, that is also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
Encrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func EncryptSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeBinary, config) }
EncryptSplit encrypts a message to a number of recipients and, optionally, signs it. hints contains optional information, that is also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
EncryptSplit
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func EncryptTextSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeText, config) }
EncryptTextSplit encrypts a message to a number of recipients and, optionally, signs it. hints contains optional information, that is also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
EncryptTextSplit
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { var signer *packet.PrivateKey if signed != nil { signKey, ok := signed.SigningKeyById(config.Now(), config.SigningKey()) if !ok { return nil, errors.InvalidArgumentError("no valid signing keys") } signer = signKey.PrivateKey if signer == nil { return nil, errors.InvalidArgumentError("no private key in signing key") } if signer.Encrypted { return nil, errors.InvalidArgumentError("signing key must be decrypted") } } var hash crypto.Hash for _, hashId := range candidateHashes { if h, ok := algorithm.HashIdToHash(hashId); ok && h.Available() { hash = h break } } // If the hash specified by config is a candidate, we'll use that. if configuredHash := config.Hash(); configuredHash.Available() { for _, hashId := range candidateHashes { if h, ok := algorithm.HashIdToHash(hashId); ok && h == configuredHash { hash = h break } } } if hash == 0 { hashId := candidateHashes[0] name, ok := algorithm.HashIdToString(hashId) if !ok { name = "#" + strconv.Itoa(int(hashId)) } return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") } var salt []byte if signer != nil { var opsVersion = 3 if signer.Version == 6 { opsVersion = signer.Version } ops := &packet.OnePassSignature{ Version: opsVersion, SigType: sigType, Hash: hash, PubKeyAlgo: signer.PubKeyAlgo, KeyId: signer.KeyId, IsLast: true, } if opsVersion == 6 { ops.KeyFingerprint = signer.Fingerprint salt, err = packet.SignatureSaltForHash(hash, config.Random()) if err != nil { return nil, err } ops.Salt = salt } if err := ops.Serialize(payload); err != nil { return nil, err } } if hints == nil { hints = &FileHints{} } w := payload if signer != nil { // If we need to write a signature packet after the literal // data then we need to stop literalData from closing // encryptedData. w = noOpCloser{w} } var epochSeconds uint32 if !hints.ModTime.IsZero() { epochSeconds = uint32(hints.ModTime.Unix()) } literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) if err != nil { return nil, err } if signer != nil { h, wrappedHash, err := hashForSignature(hash, sigType, salt) if err != nil { return nil, err } metadata := &packet.LiteralData{ Format: 'u', FileName: hints.FileName, Time: epochSeconds, } if hints.IsBinary { metadata.Format = 'b' } return signatureWriter{payload, literalData, hash, wrappedHash, h, salt, signer, sigType, config, metadata}, nil } return literalData, nil }
writeAndSign writes the data as a payload package and, optionally, signs it. hints contains optional information, that is also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
writeAndSign
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func encrypt(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { if len(to) == 0 { return nil, errors.InvalidArgumentError("no encryption recipient provided") } // These are the possible ciphers that we'll use for the message. candidateCiphers := []uint8{ uint8(packet.CipherAES256), uint8(packet.CipherAES128), } // These are the possible hash functions that we'll use for the signature. candidateHashes := []uint8{ hashToHashId(crypto.SHA256), hashToHashId(crypto.SHA384), hashToHashId(crypto.SHA512), hashToHashId(crypto.SHA3_256), hashToHashId(crypto.SHA3_512), } // Prefer GCM if everyone supports it candidateCipherSuites := [][2]uint8{ {uint8(packet.CipherAES256), uint8(packet.AEADModeGCM)}, {uint8(packet.CipherAES256), uint8(packet.AEADModeEAX)}, {uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)}, {uint8(packet.CipherAES128), uint8(packet.AEADModeGCM)}, {uint8(packet.CipherAES128), uint8(packet.AEADModeEAX)}, {uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}, } candidateCompression := []uint8{ uint8(packet.CompressionNone), uint8(packet.CompressionZIP), uint8(packet.CompressionZLIB), } encryptKeys := make([]Key, len(to)) // AEAD is used only if config enables it and every key supports it aeadSupported := config.AEAD() != nil for i := range to { var ok bool encryptKeys[i], ok = to[i].EncryptionKey(config.Now()) if !ok { return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no valid encryption keys") } primarySelfSignature, _ := to[i].PrimarySelfSignature() if primarySelfSignature == nil { return nil, errors.InvalidArgumentError("entity without a self-signature") } if !primarySelfSignature.SEIPDv2 { aeadSupported = false } candidateCiphers = intersectPreferences(candidateCiphers, primarySelfSignature.PreferredSymmetric) candidateHashes = intersectPreferences(candidateHashes, primarySelfSignature.PreferredHash) candidateCipherSuites = intersectCipherSuites(candidateCipherSuites, primarySelfSignature.PreferredCipherSuites) candidateCompression = intersectPreferences(candidateCompression, primarySelfSignature.PreferredCompression) } // In the event that the intersection of supported algorithms is empty we use the ones // labelled as MUST that every implementation supports. if len(candidateCiphers) == 0 { // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.3 candidateCiphers = []uint8{uint8(packet.CipherAES128)} } if len(candidateHashes) == 0 { // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#hash-algos candidateHashes = []uint8{hashToHashId(crypto.SHA256)} } if len(candidateCipherSuites) == 0 { // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.6 candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}} } cipher := packet.CipherFunction(candidateCiphers[0]) aeadCipherSuite := packet.CipherSuite{ Cipher: packet.CipherFunction(candidateCipherSuites[0][0]), Mode: packet.AEADMode(candidateCipherSuites[0][1]), } // If the cipher specified by config is a candidate, we'll use that. configuredCipher := config.Cipher() for _, c := range candidateCiphers { cipherFunc := packet.CipherFunction(c) if cipherFunc == configuredCipher { cipher = cipherFunc break } } symKey := make([]byte, cipher.KeySize()) if _, err := io.ReadFull(config.Random(), symKey); err != nil { return nil, err } for _, key := range encryptKeys { if err := packet.SerializeEncryptedKeyAEAD(keyWriter, key.PublicKey, cipher, aeadSupported, symKey, config); err != nil { return nil, err } } var payload io.WriteCloser payload, err = packet.SerializeSymmetricallyEncrypted(dataWriter, cipher, aeadSupported, aeadCipherSuite, symKey, config) if err != nil { return } payload, err = handleCompression(payload, candidateCompression, config) if err != nil { return nil, err } return writeAndSign(payload, candidateHashes, signed, hints, sigType, config) }
encrypt encrypts a message to a number of recipients and, optionally, signs it. hints contains optional information, that is also encrypted, that aids the recipients in processing the message. The resulting WriteCloser must be closed after the contents of the file have been written. If config is nil, sensible defaults will be used.
encrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func Sign(output io.Writer, signed *Entity, hints *FileHints, config *packet.Config) (input io.WriteCloser, err error) { if signed == nil { return nil, errors.InvalidArgumentError("no signer provided") } // These are the possible hash functions that we'll use for the signature. candidateHashes := []uint8{ hashToHashId(crypto.SHA256), hashToHashId(crypto.SHA384), hashToHashId(crypto.SHA512), hashToHashId(crypto.SHA3_256), hashToHashId(crypto.SHA3_512), } defaultHashes := candidateHashes[0:1] primarySelfSignature, _ := signed.PrimarySelfSignature() if primarySelfSignature == nil { return nil, errors.StructuralError("signed entity has no self-signature") } preferredHashes := primarySelfSignature.PreferredHash if len(preferredHashes) == 0 { preferredHashes = defaultHashes } candidateHashes = intersectPreferences(candidateHashes, preferredHashes) if len(candidateHashes) == 0 { return nil, errors.StructuralError("cannot sign because signing key shares no common algorithms with candidate hashes") } return writeAndSign(noOpCloser{output}, candidateHashes, signed, hints, packet.SigTypeBinary, config) }
Sign signs a message. The resulting WriteCloser must be closed after the contents of the file have been written. hints contains optional information that aids the recipients in processing the message. If config is nil, sensible defaults will be used.
Sign
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go
MIT
func NewCanonicalTextHash(h hash.Hash) hash.Hash { return &canonicalTextHash{h, 0} }
NewCanonicalTextHash reformats text written to it into the canonical form and then applies the hash h. See RFC 4880, section 5.2.1.
NewCanonicalTextHash
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/canonical_text.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/canonical_text.go
MIT
func HashIdToHash(id byte) (h crypto.Hash, ok bool) { return algorithm.HashIdToHash(id) }
HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP hash id.
HashIdToHash
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
MIT
func HashIdToString(id byte) (name string, ok bool) { return algorithm.HashIdToString(id) }
HashIdToString returns the name of the hash function corresponding to the given OpenPGP hash id.
HashIdToString
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
MIT
func HashToHashId(h crypto.Hash) (id byte, ok bool) { return algorithm.HashToHashId(h) }
HashToHashId returns an OpenPGP hash id which corresponds the given Hash.
HashToHashId
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/hash.go
MIT
func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { creationTime := config.Now() keyLifetimeSecs := config.KeyLifetime() // Generate a primary signing key primaryPrivRaw, err := newSigner(config) if err != nil { return nil, err } primary := packet.NewSignerPrivateKey(creationTime, primaryPrivRaw) if config.V6() { primary.UpgradeToV6() } e := &Entity{ PrimaryKey: &primary.PublicKey, PrivateKey: primary, Identities: make(map[string]*Identity), Subkeys: []Subkey{}, Signatures: []*packet.Signature{}, } if config.V6() { // In v6 keys algorithm preferences should be stored in direct key signatures selfSignature := createSignaturePacket(&primary.PublicKey, packet.SigTypeDirectSignature, config) err = writeKeyProperties(selfSignature, creationTime, keyLifetimeSecs, config) if err != nil { return nil, err } err = selfSignature.SignDirectKeyBinding(&primary.PublicKey, primary, config) if err != nil { return nil, err } e.Signatures = append(e.Signatures, selfSignature) e.SelfSignature = selfSignature } err = e.addUserId(name, comment, email, config, creationTime, keyLifetimeSecs, !config.V6()) if err != nil { return nil, err } // NOTE: No key expiry here, but we will not return this subkey in EncryptionKey() // if the primary/master key has expired. err = e.addEncryptionSubkey(config, creationTime, 0) if err != nil { return nil, err } return e, nil }
NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a single identity composed of the given full name, comment and email, any of which may be empty but must not contain any of "()<>\x00". If config is nil, sensible defaults will be used.
NewEntity
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func (e *Entity) AddSigningSubkey(config *packet.Config) error { creationTime := config.Now() keyLifetimeSecs := config.KeyLifetime() subPrivRaw, err := newSigner(config) if err != nil { return err } sub := packet.NewSignerPrivateKey(creationTime, subPrivRaw) sub.IsSubkey = true if config.V6() { sub.UpgradeToV6() } subkey := Subkey{ PublicKey: &sub.PublicKey, PrivateKey: sub, } subkey.Sig = createSignaturePacket(e.PrimaryKey, packet.SigTypeSubkeyBinding, config) subkey.Sig.CreationTime = creationTime subkey.Sig.KeyLifetimeSecs = &keyLifetimeSecs subkey.Sig.FlagsValid = true subkey.Sig.FlagSign = true subkey.Sig.EmbeddedSignature = createSignaturePacket(subkey.PublicKey, packet.SigTypePrimaryKeyBinding, config) subkey.Sig.EmbeddedSignature.CreationTime = creationTime err = subkey.Sig.EmbeddedSignature.CrossSignKey(subkey.PublicKey, e.PrimaryKey, subkey.PrivateKey, config) if err != nil { return err } err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) if err != nil { return err } e.Subkeys = append(e.Subkeys, subkey) return nil }
AddSigningSubkey adds a signing keypair as a subkey to the Entity. If config is nil, sensible defaults will be used.
AddSigningSubkey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func (e *Entity) AddEncryptionSubkey(config *packet.Config) error { creationTime := config.Now() keyLifetimeSecs := config.KeyLifetime() return e.addEncryptionSubkey(config, creationTime, keyLifetimeSecs) }
AddEncryptionSubkey adds an encryption keypair as a subkey to the Entity. If config is nil, sensible defaults will be used.
AddEncryptionSubkey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func newSigner(config *packet.Config) (signer interface{}, err error) { switch config.PublicKeyAlgorithm() { case packet.PubKeyAlgoRSA: bits := config.RSAModulusBits() if bits < 1024 { return nil, errors.InvalidArgumentError("bits must be >= 1024") } if config != nil && len(config.RSAPrimes) >= 2 { primes := config.RSAPrimes[0:2] config.RSAPrimes = config.RSAPrimes[2:] return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes) } return rsa.GenerateKey(config.Random(), bits) case packet.PubKeyAlgoEdDSA: if config.V6() { // Implementations MUST NOT accept or generate v6 key material // using the deprecated OIDs. return nil, errors.InvalidArgumentError("EdDSALegacy cannot be used for v6 keys") } curve := ecc.FindEdDSAByGenName(string(config.CurveName())) if curve == nil { return nil, errors.InvalidArgumentError("unsupported curve") } priv, err := eddsa.GenerateKey(config.Random(), curve) if err != nil { return nil, err } return priv, nil case packet.PubKeyAlgoECDSA: curve := ecc.FindECDSAByGenName(string(config.CurveName())) if curve == nil { return nil, errors.InvalidArgumentError("unsupported curve") } priv, err := ecdsa.GenerateKey(config.Random(), curve) if err != nil { return nil, err } return priv, nil case packet.PubKeyAlgoEd25519: priv, err := ed25519.GenerateKey(config.Random()) if err != nil { return nil, err } return priv, nil case packet.PubKeyAlgoEd448: priv, err := ed448.GenerateKey(config.Random()) if err != nil { return nil, err } return priv, nil default: return nil, errors.InvalidArgumentError("unsupported public key algorithm") } }
Generates a signing key
newSigner
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func newDecrypter(config *packet.Config) (decrypter interface{}, err error) { switch config.PublicKeyAlgorithm() { case packet.PubKeyAlgoRSA: bits := config.RSAModulusBits() if bits < 1024 { return nil, errors.InvalidArgumentError("bits must be >= 1024") } if config != nil && len(config.RSAPrimes) >= 2 { primes := config.RSAPrimes[0:2] config.RSAPrimes = config.RSAPrimes[2:] return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes) } return rsa.GenerateKey(config.Random(), bits) case packet.PubKeyAlgoEdDSA, packet.PubKeyAlgoECDSA: fallthrough // When passing EdDSA or ECDSA, we generate an ECDH subkey case packet.PubKeyAlgoECDH: if config.V6() && (config.CurveName() == packet.Curve25519 || config.CurveName() == packet.Curve448) { // Implementations MUST NOT accept or generate v6 key material // using the deprecated OIDs. return nil, errors.InvalidArgumentError("ECDH with Curve25519/448 legacy cannot be used for v6 keys") } var kdf = ecdh.KDF{ Hash: algorithm.SHA512, Cipher: algorithm.AES256, } curve := ecc.FindECDHByGenName(string(config.CurveName())) if curve == nil { return nil, errors.InvalidArgumentError("unsupported curve") } return ecdh.GenerateKey(config.Random(), curve, kdf) case packet.PubKeyAlgoEd25519, packet.PubKeyAlgoX25519: // When passing Ed25519, we generate an x25519 subkey return x25519.GenerateKey(config.Random()) case packet.PubKeyAlgoEd448, packet.PubKeyAlgoX448: // When passing Ed448, we generate an x448 subkey return x448.GenerateKey(config.Random()) default: return nil, errors.InvalidArgumentError("unsupported public key algorithm") } }
Generates an encryption/decryption key
newDecrypter
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func generateRSAKeyWithPrimes(random io.Reader, nprimes int, bits int, prepopulatedPrimes []*big.Int) (*rsa.PrivateKey, error) { priv := new(rsa.PrivateKey) priv.E = 65537 if nprimes < 2 { return nil, goerrors.New("generateRSAKeyWithPrimes: nprimes must be >= 2") } if bits < 1024 { return nil, goerrors.New("generateRSAKeyWithPrimes: bits must be >= 1024") } primes := make([]*big.Int, nprimes) NextSetOfPrimes: for { todo := bits // crypto/rand should set the top two bits in each prime. // Thus each prime has the form // p_i = 2^bitlen(p_i) × 0.11... (in base 2). // And the product is: // P = 2^todo × α // where α is the product of nprimes numbers of the form 0.11... // // If α < 1/2 (which can happen for nprimes > 2), we need to // shift todo to compensate for lost bits: the mean value of 0.11... // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 // will give good results. if nprimes >= 7 { todo += (nprimes - 2) / 5 } for i := 0; i < nprimes; i++ { var err error if len(prepopulatedPrimes) == 0 { primes[i], err = rand.Prime(random, todo/(nprimes-i)) if err != nil { return nil, err } } else { primes[i] = prepopulatedPrimes[0] prepopulatedPrimes = prepopulatedPrimes[1:] } todo -= primes[i].BitLen() } // Make sure that primes is pairwise unequal. for i, prime := range primes { for j := 0; j < i; j++ { if prime.Cmp(primes[j]) == 0 { continue NextSetOfPrimes } } } n := new(big.Int).Set(bigOne) totient := new(big.Int).Set(bigOne) pminus1 := new(big.Int) for _, prime := range primes { n.Mul(n, prime) pminus1.Sub(prime, bigOne) totient.Mul(totient, pminus1) } if n.BitLen() != bits { // This should never happen for nprimes == 2 because // crypto/rand should set the top two bits in each prime. // For nprimes > 2 we hope it does not happen often. continue NextSetOfPrimes } priv.D = new(big.Int) e := big.NewInt(int64(priv.E)) ok := priv.D.ModInverse(e, totient) if ok != nil { priv.Primes = primes priv.N = n break } } priv.Precompute() return priv, nil }
generateRSAKeyWithPrimes generates a multi-prime RSA keypair of the given bit size, using the given random source and pre-populated primes.
generateRSAKeyWithPrimes
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go
MIT
func NewPrivateKey(key PublicKey) *PrivateKey { return &PrivateKey{ PublicKey: key, } }
NewPrivateKey creates a new empty private key including the public key.
NewPrivateKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func Validate(pk *PrivateKey) (err error) { var expectedPublicKey, privateKey x25519lib.Key subtle.ConstantTimeCopy(1, privateKey[:], pk.Secret) x25519lib.KeyGen(&expectedPublicKey, &privateKey) if subtle.ConstantTimeCompare(expectedPublicKey[:], pk.PublicKey.Point) == 0 { return errors.KeyInvalidError("x25519: invalid key") } return nil }
Validate validates that the provided public key matches the private key.
Validate
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func GenerateKey(rand io.Reader) (*PrivateKey, error) { var privateKey, publicKey x25519lib.Key privateKeyOut := new(PrivateKey) err := generateKey(rand, &privateKey, &publicKey) if err != nil { return nil, err } privateKeyOut.PublicKey.Point = publicKey[:] privateKeyOut.Secret = privateKey[:] return privateKeyOut, nil }
GenerateKey generates a new x25519 key pair.
GenerateKey
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func Encrypt(rand io.Reader, publicKey *PublicKey, sessionKey []byte) (ephemeralPublicKey *PublicKey, encryptedSessionKey []byte, err error) { var ephemeralPrivate, ephemeralPublic, staticPublic, shared x25519lib.Key // Check that the input static public key has 32 bytes if len(publicKey.Point) != KeySize { err = errors.KeyInvalidError("x25519: the public key has the wrong size") return } copy(staticPublic[:], publicKey.Point) // Generate ephemeral keyPair err = generateKey(rand, &ephemeralPrivate, &ephemeralPublic) if err != nil { return } // Compute shared key ok := x25519lib.Shared(&shared, &ephemeralPrivate, &staticPublic) if !ok { err = errors.KeyInvalidError("x25519: the public key is a low order point") return } // Derive the encryption key from the shared secret encryptionKey := applyHKDF(ephemeralPublic[:], publicKey.Point[:], shared[:]) ephemeralPublicKey = &PublicKey{ Point: ephemeralPublic[:], } // Encrypt the sessionKey with aes key wrapping encryptedSessionKey, err = keywrap.Wrap(encryptionKey, sessionKey) return }
Encrypt encrypts a sessionKey with x25519 according to the OpenPGP crypto refresh specification section 5.1.6. The function assumes that the sessionKey has the correct format and padding according to the specification.
Encrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func Decrypt(privateKey *PrivateKey, ephemeralPublicKey *PublicKey, ciphertext []byte) (encodedSessionKey []byte, err error) { var ephemeralPublic, staticPrivate, shared x25519lib.Key // Check that the input ephemeral public key has 32 bytes if len(ephemeralPublicKey.Point) != KeySize { err = errors.KeyInvalidError("x25519: the public key has the wrong size") return } copy(ephemeralPublic[:], ephemeralPublicKey.Point) subtle.ConstantTimeCopy(1, staticPrivate[:], privateKey.Secret) // Compute shared key ok := x25519lib.Shared(&shared, &staticPrivate, &ephemeralPublic) if !ok { err = errors.KeyInvalidError("x25519: the ephemeral public key is a low order point") return } // Derive the encryption key from the shared secret encryptionKey := applyHKDF(ephemeralPublicKey.Point[:], privateKey.PublicKey.Point[:], shared[:]) // Decrypt the session key with aes key wrapping encodedSessionKey, err = keywrap.Unwrap(encryptionKey, ciphertext) return }
Decrypt decrypts a session key stored in ciphertext with the provided x25519 private key and ephemeral public key.
Decrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func EncodedFieldsLength(encryptedSessionKey []byte, v6 bool) int { lenCipherFunction := 0 if !v6 { lenCipherFunction = 1 } return KeySize + 1 + len(encryptedSessionKey) + lenCipherFunction }
EncodeFieldsLength returns the length of the ciphertext encoding given the encrypted session key.
EncodedFieldsLength
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func EncodeFields(writer io.Writer, ephemeralPublicKey *PublicKey, encryptedSessionKey []byte, cipherFunction byte, v6 bool) (err error) { lenAlgorithm := 0 if !v6 { lenAlgorithm = 1 } if _, err = writer.Write(ephemeralPublicKey.Point); err != nil { return err } if _, err = writer.Write([]byte{byte(len(encryptedSessionKey) + lenAlgorithm)}); err != nil { return err } if !v6 { if _, err = writer.Write([]byte{cipherFunction}); err != nil { return err } } _, err = writer.Write(encryptedSessionKey) return err }
EncodeField encodes x25519 session key encryption fields as ephemeral x25519 public key | follow byte length | cipherFunction (v3 only) | encryptedSessionKey and writes it to writer.
EncodeFields
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func DecodeFields(reader io.Reader, v6 bool) (ephemeralPublicKey *PublicKey, encryptedSessionKey []byte, cipherFunction byte, err error) { var buf [1]byte ephemeralPublicKey = &PublicKey{ Point: make([]byte, KeySize), } // 32 octets representing an ephemeral x25519 public key. if _, err = io.ReadFull(reader, ephemeralPublicKey.Point); err != nil { return nil, nil, 0, err } // A one-octet size of the following fields. if _, err = io.ReadFull(reader, buf[:]); err != nil { return nil, nil, 0, err } followingLen := buf[0] // The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). if !v6 { if _, err = io.ReadFull(reader, buf[:]); err != nil { return nil, nil, 0, err } cipherFunction = buf[0] followingLen -= 1 } // The encrypted session key. encryptedSessionKey = make([]byte, followingLen) if _, err = io.ReadFull(reader, encryptedSessionKey); err != nil { return nil, nil, 0, err } return ephemeralPublicKey, encryptedSessionKey, cipherFunction, nil }
DecodeField decodes a x25519 session key encryption as ephemeral x25519 public key | follow byte length | cipherFunction (v3 only) | encryptedSessionKey.
DecodeFields
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/x25519/x25519.go
MIT
func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) { pLen := (pub.P.BitLen() + 7) / 8 if len(msg) > pLen-11 { err = errors.New("elgamal: message too long") return } // EM = 0x02 || PS || 0x00 || M em := make([]byte, pLen-1) em[0] = 2 ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):] err = nonZeroRandomBytes(ps, random) if err != nil { return } em[len(em)-len(msg)-1] = 0 copy(mm, msg) m := new(big.Int).SetBytes(em) k, err := rand.Int(random, pub.P) if err != nil { return } c1 = new(big.Int).Exp(pub.G, k, pub.P) s := new(big.Int).Exp(pub.Y, k, pub.P) c2 = s.Mul(s, m) c2.Mod(c2, pub.P) return }
Encrypt encrypts the given message to the given public key. The result is a pair of integers. Errors can result from reading random, or because msg is too large to be encrypted to the public key.
Encrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
MIT
func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) { s := new(big.Int).Exp(c1, priv.X, priv.P) if s.ModInverse(s, priv.P) == nil { return nil, errors.New("elgamal: invalid private key") } s.Mul(s, c2) s.Mod(s, priv.P) em := s.Bytes() firstByteIsTwo := subtle.ConstantTimeByteEq(em[0], 2) // The remainder of the plaintext must be a string of non-zero random // octets, followed by a 0, followed by the message. // lookingForIndex: 1 iff we are still looking for the zero. // index: the offset of the first zero byte. var lookingForIndex, index int lookingForIndex = 1 for i := 1; i < len(em); i++ { equals0 := subtle.ConstantTimeByteEq(em[i], 0) index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) } if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { return nil, errors.New("elgamal: decryption error") } return em[index+1:], nil }
Decrypt takes two integers, resulting from an ElGamal encryption, and returns the plaintext of the message. An error can result only if the ciphertext is invalid. Users should keep in mind that this is a padding oracle and thus, if exposed to an adaptive chosen ciphertext attack, can be used to break the cryptosystem. See “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto '98),
Decrypt
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
MIT
func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { _, err = io.ReadFull(rand, s) if err != nil { return } for i := 0; i < len(s); i++ { for s[i] == 0 { _, err = io.ReadFull(rand, s[i:i+1]) if err != nil { return } } } return }
nonZeroRandomBytes fills the given slice with non-zero random octets.
nonZeroRandomBytes
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go
MIT
func Wrap(key, plainText []byte) ([]byte, error) { if len(plainText)%8 != 0 { return nil, ErrWrapPlaintext } c, err := aes.NewCipher(key) if err != nil { return nil, ErrInvalidKey } nblocks := len(plainText) / 8 // 1) Initialize variables. var block [aes.BlockSize]byte // - Set A = IV, an initial value (see 2.2.3) for ii := 0; ii < 8; ii++ { block[ii] = 0xA6 } // - For i = 1 to n // - Set R[i] = P[i] intermediate := make([]byte, len(plainText)) copy(intermediate, plainText) // 2) Calculate intermediate values. for ii := 0; ii < 6; ii++ { for jj := 0; jj < nblocks; jj++ { // - B = AES(K, A | R[i]) copy(block[8:], intermediate[jj*8:jj*8+8]) c.Encrypt(block[:], block[:]) // - A = MSB(64, B) ^ t where t = (n*j)+1 t := uint64(ii*nblocks + jj + 1) val := binary.BigEndian.Uint64(block[:8]) ^ t binary.BigEndian.PutUint64(block[:8], val) // - R[i] = LSB(64, B) copy(intermediate[jj*8:jj*8+8], block[8:]) } } // 3) Output results. // - Set C[0] = A // - For i = 1 to n // - C[i] = R[i] return append(block[:8], intermediate...), nil }
Wrap a key using the RFC 3394 AES Key Wrap Algorithm.
Wrap
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go
MIT
func Unwrap(key, cipherText []byte) ([]byte, error) { if len(cipherText)%8 != 0 { return nil, ErrUnwrapCiphertext } c, err := aes.NewCipher(key) if err != nil { return nil, ErrInvalidKey } nblocks := len(cipherText)/8 - 1 // 1) Initialize variables. var block [aes.BlockSize]byte // - Set A = C[0] copy(block[:8], cipherText[:8]) // - For i = 1 to n // - Set R[i] = C[i] intermediate := make([]byte, len(cipherText)-8) copy(intermediate, cipherText[8:]) // 2) Compute intermediate values. for jj := 5; jj >= 0; jj-- { for ii := nblocks - 1; ii >= 0; ii-- { // - B = AES-1(K, (A ^ t) | R[i]) where t = n*j+1 // - A = MSB(64, B) t := uint64(jj*nblocks + ii + 1) val := binary.BigEndian.Uint64(block[:8]) ^ t binary.BigEndian.PutUint64(block[:8], val) copy(block[8:], intermediate[ii*8:ii*8+8]) c.Decrypt(block[:], block[:]) // - R[i] = LSB(B, 64) copy(intermediate[ii*8:ii*8+8], block[8:]) } } // 3) Output results. // - If A is an appropriate initial value (see 2.2.3), for ii := 0; ii < 8; ii++ { if block[ii] != 0xA6 { return nil, ErrUnwrapFailed } } // - For i = 1 to n // - P[i] = R[i] return intermediate, nil }
Unwrap a key using the RFC 3394 AES Key Wrap Algorithm.
Unwrap
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go
MIT
func (c *curve25519) MarshalBytePoint(point []byte) []byte { return append([]byte{0x40}, point...) }
MarshalBytePoint encodes the public point from native format, adding the prefix. See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6
MarshalBytePoint
go
integrations/terraform-provider-github
vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve25519.go
https://github.com/integrations/terraform-provider-github/blob/master/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve25519.go
MIT