summaryrefslogtreecommitdiffstats
path: root/src/crypto/internal/boring
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 19:19:13 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 19:19:13 +0000
commitccd992355df7192993c666236047820244914598 (patch)
treef00fea65147227b7743083c6148396f74cd66935 /src/crypto/internal/boring
parentInitial commit. (diff)
downloadgolang-1.21-ccd992355df7192993c666236047820244914598.tar.xz
golang-1.21-ccd992355df7192993c666236047820244914598.zip
Adding upstream version 1.21.8.upstream/1.21.8
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/crypto/internal/boring')
-rw-r--r--src/crypto/internal/boring/Dockerfile63
-rw-r--r--src/crypto/internal/boring/LICENSE202
-rw-r--r--src/crypto/internal/boring/README.md39
-rw-r--r--src/crypto/internal/boring/aes.go385
-rw-r--r--src/crypto/internal/boring/bbig/big.go33
-rw-r--r--src/crypto/internal/boring/bcache/cache.go140
-rw-r--r--src/crypto/internal/boring/bcache/cache_test.go122
-rw-r--r--src/crypto/internal/boring/bcache/stub.s6
-rw-r--r--src/crypto/internal/boring/boring.go126
-rw-r--r--src/crypto/internal/boring/boring_test.go34
-rwxr-xr-xsrc/crypto/internal/boring/build-boring.sh44
-rwxr-xr-xsrc/crypto/internal/boring/build-goboring.sh237
-rwxr-xr-xsrc/crypto/internal/boring/build.sh46
-rw-r--r--src/crypto/internal/boring/div_test.c83
-rw-r--r--src/crypto/internal/boring/doc.go19
-rw-r--r--src/crypto/internal/boring/ecdh.go224
-rw-r--r--src/crypto/internal/boring/ecdsa.go172
-rw-r--r--src/crypto/internal/boring/fipstls/stub.s12
-rw-r--r--src/crypto/internal/boring/fipstls/tls.go52
-rw-r--r--src/crypto/internal/boring/goboringcrypto.h255
-rw-r--r--src/crypto/internal/boring/hmac.go153
-rw-r--r--src/crypto/internal/boring/notboring.go122
-rw-r--r--src/crypto/internal/boring/rand.go24
-rw-r--r--src/crypto/internal/boring/rsa.go379
-rw-r--r--src/crypto/internal/boring/sha.go599
-rw-r--r--src/crypto/internal/boring/sig/sig.go17
-rw-r--r--src/crypto/internal/boring/sig/sig_amd64.s54
-rw-r--r--src/crypto/internal/boring/sig/sig_other.s20
-rw-r--r--src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.sysobin0 -> 2555664 bytes
-rw-r--r--src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.sysobin0 -> 1980296 bytes
-rw-r--r--src/crypto/internal/boring/syso/syso.go9
31 files changed, 3671 insertions, 0 deletions
diff --git a/src/crypto/internal/boring/Dockerfile b/src/crypto/internal/boring/Dockerfile
new file mode 100644
index 0000000..58eb028
--- /dev/null
+++ b/src/crypto/internal/boring/Dockerfile
@@ -0,0 +1,63 @@
+# Copyright 2020 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+# Run this using build.sh.
+
+ARG ubuntu=ubuntu
+FROM $ubuntu:focal
+
+RUN mkdir /boring
+WORKDIR /boring
+
+ENV LANG=C
+ENV LANGUAGE=
+
+# Following NIST submission draft dated July 3, 2021.
+# This corresponds to boringssl.googlesource.com/boringssl tag fips-20210429.
+ENV ClangV=12
+RUN apt-get update && \
+ apt-get install --no-install-recommends -y cmake xz-utils wget unzip ca-certificates clang-$ClangV python
+
+# Download, validate, unpack, build, and install Ninja.
+ENV NinjaV=1.10.2
+ENV NinjaH=ce35865411f0490368a8fc383f29071de6690cbadc27704734978221f25e2bed
+RUN \
+ wget https://github.com/ninja-build/ninja/archive/refs/tags/v$NinjaV.tar.gz && \
+ echo "$NinjaH v$NinjaV.tar.gz" >sha && sha256sum -c sha && \
+ tar -xzf v$NinjaV.tar.gz && \
+ rm v$NinjaV.tar.gz && \
+ cd ninja-$NinjaV && \
+ CC=clang-$ClangV CXX=clang++-$ClangV ./configure.py --bootstrap && \
+ mv ninja /usr/local/bin/
+
+# Download, validate, unpack, and install Go.
+ARG GOARCH
+ENV GoV=1.16.5
+ENV GoHamd64=b12c23023b68de22f74c0524f10b753e7b08b1504cb7e417eccebdd3fae49061
+ENV GoHarm64=d5446b46ef6f36fdffa852f73dfbbe78c1ddf010b99fa4964944b9ae8b4d6799
+RUN \
+ eval GoH=\${GoH$GOARCH} && \
+ wget https://golang.org/dl/go$GoV.linux-$GOARCH.tar.gz && \
+ echo "$GoH go$GoV.linux-$GOARCH.tar.gz" >sha && sha256sum -c sha && \
+ tar -C /usr/local -xzf go$GoV.linux-$GOARCH.tar.gz && \
+ rm go$GoV.linux-$GOARCH.tar.gz && \
+ ln -s /usr/local/go/bin/go /usr/local/bin/
+
+# Download, validate, and unpack BoringCrypto.
+ENV BoringV=853ca1ea1168dff08011e5d42d94609cc0ca2e27
+ENV BoringH=a4d069ccef6f3c7bc0c68de82b91414f05cb817494cd1ab483dcf3368883c7c2
+RUN \
+ wget https://commondatastorage.googleapis.com/chromium-boringssl-fips/boringssl-$BoringV.tar.xz && \
+ echo "$BoringH boringssl-$BoringV.tar.xz" >sha && sha256sum -c sha && \
+ tar xJf boringssl-$BoringV.tar.xz
+
+# Build BoringCrypto.
+ADD build-boring.sh /boring/build-boring.sh
+RUN /boring/build-boring.sh
+
+# Build Go BoringCrypto syso.
+# build.sh copies it back out of the Docker image.
+ADD goboringcrypto.h /boring/godriver/goboringcrypto.h
+ADD build-goboring.sh /boring/build-goboring.sh
+RUN /boring/build-goboring.sh
diff --git a/src/crypto/internal/boring/LICENSE b/src/crypto/internal/boring/LICENSE
new file mode 100644
index 0000000..38990bd
--- /dev/null
+++ b/src/crypto/internal/boring/LICENSE
@@ -0,0 +1,202 @@
+The Go source code and supporting files in this directory
+are covered by the usual Go license (see ../../../../LICENSE).
+
+When building with GOEXPERIMENT=boringcrypto, the following applies.
+
+The goboringcrypto_linux_amd64.syso object file is built
+from BoringSSL source code by build/build.sh and is covered
+by the BoringSSL license reproduced below and also at
+https://boringssl.googlesource.com/boringssl/+/fips-20190808/LICENSE.
+
+BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL
+licensing. Files that are completely new have a Google copyright and an ISC
+license. This license is reproduced at the bottom of this file.
+
+Contributors to BoringSSL are required to follow the CLA rules for Chromium:
+https://cla.developers.google.com/clas
+
+Some files from Intel are under yet another license, which is also included
+underneath.
+
+The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the
+OpenSSL License and the original SSLeay license apply to the toolkit. See below
+for the actual license texts. Actually both licenses are BSD-style Open Source
+licenses. In case of any license issues related to OpenSSL please contact
+openssl-core@openssl.org.
+
+The following are Google-internal bug numbers where explicit permission from
+some authors is recorded for use of their work. (This is purely for our own
+record keeping.)
+ 27287199
+ 27287880
+ 27287883
+
+ OpenSSL License
+ ---------------
+
+/* ====================================================================
+ * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * openssl-core@openssl.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+ Original SSLeay License
+ -----------------------
+
+/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+ * All rights reserved.
+ *
+ * This package is an SSL implementation written
+ * by Eric Young (eay@cryptsoft.com).
+ * The implementation was written so as to conform with Netscapes SSL.
+ *
+ * This library is free for commercial and non-commercial use as long as
+ * the following conditions are aheared to. The following conditions
+ * apply to all code found in this distribution, be it the RC4, RSA,
+ * lhash, DES, etc., code; not just the SSL code. The SSL documentation
+ * included with this distribution is covered by the same copyright terms
+ * except that the holder is Tim Hudson (tjh@cryptsoft.com).
+ *
+ * Copyright remains Eric Young's, and as such any Copyright notices in
+ * the code are not to be removed.
+ * If this package is used in a product, Eric Young should be given attribution
+ * as the author of the parts of the library used.
+ * This can be in the form of a textual message at program startup or
+ * in documentation (online or textual) provided with the package.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * "This product includes cryptographic software written by
+ * Eric Young (eay@cryptsoft.com)"
+ * The word 'cryptographic' can be left out if the rouines from the library
+ * being used are not cryptographic related :-).
+ * 4. If you include any Windows specific code (or a derivative thereof) from
+ * the apps directory (application code) you must include an acknowledgement:
+ * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * The licence and distribution terms for any publically available version or
+ * derivative of this code cannot be changed. i.e. this code cannot simply be
+ * copied and put under another distribution licence
+ * [including the GNU Public Licence.]
+ */
+
+
+ISC license used for completely new code in BoringSSL:
+
+/* Copyright (c) 2015, Google Inc.
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
+
+
+Some files from Intel carry the following license:
+
+# Copyright (c) 2012, Intel Corporation
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the
+# distribution.
+#
+# * Neither the name of the Intel Corporation nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+#
+# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""AS IS"" AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/crypto/internal/boring/README.md b/src/crypto/internal/boring/README.md
new file mode 100644
index 0000000..ec02786
--- /dev/null
+++ b/src/crypto/internal/boring/README.md
@@ -0,0 +1,39 @@
+We have been working inside Google on a fork of Go that uses
+BoringCrypto (the core of [BoringSSL](https://boringssl.googlesource.com/boringssl/))
+for various crypto primitives, in furtherance of some work related to FIPS 140.
+We have heard that some external users of Go would be
+interested in this code as well, so we have published this code
+here in the main Go repository behind the setting GOEXPERIMENT=boringcrypto.
+
+Use of GOEXPERIMENT=boringcrypto outside Google is _unsupported_.
+This mode is not part of the [Go 1 compatibility rules](https://go.dev/doc/go1compat),
+and it may change incompatibly or break in other ways at any time.
+
+To be clear, we are not making any statements or representations about
+the suitability of this code in relation to the FIPS 140 standard.
+Interested users will have to evaluate for themselves whether the code
+is useful for their own purposes.
+
+---
+
+This directory holds the core of the BoringCrypto implementation
+as well as the build scripts for the module itself: syso/*.syso.
+
+syso/goboringcrypto_linux_amd64.syso is built with:
+
+ GOARCH=amd64 ./build.sh
+
+syso/goboringcrypto_linux_arm64.syso is built with:
+
+ GOARCH=arm64 ./build.sh
+
+Both run on an x86 Debian Linux system using Docker.
+For the arm64 build to run on an x86 system, you need
+
+ apt-get install qemu-user-static qemu-binfmt-support
+
+to allow the x86 kernel to run arm64 binaries via QEMU.
+
+See build.sh for more details about the build.
+
+
diff --git a/src/crypto/internal/boring/aes.go b/src/crypto/internal/boring/aes.go
new file mode 100644
index 0000000..6fae1d5
--- /dev/null
+++ b/src/crypto/internal/boring/aes.go
@@ -0,0 +1,385 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+/*
+
+#include "goboringcrypto.h"
+
+// These wrappers allocate out_len on the C stack, and check that it matches the expected
+// value, to avoid having to pass a pointer from Go, which would escape to the heap.
+
+int EVP_AEAD_CTX_seal_wrapper(const GO_EVP_AEAD_CTX *ctx, uint8_t *out,
+ size_t exp_out_len,
+ const uint8_t *nonce, size_t nonce_len,
+ const uint8_t *in, size_t in_len,
+ const uint8_t *ad, size_t ad_len) {
+ size_t out_len;
+ int ok = _goboringcrypto_EVP_AEAD_CTX_seal(ctx, out, &out_len, exp_out_len,
+ nonce, nonce_len, in, in_len, ad, ad_len);
+ if (out_len != exp_out_len) {
+ return 0;
+ }
+ return ok;
+};
+
+int EVP_AEAD_CTX_open_wrapper(const GO_EVP_AEAD_CTX *ctx, uint8_t *out,
+ size_t exp_out_len,
+ const uint8_t *nonce, size_t nonce_len,
+ const uint8_t *in, size_t in_len,
+ const uint8_t *ad, size_t ad_len) {
+ size_t out_len;
+ int ok = _goboringcrypto_EVP_AEAD_CTX_open(ctx, out, &out_len, exp_out_len,
+ nonce, nonce_len, in, in_len, ad, ad_len);
+ if (out_len != exp_out_len) {
+ return 0;
+ }
+ return ok;
+};
+
+*/
+import "C"
+import (
+ "bytes"
+ "crypto/cipher"
+ "errors"
+ "runtime"
+ "strconv"
+ "unsafe"
+)
+
+type aesKeySizeError int
+
+func (k aesKeySizeError) Error() string {
+ return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
+}
+
+const aesBlockSize = 16
+
+type aesCipher struct {
+ key []byte
+ enc C.GO_AES_KEY
+ dec C.GO_AES_KEY
+}
+
+type extraModes interface {
+ // Copied out of crypto/aes/modes.go.
+ NewCBCEncrypter(iv []byte) cipher.BlockMode
+ NewCBCDecrypter(iv []byte) cipher.BlockMode
+ NewCTR(iv []byte) cipher.Stream
+ NewGCM(nonceSize, tagSize int) (cipher.AEAD, error)
+}
+
+var _ extraModes = (*aesCipher)(nil)
+
+func NewAESCipher(key []byte) (cipher.Block, error) {
+ c := &aesCipher{key: bytes.Clone(key)}
+ // Note: 0 is success, contradicting the usual BoringCrypto convention.
+ if C._goboringcrypto_AES_set_decrypt_key((*C.uint8_t)(unsafe.Pointer(&c.key[0])), C.uint(8*len(c.key)), &c.dec) != 0 ||
+ C._goboringcrypto_AES_set_encrypt_key((*C.uint8_t)(unsafe.Pointer(&c.key[0])), C.uint(8*len(c.key)), &c.enc) != 0 {
+ return nil, aesKeySizeError(len(key))
+ }
+ return c, nil
+}
+
+func (c *aesCipher) BlockSize() int { return aesBlockSize }
+
+func (c *aesCipher) Encrypt(dst, src []byte) {
+ if inexactOverlap(dst, src) {
+ panic("crypto/cipher: invalid buffer overlap")
+ }
+ if len(src) < aesBlockSize {
+ panic("crypto/aes: input not full block")
+ }
+ if len(dst) < aesBlockSize {
+ panic("crypto/aes: output not full block")
+ }
+ C._goboringcrypto_AES_encrypt(
+ (*C.uint8_t)(unsafe.Pointer(&src[0])),
+ (*C.uint8_t)(unsafe.Pointer(&dst[0])),
+ &c.enc)
+}
+
+func (c *aesCipher) Decrypt(dst, src []byte) {
+ if inexactOverlap(dst, src) {
+ panic("crypto/cipher: invalid buffer overlap")
+ }
+ if len(src) < aesBlockSize {
+ panic("crypto/aes: input not full block")
+ }
+ if len(dst) < aesBlockSize {
+ panic("crypto/aes: output not full block")
+ }
+ C._goboringcrypto_AES_decrypt(
+ (*C.uint8_t)(unsafe.Pointer(&src[0])),
+ (*C.uint8_t)(unsafe.Pointer(&dst[0])),
+ &c.dec)
+}
+
+type aesCBC struct {
+ key *C.GO_AES_KEY
+ mode C.int
+ iv [aesBlockSize]byte
+}
+
+func (x *aesCBC) BlockSize() int { return aesBlockSize }
+
+func (x *aesCBC) CryptBlocks(dst, src []byte) {
+ if inexactOverlap(dst, src) {
+ panic("crypto/cipher: invalid buffer overlap")
+ }
+ if len(src)%aesBlockSize != 0 {
+ panic("crypto/cipher: input not full blocks")
+ }
+ if len(dst) < len(src) {
+ panic("crypto/cipher: output smaller than input")
+ }
+ if len(src) > 0 {
+ C._goboringcrypto_AES_cbc_encrypt(
+ (*C.uint8_t)(unsafe.Pointer(&src[0])),
+ (*C.uint8_t)(unsafe.Pointer(&dst[0])),
+ C.size_t(len(src)), x.key,
+ (*C.uint8_t)(unsafe.Pointer(&x.iv[0])), x.mode)
+ }
+}
+
+func (x *aesCBC) SetIV(iv []byte) {
+ if len(iv) != aesBlockSize {
+ panic("cipher: incorrect length IV")
+ }
+ copy(x.iv[:], iv)
+}
+
+func (c *aesCipher) NewCBCEncrypter(iv []byte) cipher.BlockMode {
+ x := &aesCBC{key: &c.enc, mode: C.GO_AES_ENCRYPT}
+ copy(x.iv[:], iv)
+ return x
+}
+
+func (c *aesCipher) NewCBCDecrypter(iv []byte) cipher.BlockMode {
+ x := &aesCBC{key: &c.dec, mode: C.GO_AES_DECRYPT}
+ copy(x.iv[:], iv)
+ return x
+}
+
+type aesCTR struct {
+ key *C.GO_AES_KEY
+ iv [aesBlockSize]byte
+ num C.uint
+ ecount_buf [16]C.uint8_t
+}
+
+func (x *aesCTR) XORKeyStream(dst, src []byte) {
+ if inexactOverlap(dst, src) {
+ panic("crypto/cipher: invalid buffer overlap")
+ }
+ if len(dst) < len(src) {
+ panic("crypto/cipher: output smaller than input")
+ }
+ if len(src) == 0 {
+ return
+ }
+ C._goboringcrypto_AES_ctr128_encrypt(
+ (*C.uint8_t)(unsafe.Pointer(&src[0])),
+ (*C.uint8_t)(unsafe.Pointer(&dst[0])),
+ C.size_t(len(src)), x.key, (*C.uint8_t)(unsafe.Pointer(&x.iv[0])),
+ &x.ecount_buf[0], &x.num)
+}
+
+func (c *aesCipher) NewCTR(iv []byte) cipher.Stream {
+ x := &aesCTR{key: &c.enc}
+ copy(x.iv[:], iv)
+ return x
+}
+
+type aesGCM struct {
+ ctx C.GO_EVP_AEAD_CTX
+ aead *C.GO_EVP_AEAD
+}
+
+const (
+ gcmBlockSize = 16
+ gcmTagSize = 16
+ gcmStandardNonceSize = 12
+)
+
+type aesNonceSizeError int
+
+func (n aesNonceSizeError) Error() string {
+ return "crypto/aes: invalid GCM nonce size " + strconv.Itoa(int(n))
+}
+
+type noGCM struct {
+ cipher.Block
+}
+
+func (c *aesCipher) NewGCM(nonceSize, tagSize int) (cipher.AEAD, error) {
+ if nonceSize != gcmStandardNonceSize && tagSize != gcmTagSize {
+ return nil, errors.New("crypto/aes: GCM tag and nonce sizes can't be non-standard at the same time")
+ }
+ // Fall back to standard library for GCM with non-standard nonce or tag size.
+ if nonceSize != gcmStandardNonceSize {
+ return cipher.NewGCMWithNonceSize(&noGCM{c}, nonceSize)
+ }
+ if tagSize != gcmTagSize {
+ return cipher.NewGCMWithTagSize(&noGCM{c}, tagSize)
+ }
+ return c.newGCM(false)
+}
+
+func NewGCMTLS(c cipher.Block) (cipher.AEAD, error) {
+ return c.(*aesCipher).newGCM(true)
+}
+
+func (c *aesCipher) newGCM(tls bool) (cipher.AEAD, error) {
+ var aead *C.GO_EVP_AEAD
+ switch len(c.key) * 8 {
+ case 128:
+ if tls {
+ aead = C._goboringcrypto_EVP_aead_aes_128_gcm_tls12()
+ } else {
+ aead = C._goboringcrypto_EVP_aead_aes_128_gcm()
+ }
+ case 256:
+ if tls {
+ aead = C._goboringcrypto_EVP_aead_aes_256_gcm_tls12()
+ } else {
+ aead = C._goboringcrypto_EVP_aead_aes_256_gcm()
+ }
+ default:
+ // Fall back to standard library for GCM with non-standard key size.
+ return cipher.NewGCMWithNonceSize(&noGCM{c}, gcmStandardNonceSize)
+ }
+
+ g := &aesGCM{aead: aead}
+ if C._goboringcrypto_EVP_AEAD_CTX_init(&g.ctx, aead, (*C.uint8_t)(unsafe.Pointer(&c.key[0])), C.size_t(len(c.key)), C.GO_EVP_AEAD_DEFAULT_TAG_LENGTH, nil) == 0 {
+ return nil, fail("EVP_AEAD_CTX_init")
+ }
+ // Note: Because of the finalizer, any time g.ctx is passed to cgo,
+ // that call must be followed by a call to runtime.KeepAlive(g),
+ // to make sure g is not collected (and finalized) before the cgo
+ // call returns.
+ runtime.SetFinalizer(g, (*aesGCM).finalize)
+ if g.NonceSize() != gcmStandardNonceSize {
+ panic("boringcrypto: internal confusion about nonce size")
+ }
+ if g.Overhead() != gcmTagSize {
+ panic("boringcrypto: internal confusion about tag size")
+ }
+
+ return g, nil
+}
+
+func (g *aesGCM) finalize() {
+ C._goboringcrypto_EVP_AEAD_CTX_cleanup(&g.ctx)
+}
+
+func (g *aesGCM) NonceSize() int {
+ return int(C._goboringcrypto_EVP_AEAD_nonce_length(g.aead))
+}
+
+func (g *aesGCM) Overhead() int {
+ return int(C._goboringcrypto_EVP_AEAD_max_overhead(g.aead))
+}
+
+// base returns the address of the underlying array in b,
+// being careful not to panic when b has zero length.
+func base(b []byte) *C.uint8_t {
+ if len(b) == 0 {
+ return nil
+ }
+ return (*C.uint8_t)(unsafe.Pointer(&b[0]))
+}
+
+func (g *aesGCM) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
+ if len(nonce) != gcmStandardNonceSize {
+ panic("cipher: incorrect nonce length given to GCM")
+ }
+ if uint64(len(plaintext)) > ((1<<32)-2)*aesBlockSize || len(plaintext)+gcmTagSize < len(plaintext) {
+ panic("cipher: message too large for GCM")
+ }
+ if len(dst)+len(plaintext)+gcmTagSize < len(dst) {
+ panic("cipher: message too large for buffer")
+ }
+
+ // Make room in dst to append plaintext+overhead.
+ n := len(dst)
+ for cap(dst) < n+len(plaintext)+gcmTagSize {
+ dst = append(dst[:cap(dst)], 0)
+ }
+ dst = dst[:n+len(plaintext)+gcmTagSize]
+
+ // Check delayed until now to make sure len(dst) is accurate.
+ if inexactOverlap(dst[n:], plaintext) {
+ panic("cipher: invalid buffer overlap")
+ }
+
+ outLen := C.size_t(len(plaintext) + gcmTagSize)
+ ok := C.EVP_AEAD_CTX_seal_wrapper(
+ &g.ctx,
+ (*C.uint8_t)(unsafe.Pointer(&dst[n])), outLen,
+ base(nonce), C.size_t(len(nonce)),
+ base(plaintext), C.size_t(len(plaintext)),
+ base(additionalData), C.size_t(len(additionalData)))
+ runtime.KeepAlive(g)
+ if ok == 0 {
+ panic(fail("EVP_AEAD_CTX_seal"))
+ }
+ return dst[:n+int(outLen)]
+}
+
+var errOpen = errors.New("cipher: message authentication failed")
+
+func (g *aesGCM) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
+ if len(nonce) != gcmStandardNonceSize {
+ panic("cipher: incorrect nonce length given to GCM")
+ }
+ if len(ciphertext) < gcmTagSize {
+ return nil, errOpen
+ }
+ if uint64(len(ciphertext)) > ((1<<32)-2)*aesBlockSize+gcmTagSize {
+ return nil, errOpen
+ }
+
+ // Make room in dst to append ciphertext without tag.
+ n := len(dst)
+ for cap(dst) < n+len(ciphertext)-gcmTagSize {
+ dst = append(dst[:cap(dst)], 0)
+ }
+ dst = dst[:n+len(ciphertext)-gcmTagSize]
+
+ // Check delayed until now to make sure len(dst) is accurate.
+ if inexactOverlap(dst[n:], ciphertext) {
+ panic("cipher: invalid buffer overlap")
+ }
+
+ outLen := C.size_t(len(ciphertext) - gcmTagSize)
+ ok := C.EVP_AEAD_CTX_open_wrapper(
+ &g.ctx,
+ base(dst[n:]), outLen,
+ base(nonce), C.size_t(len(nonce)),
+ base(ciphertext), C.size_t(len(ciphertext)),
+ base(additionalData), C.size_t(len(additionalData)))
+ runtime.KeepAlive(g)
+ if ok == 0 {
+ return nil, errOpen
+ }
+ return dst[:n+int(outLen)], nil
+}
+
+func anyOverlap(x, y []byte) bool {
+ return len(x) > 0 && len(y) > 0 &&
+ uintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) &&
+ uintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1]))
+}
+
+func inexactOverlap(x, y []byte) bool {
+ if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] {
+ return false
+ }
+ return anyOverlap(x, y)
+}
diff --git a/src/crypto/internal/boring/bbig/big.go b/src/crypto/internal/boring/bbig/big.go
new file mode 100644
index 0000000..5ce4697
--- /dev/null
+++ b/src/crypto/internal/boring/bbig/big.go
@@ -0,0 +1,33 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package bbig
+
+import (
+ "crypto/internal/boring"
+ "math/big"
+ "unsafe"
+)
+
+func Enc(b *big.Int) boring.BigInt {
+ if b == nil {
+ return nil
+ }
+ x := b.Bits()
+ if len(x) == 0 {
+ return boring.BigInt{}
+ }
+ return unsafe.Slice((*uint)(&x[0]), len(x))
+}
+
+func Dec(b boring.BigInt) *big.Int {
+ if b == nil {
+ return nil
+ }
+ if len(b) == 0 {
+ return new(big.Int)
+ }
+ x := unsafe.Slice((*big.Word)(&b[0]), len(b))
+ return new(big.Int).SetBits(x)
+}
diff --git a/src/crypto/internal/boring/bcache/cache.go b/src/crypto/internal/boring/bcache/cache.go
new file mode 100644
index 0000000..7934d03
--- /dev/null
+++ b/src/crypto/internal/boring/bcache/cache.go
@@ -0,0 +1,140 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package bcache implements a GC-friendly cache (see [Cache]) for BoringCrypto.
+package bcache
+
+import (
+ "sync/atomic"
+ "unsafe"
+)
+
+// A Cache is a GC-friendly concurrent map from unsafe.Pointer to
+// unsafe.Pointer. It is meant to be used for maintaining shadow
+// BoringCrypto state associated with certain allocated structs, in
+// particular public and private RSA and ECDSA keys.
+//
+// The cache is GC-friendly in the sense that the keys do not
+// indefinitely prevent the garbage collector from collecting them.
+// Instead, at the start of each GC, the cache is cleared entirely. That
+// is, the cache is lossy, and the loss happens at the start of each GC.
+// This means that clients need to be able to cope with cache entries
+// disappearing, but it also means that clients don't need to worry about
+// cache entries keeping the keys from being collected.
+type Cache[K, V any] struct {
+ // The runtime atomically stores nil to ptable at the start of each GC.
+ ptable atomic.Pointer[cacheTable[K, V]]
+}
+
+type cacheTable[K, V any] [cacheSize]atomic.Pointer[cacheEntry[K, V]]
+
+// A cacheEntry is a single entry in the linked list for a given hash table entry.
+type cacheEntry[K, V any] struct {
+ k *K // immutable once created
+ v atomic.Pointer[V] // read and written atomically to allow updates
+ next *cacheEntry[K, V] // immutable once linked into table
+}
+
+func registerCache(unsafe.Pointer) // provided by runtime
+
+// Register registers the cache with the runtime,
+// so that c.ptable can be cleared at the start of each GC.
+// Register must be called during package initialization.
+func (c *Cache[K, V]) Register() {
+ registerCache(unsafe.Pointer(&c.ptable))
+}
+
+// cacheSize is the number of entries in the hash table.
+// The hash is the pointer value mod cacheSize, a prime.
+// Collisions are resolved by maintaining a linked list in each hash slot.
+const cacheSize = 1021
+
+// table returns a pointer to the current cache hash table,
+// coping with the possibility of the GC clearing it out from under us.
+func (c *Cache[K, V]) table() *cacheTable[K, V] {
+ for {
+ p := c.ptable.Load()
+ if p == nil {
+ p = new(cacheTable[K, V])
+ if !c.ptable.CompareAndSwap(nil, p) {
+ continue
+ }
+ }
+ return p
+ }
+}
+
+// Clear clears the cache.
+// The runtime does this automatically at each garbage collection;
+// this method is exposed only for testing.
+func (c *Cache[K, V]) Clear() {
+ // The runtime does this at the start of every garbage collection
+ // (itself, not by calling this function).
+ c.ptable.Store(nil)
+}
+
+// Get returns the cached value associated with v,
+// which is either the value v corresponding to the most recent call to Put(k, v)
+// or nil if that cache entry has been dropped.
+func (c *Cache[K, V]) Get(k *K) *V {
+ head := &c.table()[uintptr(unsafe.Pointer(k))%cacheSize]
+ e := head.Load()
+ for ; e != nil; e = e.next {
+ if e.k == k {
+ return e.v.Load()
+ }
+ }
+ return nil
+}
+
+// Put sets the cached value associated with k to v.
+func (c *Cache[K, V]) Put(k *K, v *V) {
+ head := &c.table()[uintptr(unsafe.Pointer(k))%cacheSize]
+
+ // Strategy is to walk the linked list at head,
+ // same as in Get, to look for existing entry.
+ // If we find one, we update v atomically in place.
+ // If not, then we race to replace the start = *head
+ // we observed with a new k, v entry.
+ // If we win that race, we're done.
+ // Otherwise, we try the whole thing again,
+ // with two optimizations:
+ //
+ // 1. We track in noK the start of the section of
+ // the list that we've confirmed has no entry for k.
+ // The next time down the list, we can stop at noK,
+ // because new entries are inserted at the front of the list.
+ // This guarantees we never traverse an entry
+ // multiple times.
+ //
+ // 2. We only allocate the entry to be added once,
+ // saving it in add for the next attempt.
+ var add, noK *cacheEntry[K, V]
+ n := 0
+ for {
+ e := head.Load()
+ start := e
+ for ; e != nil && e != noK; e = e.next {
+ if e.k == k {
+ e.v.Store(v)
+ return
+ }
+ n++
+ }
+ if add == nil {
+ add = &cacheEntry[K, V]{k: k}
+ add.v.Store(v)
+ }
+ add.next = start
+ if n >= 1000 {
+ // If an individual list gets too long, which shouldn't happen,
+ // throw it away to avoid quadratic lookup behavior.
+ add.next = nil
+ }
+ if head.CompareAndSwap(start, add) {
+ return
+ }
+ noK = start
+ }
+}
diff --git a/src/crypto/internal/boring/bcache/cache_test.go b/src/crypto/internal/boring/bcache/cache_test.go
new file mode 100644
index 0000000..19458a1
--- /dev/null
+++ b/src/crypto/internal/boring/bcache/cache_test.go
@@ -0,0 +1,122 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package bcache
+
+import (
+ "fmt"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+var registeredCache Cache[int, int32]
+
+func init() {
+ registeredCache.Register()
+}
+
+var seq atomic.Uint32
+
+func next[T int | int32]() *T {
+ x := new(T)
+ *x = T(seq.Add(1))
+ return x
+}
+
+func str[T int | int32](x *T) string {
+ if x == nil {
+ return "nil"
+ }
+ return fmt.Sprint(*x)
+}
+
+func TestCache(t *testing.T) {
+ // Use unregistered cache for functionality tests,
+ // to keep the runtime from clearing behind our backs.
+ c := new(Cache[int, int32])
+
+ // Create many entries.
+ m := make(map[*int]*int32)
+ for i := 0; i < 10000; i++ {
+ k := next[int]()
+ v := next[int32]()
+ m[k] = v
+ c.Put(k, v)
+ }
+
+ // Overwrite a random 20% of those.
+ n := 0
+ for k := range m {
+ v := next[int32]()
+ m[k] = v
+ c.Put(k, v)
+ if n++; n >= 2000 {
+ break
+ }
+ }
+
+ // Check results.
+ for k, v := range m {
+ if cv := c.Get(k); cv != v {
+ t.Fatalf("c.Get(%v) = %v, want %v", str(k), str(cv), str(v))
+ }
+ }
+
+ c.Clear()
+ for k := range m {
+ if cv := c.Get(k); cv != nil {
+ t.Fatalf("after GC, c.Get(%v) = %v, want nil", str(k), str(cv))
+ }
+ }
+
+ // Check that registered cache is cleared at GC.
+ c = &registeredCache
+ for k, v := range m {
+ c.Put(k, v)
+ }
+ runtime.GC()
+ for k := range m {
+ if cv := c.Get(k); cv != nil {
+ t.Fatalf("after Clear, c.Get(%v) = %v, want nil", str(k), str(cv))
+ }
+ }
+
+ // Check that cache works for concurrent access.
+ // Lists are discarded if they reach 1000 entries,
+ // and there are cacheSize list heads, so we should be
+ // able to do 100 * cacheSize entries with no problem at all.
+ c = new(Cache[int, int32])
+ var barrier, wg sync.WaitGroup
+ const N = 100
+ barrier.Add(N)
+ wg.Add(N)
+ var lost int32
+ for i := 0; i < N; i++ {
+ go func() {
+ defer wg.Done()
+
+ m := make(map[*int]*int32)
+ for j := 0; j < cacheSize; j++ {
+ k, v := next[int](), next[int32]()
+ m[k] = v
+ c.Put(k, v)
+ }
+ barrier.Done()
+ barrier.Wait()
+
+ for k, v := range m {
+ if cv := c.Get(k); cv != v {
+ t.Errorf("c.Get(%v) = %v, want %v", str(k), str(cv), str(v))
+ atomic.AddInt32(&lost, +1)
+ }
+ }
+ }()
+ }
+ wg.Wait()
+ if lost != 0 {
+ t.Errorf("lost %d entries", lost)
+ }
+}
diff --git a/src/crypto/internal/boring/bcache/stub.s b/src/crypto/internal/boring/bcache/stub.s
new file mode 100644
index 0000000..59f2dee
--- /dev/null
+++ b/src/crypto/internal/boring/bcache/stub.s
@@ -0,0 +1,6 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This file is here to silence an error about registerCache not having a body.
+// (The body is provided by package runtime.)
diff --git a/src/crypto/internal/boring/boring.go b/src/crypto/internal/boring/boring.go
new file mode 100644
index 0000000..102380a
--- /dev/null
+++ b/src/crypto/internal/boring/boring.go
@@ -0,0 +1,126 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+/*
+// goboringcrypto_linux_amd64.syso references pthread functions.
+#cgo LDFLAGS: "-pthread"
+
+#include "goboringcrypto.h"
+*/
+import "C"
+import (
+ "crypto/internal/boring/sig"
+ _ "crypto/internal/boring/syso"
+ "math/bits"
+ "unsafe"
+)
+
+const available = true
+
+func init() {
+ C._goboringcrypto_BORINGSSL_bcm_power_on_self_test()
+ if C._goboringcrypto_FIPS_mode() != 1 {
+ panic("boringcrypto: not in FIPS mode")
+ }
+ sig.BoringCrypto()
+}
+
+// Unreachable marks code that should be unreachable
+// when BoringCrypto is in use. It panics.
+func Unreachable() {
+ panic("boringcrypto: invalid code execution")
+}
+
+// provided by runtime to avoid os import.
+func runtime_arg0() string
+
+func hasSuffix(s, t string) bool {
+ return len(s) > len(t) && s[len(s)-len(t):] == t
+}
+
+// UnreachableExceptTests marks code that should be unreachable
+// when BoringCrypto is in use. It panics.
+func UnreachableExceptTests() {
+ name := runtime_arg0()
+ // If BoringCrypto ran on Windows we'd need to allow _test.exe and .test.exe as well.
+ if !hasSuffix(name, "_test") && !hasSuffix(name, ".test") {
+ println("boringcrypto: unexpected code execution in", name)
+ panic("boringcrypto: invalid code execution")
+ }
+}
+
+type fail string
+
+func (e fail) Error() string { return "boringcrypto: " + string(e) + " failed" }
+
+func wbase(b BigInt) *C.uint8_t {
+ if len(b) == 0 {
+ return nil
+ }
+ return (*C.uint8_t)(unsafe.Pointer(&b[0]))
+}
+
+const wordBytes = bits.UintSize / 8
+
+func bigToBN(x BigInt) *C.GO_BIGNUM {
+ return C._goboringcrypto_BN_le2bn(wbase(x), C.size_t(len(x)*wordBytes), nil)
+}
+
+func bytesToBN(x []byte) *C.GO_BIGNUM {
+ return C._goboringcrypto_BN_bin2bn((*C.uint8_t)(&x[0]), C.size_t(len(x)), nil)
+}
+
+func bnToBig(bn *C.GO_BIGNUM) BigInt {
+ x := make(BigInt, (C._goboringcrypto_BN_num_bytes(bn)+wordBytes-1)/wordBytes)
+ if C._goboringcrypto_BN_bn2le_padded(wbase(x), C.size_t(len(x)*wordBytes), bn) == 0 {
+ panic("boringcrypto: bignum conversion failed")
+ }
+ return x
+}
+
+func bigToBn(bnp **C.GO_BIGNUM, b BigInt) bool {
+ if *bnp != nil {
+ C._goboringcrypto_BN_free(*bnp)
+ *bnp = nil
+ }
+ if b == nil {
+ return true
+ }
+ bn := bigToBN(b)
+ if bn == nil {
+ return false
+ }
+ *bnp = bn
+ return true
+}
+
+// noescape hides a pointer from escape analysis. noescape is
+// the identity function but escape analysis doesn't think the
+// output depends on the input. noescape is inlined and currently
+// compiles down to zero instructions.
+// USE CAREFULLY!
+//
+//go:nosplit
+func noescape(p unsafe.Pointer) unsafe.Pointer {
+ x := uintptr(p)
+ return unsafe.Pointer(x ^ 0)
+}
+
+var zero byte
+
+// addr converts p to its base addr, including a noescape along the way.
+// If p is nil, addr returns a non-nil pointer, so that the result can always
+// be dereferenced.
+//
+//go:nosplit
+func addr(p []byte) *byte {
+ if len(p) == 0 {
+ return &zero
+ }
+ return (*byte)(noescape(unsafe.Pointer(&p[0])))
+}
diff --git a/src/crypto/internal/boring/boring_test.go b/src/crypto/internal/boring/boring_test.go
new file mode 100644
index 0000000..83bbbd3
--- /dev/null
+++ b/src/crypto/internal/boring/boring_test.go
@@ -0,0 +1,34 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Most functionality in this package is tested by replacing existing code
+// and inheriting that code's tests.
+
+package boring
+
+import "testing"
+
+// Test that func init does not panic.
+func TestInit(t *testing.T) {}
+
+// Test that Unreachable panics.
+func TestUnreachable(t *testing.T) {
+ defer func() {
+ if Enabled {
+ if err := recover(); err == nil {
+ t.Fatal("expected Unreachable to panic")
+ }
+ } else {
+ if err := recover(); err != nil {
+ t.Fatalf("expected Unreachable to be a no-op")
+ }
+ }
+ }()
+ Unreachable()
+}
+
+// Test that UnreachableExceptTests does not panic (this is a test).
+func TestUnreachableExceptTests(t *testing.T) {
+ UnreachableExceptTests()
+}
diff --git a/src/crypto/internal/boring/build-boring.sh b/src/crypto/internal/boring/build-boring.sh
new file mode 100755
index 0000000..db49852
--- /dev/null
+++ b/src/crypto/internal/boring/build-boring.sh
@@ -0,0 +1,44 @@
+#!/bin/bash
+# Copyright 2020 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+# Do not run directly; run build.sh, which runs this in Docker.
+# This script builds boringssl, which has already been unpacked in /boring/boringssl.
+
+set -e
+id
+date
+cd /boring
+
+# Go requires -fPIC for linux/amd64 cgo builds.
+# Setting -fPIC only affects the compilation of the non-module code in libcrypto.a,
+# because the FIPS module itself is already built with -fPIC.
+echo '#!/bin/bash
+exec clang-'$ClangV' -DGOBORING -fPIC "$@"
+' >/usr/local/bin/clang
+echo '#!/bin/bash
+exec clang++-'$ClangV' -DGOBORING -fPIC "$@"
+' >/usr/local/bin/clang++
+chmod +x /usr/local/bin/clang /usr/local/bin/clang++
+
+# The BoringSSL tests use Go, and cgo would look for gcc.
+export CGO_ENABLED=0
+
+# Modify the support code crypto/mem.c (outside the FIPS module)
+# to not try to use weak symbols, because they don't work with some
+# Go toolchain / clang toolchain combinations.
+perl -p -i -e 's/defined.*ELF.*defined.*GNUC.*/$0 \&\& !defined(GOBORING)/' boringssl/crypto/mem.c
+
+# Verbatim instructions from BoringCrypto build docs.
+printf "set(CMAKE_C_COMPILER \"clang\")\nset(CMAKE_CXX_COMPILER \"clang++\")\n" >${HOME}/toolchain
+cd boringssl
+mkdir build && cd build && cmake -GNinja -DCMAKE_TOOLCHAIN_FILE=${HOME}/toolchain -DFIPS=1 -DCMAKE_BUILD_TYPE=Release ..
+ninja
+./crypto/crypto_test
+cd ../..
+
+if [ "$(./boringssl/build/tool/bssl isfips)" != 1 ]; then
+ echo "NOT FIPS"
+ exit 2
+fi
diff --git a/src/crypto/internal/boring/build-goboring.sh b/src/crypto/internal/boring/build-goboring.sh
new file mode 100755
index 0000000..4938b5e
--- /dev/null
+++ b/src/crypto/internal/boring/build-goboring.sh
@@ -0,0 +1,237 @@
+#!/bin/bash
+# Copyright 2020 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+# Do not run directly; run build.sh, which runs this in Docker.
+# This script builds goboringcrypto's syso, after boringssl has been built.
+
+export TERM=dumb
+
+set -e
+set -x
+id
+date
+export LANG=C
+unset LANGUAGE
+
+case $(uname -m) in
+x86_64) export GOARCH=amd64 ;;
+aarch64) export GOARCH=arm64 ;;
+*)
+ echo 'unknown uname -m:' $(uname -m) >&2
+ exit 2
+esac
+
+export CGO_ENABLED=0
+
+# Build and run test C++ program to make sure goboringcrypto.h matches openssl/*.h.
+# Also collect list of checked symbols in syms.txt
+set -e
+cd /boring/godriver
+cat >goboringcrypto.cc <<'EOF'
+#include <cassert>
+#include "goboringcrypto0.h"
+#include "goboringcrypto1.h"
+#define check_size(t) if(sizeof(t) != sizeof(GO_ ## t)) {printf("sizeof(" #t ")=%d, but sizeof(GO_" #t ")=%d\n", (int)sizeof(t), (int)sizeof(GO_ ## t)); ret=1;}
+#define check_func(f) { auto x = f; x = _goboringcrypto_ ## f ; }
+#define check_value(n, v) if(n != v) {printf(#n "=%d, but goboringcrypto.h defines it as %d\n", (int)n, (int)v); ret=1;}
+int main() {
+int ret = 0;
+#include "goboringcrypto.x"
+return ret;
+}
+EOF
+
+cat >boringx.awk <<'EOF'
+BEGIN {
+ exitcode = 0
+}
+
+# Ignore comments, #includes, blank lines.
+/^\/\// || /^#/ || NF == 0 { next }
+
+# Ignore unchecked declarations.
+/\/\*unchecked/ { next }
+
+# Check enum values.
+!enum && ($1 == "enum" || $2 == "enum") && $NF == "{" {
+ enum = 1
+ next
+}
+enum && $1 == "};" {
+ enum = 0
+ next
+}
+enum && /^}.*;$/ {
+ enum = 0
+ next
+}
+enum && NF == 3 && $2 == "=" {
+ name = $1
+ sub(/^GO_/, "", name)
+ val = $3
+ sub(/,$/, "", val)
+ print "check_value(" name ", " val ")" > "goboringcrypto.x"
+ next
+}
+enum {
+ print FILENAME ":" NR ": unexpected line in enum: " $0 > "/dev/stderr"
+ exitcode = 1
+ next
+}
+
+# Check struct sizes.
+/^typedef struct / && $NF ~ /^GO_/ {
+ name = $NF
+ sub(/^GO_/, "", name)
+ sub(/;$/, "", name)
+ print "check_size(" name ")" > "goboringcrypto.x"
+ next
+}
+
+# Check function prototypes.
+/^(const )?[^ ]+ \**_goboringcrypto_.*\(/ {
+ name = $2
+ if($1 == "const")
+ name = $3
+ sub(/^\**_goboringcrypto_/, "", name)
+ sub(/\(.*/, "", name)
+ print "check_func(" name ")" > "goboringcrypto.x"
+ print name > "syms.txt"
+ next
+}
+
+{
+ print FILENAME ":" NR ": unexpected line: " $0 > "/dev/stderr"
+ exitcode = 1
+}
+
+END {
+ exit exitcode
+}
+EOF
+
+cat >boringh.awk <<'EOF'
+/^\/\/ #include/ {sub(/\/\//, ""); print > "goboringcrypto0.h"; next}
+/typedef struct|enum ([a-z_]+ )?{|^[ \t]/ {print >"goboringcrypto1.h";next}
+{gsub(/GO_/, ""); gsub(/enum go_/, "enum "); gsub(/go_point_conv/, "point_conv"); print >"goboringcrypto1.h"}
+EOF
+
+awk -f boringx.awk goboringcrypto.h # writes goboringcrypto.x
+awk -f boringh.awk goboringcrypto.h # writes goboringcrypto[01].h
+
+ls -l ../boringssl/include
+clang++ -std=c++11 -fPIC -I../boringssl/include -O2 -o a.out goboringcrypto.cc
+./a.out || exit 2
+
+# clang implements u128 % u128 -> u128 by calling __umodti3,
+# which is in libgcc. To make the result self-contained even if linking
+# against a different compiler version, link our own __umodti3 into the syso.
+# This one is specialized so it only expects divisors below 2^64,
+# which is all BoringCrypto uses. (Otherwise it will seg fault.)
+cat >umod-amd64.s <<'EOF'
+# tu_int __umodti3(tu_int x, tu_int y)
+# x is rsi:rdi, y is rcx:rdx, return result is rdx:rax.
+.globl __umodti3
+__umodti3:
+ # specialized to u128 % u64, so verify that
+ test %rcx,%rcx
+ jne 1f
+
+ # save divisor
+ movq %rdx, %r8
+
+ # reduce top 64 bits mod divisor
+ movq %rsi, %rax
+ xorl %edx, %edx
+ divq %r8
+
+ # reduce full 128-bit mod divisor
+ # quotient fits in 64 bits because top 64 bits have been reduced < divisor.
+ # (even though we only care about the remainder, divq also computes
+ # the quotient, and it will trap if the quotient is too large.)
+ movq %rdi, %rax
+ divq %r8
+
+ # expand remainder to 128 for return
+ movq %rdx, %rax
+ xorl %edx, %edx
+ ret
+
+1:
+ # crash - only want 64-bit divisor
+ xorl %ecx, %ecx
+ movl %ecx, 0(%ecx)
+ jmp 1b
+
+.section .note.GNU-stack,"",@progbits
+EOF
+
+cat >umod-arm64.c <<'EOF'
+typedef unsigned int u128 __attribute__((mode(TI)));
+
+static u128 div(u128 x, u128 y, u128 *rp) {
+ int n = 0;
+ while((y>>(128-1)) != 1 && y < x) {
+ y<<=1;
+ n++;
+ }
+ u128 q = 0;
+ for(;; n--, y>>=1, q<<=1) {
+ if(x>=y) {
+ x -= y;
+ q |= 1;
+ }
+ if(n == 0)
+ break;
+ }
+ if(rp)
+ *rp = x;
+ return q;
+}
+
+u128 __umodti3(u128 x, u128 y) {
+ u128 r;
+ div(x, y, &r);
+ return r;
+}
+
+u128 __udivti3(u128 x, u128 y) {
+ return div(x, y, 0);
+}
+EOF
+
+extra=""
+case $GOARCH in
+amd64)
+ cp umod-amd64.s umod.s
+ clang -c -o umod.o umod.s
+ extra=umod.o
+ ;;
+arm64)
+ cp umod-arm64.c umod.c
+ clang -c -o umod.o umod.c
+ extra=umod.o
+ ;;
+esac
+
+# Prepare copy of libcrypto.a with only the checked functions renamed and exported.
+# All other symbols are left alone and hidden.
+echo BORINGSSL_bcm_power_on_self_test >>syms.txt
+awk '{print "_goboringcrypto_" $0 }' syms.txt >globals.txt
+awk '{print $0 " _goboringcrypto_" $0 }' syms.txt >renames.txt
+objcopy --globalize-symbol=BORINGSSL_bcm_power_on_self_test \
+ ../boringssl/build/crypto/libcrypto.a libcrypto.a
+
+# Link together bcm.o and libcrypto.a into a single object.
+ld -r -nostdlib --whole-archive -o goboringcrypto.o libcrypto.a $extra
+
+echo __umodti3 _goboringcrypto___umodti3 >>renames.txt
+echo __udivti3 _goboringcrypto___udivti3 >>renames.txt
+objcopy --remove-section=.llvm_addrsig goboringcrypto.o goboringcrypto1.o # b/179161016
+objcopy --redefine-syms=renames.txt goboringcrypto1.o goboringcrypto2.o
+objcopy --keep-global-symbols=globals.txt --strip-unneeded goboringcrypto2.o goboringcrypto_linux_$GOARCH.syso
+
+# Done!
+ls -l goboringcrypto_linux_$GOARCH.syso
diff --git a/src/crypto/internal/boring/build.sh b/src/crypto/internal/boring/build.sh
new file mode 100755
index 0000000..ec960d7
--- /dev/null
+++ b/src/crypto/internal/boring/build.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+# Copyright 2022 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+# This shell script uses Docker to run build-boring.sh and build-goboring.sh,
+# which build goboringcrypto_linux_$GOARCH.syso according to the Security Policy.
+# Currently, amd64 and arm64 are permitted.
+
+set -e
+set -o pipefail
+
+GOARCH=${GOARCH:-$(go env GOARCH)}
+echo "# Building goboringcrypto_linux_$GOARCH.syso. Set GOARCH to override." >&2
+
+if ! which docker >/dev/null; then
+ echo "# Docker not found. Inside Google, see go/installdocker." >&2
+ exit 1
+fi
+
+platform=""
+buildargs=""
+case "$GOARCH" in
+amd64)
+ ;;
+arm64)
+ if ! docker run --rm -t arm64v8/ubuntu:focal uname -m >/dev/null 2>&1; then
+ echo "# Docker cannot run arm64 binaries. Try:"
+ echo " sudo apt-get install qemu binfmt-support qemu-user-static"
+ echo " docker run --rm --privileged multiarch/qemu-user-static --reset -p yes"
+ echo " docker run --rm -t arm64v8/ubuntu:focal uname -m"
+ exit 1
+ fi
+ platform="--platform linux/arm64/v8"
+ buildargs="--build-arg ubuntu=arm64v8/ubuntu"
+ ;;
+*)
+ echo unknown GOARCH $GOARCH >&2
+ exit 2
+esac
+
+docker build $platform $buildargs --build-arg GOARCH=$GOARCH -t goboring:$GOARCH .
+id=$(docker create $platform goboring:$GOARCH)
+docker cp $id:/boring/godriver/goboringcrypto_linux_$GOARCH.syso ./syso
+docker rm $id
+ls -l ./syso/goboringcrypto_linux_$GOARCH.syso
diff --git a/src/crypto/internal/boring/div_test.c b/src/crypto/internal/boring/div_test.c
new file mode 100644
index 0000000..f909cc9
--- /dev/null
+++ b/src/crypto/internal/boring/div_test.c
@@ -0,0 +1,83 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This file is a self-contained test for a copy of
+// the division algorithm in build-goboring.sh,
+// to verify that is correct. The real algorithm uses u128
+// but this copy uses u32 for easier testing.
+// s/32/128/g should be the only difference between the two.
+//
+// This is the dumbest possible division algorithm,
+// but any crypto code that depends on the speed of
+// division is equally dumb.
+
+//go:build ignore
+
+#include <stdio.h>
+#include <stdint.h>
+
+#define nelem(x) (sizeof(x)/sizeof((x)[0]))
+
+typedef uint32_t u32;
+
+static u32 div(u32 x, u32 y, u32 *rp) {
+ int n = 0;
+ while((y>>(32-1)) != 1 && y < x) {
+ y<<=1;
+ n++;
+ }
+ u32 q = 0;
+ for(;; n--, y>>=1, q<<=1) {
+ if(x>=y) {
+ x -= y;
+ q |= 1;
+ }
+ if(n == 0)
+ break;
+ }
+ if(rp)
+ *rp = x;
+ return q;
+}
+
+u32 tests[] = {
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ 11,
+ 31,
+ 0xFFF,
+ 0x1000,
+ 0x1001,
+ 0xF0F0F0,
+ 0xFFFFFF,
+ 0x1000000,
+ 0xF0F0F0F0,
+ 0xFFFFFFFF,
+};
+
+int
+main(void)
+{
+ for(int i=0; i<nelem(tests); i++)
+ for(int j=0; j<nelem(tests); j++) {
+ u32 n = tests[i];
+ u32 d = tests[j];
+ if(d == 0)
+ continue;
+ u32 r;
+ u32 q = div(n, d, &r);
+ if(q != n/d || r != n%d)
+ printf("div(%x, %x) = %x, %x, want %x, %x\n", n, d, q, r, n/d, n%d);
+ }
+ return 0;
+}
diff --git a/src/crypto/internal/boring/doc.go b/src/crypto/internal/boring/doc.go
new file mode 100644
index 0000000..6060fe5
--- /dev/null
+++ b/src/crypto/internal/boring/doc.go
@@ -0,0 +1,19 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package boring provides access to BoringCrypto implementation functions.
+// Check the constant Enabled to find out whether BoringCrypto is available.
+// If BoringCrypto is not available, the functions in this package all panic.
+package boring
+
+// Enabled reports whether BoringCrypto is available.
+// When enabled is false, all functions in this package panic.
+//
+// BoringCrypto is only available on linux/amd64 systems.
+const Enabled = available
+
+// A BigInt is the raw words from a BigInt.
+// This definition allows us to avoid importing math/big.
+// Conversion between BigInt and *big.Int is in crypto/internal/boring/bbig.
+type BigInt []uint
diff --git a/src/crypto/internal/boring/ecdh.go b/src/crypto/internal/boring/ecdh.go
new file mode 100644
index 0000000..8f46d81
--- /dev/null
+++ b/src/crypto/internal/boring/ecdh.go
@@ -0,0 +1,224 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+// #include "goboringcrypto.h"
+import "C"
+import (
+ "errors"
+ "runtime"
+ "unsafe"
+)
+
+type PublicKeyECDH struct {
+ curve string
+ key *C.GO_EC_POINT
+ group *C.GO_EC_GROUP
+ bytes []byte
+}
+
+func (k *PublicKeyECDH) finalize() {
+ C._goboringcrypto_EC_POINT_free(k.key)
+}
+
+type PrivateKeyECDH struct {
+ curve string
+ key *C.GO_EC_KEY
+}
+
+func (k *PrivateKeyECDH) finalize() {
+ C._goboringcrypto_EC_KEY_free(k.key)
+}
+
+func NewPublicKeyECDH(curve string, bytes []byte) (*PublicKeyECDH, error) {
+ if len(bytes) < 1 {
+ return nil, errors.New("NewPublicKeyECDH: missing key")
+ }
+
+ nid, err := curveNID(curve)
+ if err != nil {
+ return nil, err
+ }
+
+ group := C._goboringcrypto_EC_GROUP_new_by_curve_name(nid)
+ if group == nil {
+ return nil, fail("EC_GROUP_new_by_curve_name")
+ }
+ defer C._goboringcrypto_EC_GROUP_free(group)
+ key := C._goboringcrypto_EC_POINT_new(group)
+ if key == nil {
+ return nil, fail("EC_POINT_new")
+ }
+ ok := C._goboringcrypto_EC_POINT_oct2point(group, key, (*C.uint8_t)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes)), nil) != 0
+ if !ok {
+ C._goboringcrypto_EC_POINT_free(key)
+ return nil, errors.New("point not on curve")
+ }
+
+ k := &PublicKeyECDH{curve, key, group, append([]byte(nil), bytes...)}
+ // Note: Because of the finalizer, any time k.key is passed to cgo,
+ // that call must be followed by a call to runtime.KeepAlive(k),
+ // to make sure k is not collected (and finalized) before the cgo
+ // call returns.
+ runtime.SetFinalizer(k, (*PublicKeyECDH).finalize)
+ return k, nil
+}
+
+func (k *PublicKeyECDH) Bytes() []byte { return k.bytes }
+
+func NewPrivateKeyECDH(curve string, bytes []byte) (*PrivateKeyECDH, error) {
+ nid, err := curveNID(curve)
+ if err != nil {
+ return nil, err
+ }
+ key := C._goboringcrypto_EC_KEY_new_by_curve_name(nid)
+ if key == nil {
+ return nil, fail("EC_KEY_new_by_curve_name")
+ }
+ b := bytesToBN(bytes)
+ ok := b != nil && C._goboringcrypto_EC_KEY_set_private_key(key, b) != 0
+ if b != nil {
+ C._goboringcrypto_BN_free(b)
+ }
+ if !ok {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, fail("EC_KEY_set_private_key")
+ }
+ k := &PrivateKeyECDH{curve, key}
+ // Note: Same as in NewPublicKeyECDH regarding finalizer and KeepAlive.
+ runtime.SetFinalizer(k, (*PrivateKeyECDH).finalize)
+ return k, nil
+}
+
+func (k *PrivateKeyECDH) PublicKey() (*PublicKeyECDH, error) {
+ defer runtime.KeepAlive(k)
+
+ group := C._goboringcrypto_EC_KEY_get0_group(k.key)
+ if group == nil {
+ return nil, fail("EC_KEY_get0_group")
+ }
+ kbig := C._goboringcrypto_EC_KEY_get0_private_key(k.key)
+ if kbig == nil {
+ return nil, fail("EC_KEY_get0_private_key")
+ }
+ pt := C._goboringcrypto_EC_POINT_new(group)
+ if pt == nil {
+ return nil, fail("EC_POINT_new")
+ }
+ if C._goboringcrypto_EC_POINT_mul(group, pt, kbig, nil, nil, nil) == 0 {
+ C._goboringcrypto_EC_POINT_free(pt)
+ return nil, fail("EC_POINT_mul")
+ }
+ bytes, err := pointBytesECDH(k.curve, group, pt)
+ if err != nil {
+ C._goboringcrypto_EC_POINT_free(pt)
+ return nil, err
+ }
+ pub := &PublicKeyECDH{k.curve, pt, group, bytes}
+ // Note: Same as in NewPublicKeyECDH regarding finalizer and KeepAlive.
+ runtime.SetFinalizer(pub, (*PublicKeyECDH).finalize)
+ return pub, nil
+}
+
+func pointBytesECDH(curve string, group *C.GO_EC_GROUP, pt *C.GO_EC_POINT) ([]byte, error) {
+ out := make([]byte, 1+2*curveSize(curve))
+ n := C._goboringcrypto_EC_POINT_point2oct(group, pt, C.GO_POINT_CONVERSION_UNCOMPRESSED, (*C.uint8_t)(unsafe.Pointer(&out[0])), C.size_t(len(out)), nil)
+ if int(n) != len(out) {
+ return nil, fail("EC_POINT_point2oct")
+ }
+ return out, nil
+}
+
+func ECDH(priv *PrivateKeyECDH, pub *PublicKeyECDH) ([]byte, error) {
+ group := C._goboringcrypto_EC_KEY_get0_group(priv.key)
+ if group == nil {
+ return nil, fail("EC_KEY_get0_group")
+ }
+ privBig := C._goboringcrypto_EC_KEY_get0_private_key(priv.key)
+ if privBig == nil {
+ return nil, fail("EC_KEY_get0_private_key")
+ }
+ pt := C._goboringcrypto_EC_POINT_new(group)
+ if pt == nil {
+ return nil, fail("EC_POINT_new")
+ }
+ defer C._goboringcrypto_EC_POINT_free(pt)
+ if C._goboringcrypto_EC_POINT_mul(group, pt, nil, pub.key, privBig, nil) == 0 {
+ return nil, fail("EC_POINT_mul")
+ }
+ out, err := xCoordBytesECDH(priv.curve, group, pt)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func xCoordBytesECDH(curve string, group *C.GO_EC_GROUP, pt *C.GO_EC_POINT) ([]byte, error) {
+ big := C._goboringcrypto_BN_new()
+ defer C._goboringcrypto_BN_free(big)
+ if C._goboringcrypto_EC_POINT_get_affine_coordinates_GFp(group, pt, big, nil, nil) == 0 {
+ return nil, fail("EC_POINT_get_affine_coordinates_GFp")
+ }
+ return bigBytesECDH(curve, big)
+}
+
+func bigBytesECDH(curve string, big *C.GO_BIGNUM) ([]byte, error) {
+ out := make([]byte, curveSize(curve))
+ if C._goboringcrypto_BN_bn2bin_padded((*C.uint8_t)(&out[0]), C.size_t(len(out)), big) == 0 {
+ return nil, fail("BN_bn2bin_padded")
+ }
+ return out, nil
+}
+
+func curveSize(curve string) int {
+ switch curve {
+ default:
+ panic("crypto/internal/boring: unknown curve " + curve)
+ case "P-256":
+ return 256 / 8
+ case "P-384":
+ return 384 / 8
+ case "P-521":
+ return (521 + 7) / 8
+ }
+}
+
+func GenerateKeyECDH(curve string) (*PrivateKeyECDH, []byte, error) {
+ nid, err := curveNID(curve)
+ if err != nil {
+ return nil, nil, err
+ }
+ key := C._goboringcrypto_EC_KEY_new_by_curve_name(nid)
+ if key == nil {
+ return nil, nil, fail("EC_KEY_new_by_curve_name")
+ }
+ if C._goboringcrypto_EC_KEY_generate_key_fips(key) == 0 {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, nil, fail("EC_KEY_generate_key_fips")
+ }
+
+ group := C._goboringcrypto_EC_KEY_get0_group(key)
+ if group == nil {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, nil, fail("EC_KEY_get0_group")
+ }
+ b := C._goboringcrypto_EC_KEY_get0_private_key(key)
+ if b == nil {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, nil, fail("EC_KEY_get0_private_key")
+ }
+ bytes, err := bigBytesECDH(curve, b)
+ if err != nil {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, nil, err
+ }
+
+ k := &PrivateKeyECDH{curve, key}
+ // Note: Same as in NewPublicKeyECDH regarding finalizer and KeepAlive.
+ runtime.SetFinalizer(k, (*PrivateKeyECDH).finalize)
+ return k, bytes, nil
+}
diff --git a/src/crypto/internal/boring/ecdsa.go b/src/crypto/internal/boring/ecdsa.go
new file mode 100644
index 0000000..e15f368
--- /dev/null
+++ b/src/crypto/internal/boring/ecdsa.go
@@ -0,0 +1,172 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+// #include "goboringcrypto.h"
+import "C"
+import (
+ "errors"
+ "runtime"
+)
+
+type ecdsaSignature struct {
+ R, S BigInt
+}
+
+type PrivateKeyECDSA struct {
+ key *C.GO_EC_KEY
+}
+
+func (k *PrivateKeyECDSA) finalize() {
+ C._goboringcrypto_EC_KEY_free(k.key)
+}
+
+type PublicKeyECDSA struct {
+ key *C.GO_EC_KEY
+}
+
+func (k *PublicKeyECDSA) finalize() {
+ C._goboringcrypto_EC_KEY_free(k.key)
+}
+
+var errUnknownCurve = errors.New("boringcrypto: unknown elliptic curve")
+
+func curveNID(curve string) (C.int, error) {
+ switch curve {
+ case "P-224":
+ return C.GO_NID_secp224r1, nil
+ case "P-256":
+ return C.GO_NID_X9_62_prime256v1, nil
+ case "P-384":
+ return C.GO_NID_secp384r1, nil
+ case "P-521":
+ return C.GO_NID_secp521r1, nil
+ }
+ return 0, errUnknownCurve
+}
+
+func NewPublicKeyECDSA(curve string, X, Y BigInt) (*PublicKeyECDSA, error) {
+ key, err := newECKey(curve, X, Y)
+ if err != nil {
+ return nil, err
+ }
+ k := &PublicKeyECDSA{key}
+ // Note: Because of the finalizer, any time k.key is passed to cgo,
+ // that call must be followed by a call to runtime.KeepAlive(k),
+ // to make sure k is not collected (and finalized) before the cgo
+ // call returns.
+ runtime.SetFinalizer(k, (*PublicKeyECDSA).finalize)
+ return k, nil
+}
+
+func newECKey(curve string, X, Y BigInt) (*C.GO_EC_KEY, error) {
+ nid, err := curveNID(curve)
+ if err != nil {
+ return nil, err
+ }
+ key := C._goboringcrypto_EC_KEY_new_by_curve_name(nid)
+ if key == nil {
+ return nil, fail("EC_KEY_new_by_curve_name")
+ }
+ group := C._goboringcrypto_EC_KEY_get0_group(key)
+ pt := C._goboringcrypto_EC_POINT_new(group)
+ if pt == nil {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, fail("EC_POINT_new")
+ }
+ bx := bigToBN(X)
+ by := bigToBN(Y)
+ ok := bx != nil && by != nil && C._goboringcrypto_EC_POINT_set_affine_coordinates_GFp(group, pt, bx, by, nil) != 0 &&
+ C._goboringcrypto_EC_KEY_set_public_key(key, pt) != 0
+ if bx != nil {
+ C._goboringcrypto_BN_free(bx)
+ }
+ if by != nil {
+ C._goboringcrypto_BN_free(by)
+ }
+ C._goboringcrypto_EC_POINT_free(pt)
+ if !ok {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, fail("EC_POINT_set_affine_coordinates_GFp")
+ }
+ return key, nil
+}
+
+func NewPrivateKeyECDSA(curve string, X, Y BigInt, D BigInt) (*PrivateKeyECDSA, error) {
+ key, err := newECKey(curve, X, Y)
+ if err != nil {
+ return nil, err
+ }
+ bd := bigToBN(D)
+ ok := bd != nil && C._goboringcrypto_EC_KEY_set_private_key(key, bd) != 0
+ if bd != nil {
+ C._goboringcrypto_BN_free(bd)
+ }
+ if !ok {
+ C._goboringcrypto_EC_KEY_free(key)
+ return nil, fail("EC_KEY_set_private_key")
+ }
+ k := &PrivateKeyECDSA{key}
+ // Note: Because of the finalizer, any time k.key is passed to cgo,
+ // that call must be followed by a call to runtime.KeepAlive(k),
+ // to make sure k is not collected (and finalized) before the cgo
+ // call returns.
+ runtime.SetFinalizer(k, (*PrivateKeyECDSA).finalize)
+ return k, nil
+}
+
+func SignMarshalECDSA(priv *PrivateKeyECDSA, hash []byte) ([]byte, error) {
+ size := C._goboringcrypto_ECDSA_size(priv.key)
+ sig := make([]byte, size)
+ var sigLen C.uint
+ if C._goboringcrypto_ECDSA_sign(0, base(hash), C.size_t(len(hash)), base(sig), &sigLen, priv.key) == 0 {
+ return nil, fail("ECDSA_sign")
+ }
+ runtime.KeepAlive(priv)
+ return sig[:sigLen], nil
+}
+
+func VerifyECDSA(pub *PublicKeyECDSA, hash []byte, sig []byte) bool {
+ ok := C._goboringcrypto_ECDSA_verify(0, base(hash), C.size_t(len(hash)), base(sig), C.size_t(len(sig)), pub.key) != 0
+ runtime.KeepAlive(pub)
+ return ok
+}
+
+func GenerateKeyECDSA(curve string) (X, Y, D BigInt, err error) {
+ nid, err := curveNID(curve)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ key := C._goboringcrypto_EC_KEY_new_by_curve_name(nid)
+ if key == nil {
+ return nil, nil, nil, fail("EC_KEY_new_by_curve_name")
+ }
+ defer C._goboringcrypto_EC_KEY_free(key)
+ if C._goboringcrypto_EC_KEY_generate_key_fips(key) == 0 {
+ return nil, nil, nil, fail("EC_KEY_generate_key_fips")
+ }
+ group := C._goboringcrypto_EC_KEY_get0_group(key)
+ pt := C._goboringcrypto_EC_KEY_get0_public_key(key)
+ bd := C._goboringcrypto_EC_KEY_get0_private_key(key)
+ if pt == nil || bd == nil {
+ return nil, nil, nil, fail("EC_KEY_get0_private_key")
+ }
+ bx := C._goboringcrypto_BN_new()
+ if bx == nil {
+ return nil, nil, nil, fail("BN_new")
+ }
+ defer C._goboringcrypto_BN_free(bx)
+ by := C._goboringcrypto_BN_new()
+ if by == nil {
+ return nil, nil, nil, fail("BN_new")
+ }
+ defer C._goboringcrypto_BN_free(by)
+ if C._goboringcrypto_EC_POINT_get_affine_coordinates_GFp(group, pt, bx, by, nil) == 0 {
+ return nil, nil, nil, fail("EC_POINT_get_affine_coordinates_GFp")
+ }
+ return bnToBig(bx), bnToBig(by), bnToBig(bd), nil
+}
diff --git a/src/crypto/internal/boring/fipstls/stub.s b/src/crypto/internal/boring/fipstls/stub.s
new file mode 100644
index 0000000..f2e5a50
--- /dev/null
+++ b/src/crypto/internal/boring/fipstls/stub.s
@@ -0,0 +1,12 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto
+
+// runtime_arg0 is declared in tls.go without a body.
+// It's provided by package runtime,
+// but the go command doesn't know that.
+// Having this assembly file keeps the go command
+// from complaining about the missing body
+// (because the implementation might be here).
diff --git a/src/crypto/internal/boring/fipstls/tls.go b/src/crypto/internal/boring/fipstls/tls.go
new file mode 100644
index 0000000..3bf1471
--- /dev/null
+++ b/src/crypto/internal/boring/fipstls/tls.go
@@ -0,0 +1,52 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto
+
+// Package fipstls allows control over whether crypto/tls requires FIPS-approved settings.
+// This package only exists with GOEXPERIMENT=boringcrypto, but the effects are independent
+// of the use of BoringCrypto.
+package fipstls
+
+import "sync/atomic"
+
+var required atomic.Bool
+
+// Force forces crypto/tls to restrict TLS configurations to FIPS-approved settings.
+// By design, this call is impossible to undo (except in tests).
+//
+// Note that this call has an effect even in programs using
+// standard crypto (that is, even when Enabled = false).
+func Force() {
+ required.Store(true)
+}
+
+// Abandon allows non-FIPS-approved settings.
+// If called from a non-test binary, it panics.
+func Abandon() {
+ // Note: Not using boring.UnreachableExceptTests because we want
+ // this test to happen even when boring.Enabled = false.
+ name := runtime_arg0()
+ // Allow _test for Go command, .test for Bazel,
+ // NaClMain for NaCl (where all binaries run as NaClMain),
+ // and empty string for Windows (where runtime_arg0 can't easily find the name).
+ // Since this is an internal package, testing that this isn't used on the
+ // other operating systems should suffice to catch any mistakes.
+ if !hasSuffix(name, "_test") && !hasSuffix(name, ".test") && name != "NaClMain" && name != "" {
+ panic("fipstls: invalid use of Abandon in " + name)
+ }
+ required.Store(false)
+}
+
+// provided by runtime
+func runtime_arg0() string
+
+func hasSuffix(s, t string) bool {
+ return len(s) > len(t) && s[len(s)-len(t):] == t
+}
+
+// Required reports whether FIPS-approved settings are required.
+func Required() bool {
+ return required.Load()
+}
diff --git a/src/crypto/internal/boring/goboringcrypto.h b/src/crypto/internal/boring/goboringcrypto.h
new file mode 100644
index 0000000..2b11049
--- /dev/null
+++ b/src/crypto/internal/boring/goboringcrypto.h
@@ -0,0 +1,255 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This header file describes the BoringCrypto ABI as built for use in Go.
+// The BoringCrypto build for Go (which generates goboringcrypto_*.syso)
+// takes the standard libcrypto.a from BoringCrypto and adds the prefix
+// _goboringcrypto_ to every symbol, to avoid possible conflicts with
+// code wrapping a different BoringCrypto or OpenSSL.
+//
+// To make this header standalone (so that building Go does not require
+// having a full set of BoringCrypto headers), the struct details are not here.
+// Instead, while building the syso, we compile and run a C++ program
+// that checks that the sizes match. The program also checks (during compilation)
+// that all the function prototypes match the BoringCrypto equivalents.
+// The generation of the checking program depends on the declaration
+// forms used below (one line for most, multiline for enums).
+
+#include <stdlib.h> // size_t
+#include <stdint.h> // uint8_t
+
+// This symbol is hidden in BoringCrypto and marked as a constructor,
+// but cmd/link's internal linking mode doesn't handle constructors.
+// Until it does, we've exported the symbol and can call it explicitly.
+// (If using external linking mode, it will therefore be called twice,
+// once explicitly and once as a constructor, but that's OK.)
+/*unchecked*/ void _goboringcrypto_BORINGSSL_bcm_power_on_self_test(void);
+
+// #include <openssl/crypto.h>
+int _goboringcrypto_FIPS_mode(void);
+void* _goboringcrypto_OPENSSL_malloc(size_t);
+
+// #include <openssl/rand.h>
+int _goboringcrypto_RAND_bytes(uint8_t*, size_t);
+
+// #include <openssl/nid.h>
+enum {
+ GO_NID_md5_sha1 = 114,
+
+ GO_NID_secp224r1 = 713,
+ GO_NID_X9_62_prime256v1 = 415,
+ GO_NID_secp384r1 = 715,
+ GO_NID_secp521r1 = 716,
+
+ GO_NID_sha224 = 675,
+ GO_NID_sha256 = 672,
+ GO_NID_sha384 = 673,
+ GO_NID_sha512 = 674,
+};
+
+// #include <openssl/sha.h>
+typedef struct GO_SHA_CTX { char data[96]; } GO_SHA_CTX;
+int _goboringcrypto_SHA1_Init(GO_SHA_CTX*);
+int _goboringcrypto_SHA1_Update(GO_SHA_CTX*, const void*, size_t);
+int _goboringcrypto_SHA1_Final(uint8_t*, GO_SHA_CTX*);
+
+typedef struct GO_SHA256_CTX { char data[48+64]; } GO_SHA256_CTX;
+int _goboringcrypto_SHA224_Init(GO_SHA256_CTX*);
+int _goboringcrypto_SHA224_Update(GO_SHA256_CTX*, const void*, size_t);
+int _goboringcrypto_SHA224_Final(uint8_t*, GO_SHA256_CTX*);
+int _goboringcrypto_SHA256_Init(GO_SHA256_CTX*);
+int _goboringcrypto_SHA256_Update(GO_SHA256_CTX*, const void*, size_t);
+int _goboringcrypto_SHA256_Final(uint8_t*, GO_SHA256_CTX*);
+
+typedef struct GO_SHA512_CTX { char data[88+128]; } GO_SHA512_CTX;
+int _goboringcrypto_SHA384_Init(GO_SHA512_CTX*);
+int _goboringcrypto_SHA384_Update(GO_SHA512_CTX*, const void*, size_t);
+int _goboringcrypto_SHA384_Final(uint8_t*, GO_SHA512_CTX*);
+int _goboringcrypto_SHA512_Init(GO_SHA512_CTX*);
+int _goboringcrypto_SHA512_Update(GO_SHA512_CTX*, const void*, size_t);
+int _goboringcrypto_SHA512_Final(uint8_t*, GO_SHA512_CTX*);
+
+// #include <openssl/digest.h>
+/*unchecked (opaque)*/ typedef struct GO_EVP_MD { char data[1]; } GO_EVP_MD;
+const GO_EVP_MD* _goboringcrypto_EVP_md4(void);
+const GO_EVP_MD* _goboringcrypto_EVP_md5(void);
+const GO_EVP_MD* _goboringcrypto_EVP_md5_sha1(void);
+const GO_EVP_MD* _goboringcrypto_EVP_sha1(void);
+const GO_EVP_MD* _goboringcrypto_EVP_sha224(void);
+const GO_EVP_MD* _goboringcrypto_EVP_sha256(void);
+const GO_EVP_MD* _goboringcrypto_EVP_sha384(void);
+const GO_EVP_MD* _goboringcrypto_EVP_sha512(void);
+int _goboringcrypto_EVP_MD_type(const GO_EVP_MD*);
+size_t _goboringcrypto_EVP_MD_size(const GO_EVP_MD*);
+
+// #include <openssl/hmac.h>
+typedef struct GO_HMAC_CTX { char data[104]; } GO_HMAC_CTX;
+void _goboringcrypto_HMAC_CTX_init(GO_HMAC_CTX*);
+void _goboringcrypto_HMAC_CTX_cleanup(GO_HMAC_CTX*);
+int _goboringcrypto_HMAC_Init(GO_HMAC_CTX*, const void*, int, const GO_EVP_MD*);
+int _goboringcrypto_HMAC_Update(GO_HMAC_CTX*, const uint8_t*, size_t);
+int _goboringcrypto_HMAC_Final(GO_HMAC_CTX*, uint8_t*, unsigned int*);
+size_t _goboringcrypto_HMAC_size(const GO_HMAC_CTX*);
+int _goboringcrypto_HMAC_CTX_copy_ex(GO_HMAC_CTX *dest, const GO_HMAC_CTX *src);
+
+// #include <openssl/aes.h>
+typedef struct GO_AES_KEY { char data[244]; } GO_AES_KEY;
+int _goboringcrypto_AES_set_encrypt_key(const uint8_t*, unsigned int, GO_AES_KEY*);
+int _goboringcrypto_AES_set_decrypt_key(const uint8_t*, unsigned int, GO_AES_KEY*);
+void _goboringcrypto_AES_encrypt(const uint8_t*, uint8_t*, const GO_AES_KEY*);
+void _goboringcrypto_AES_decrypt(const uint8_t*, uint8_t*, const GO_AES_KEY*);
+void _goboringcrypto_AES_ctr128_encrypt(const uint8_t*, uint8_t*, size_t, const GO_AES_KEY*, uint8_t*, uint8_t*, unsigned int*);
+enum {
+ GO_AES_ENCRYPT = 1,
+ GO_AES_DECRYPT = 0
+};
+void _goboringcrypto_AES_cbc_encrypt(const uint8_t*, uint8_t*, size_t, const GO_AES_KEY*, uint8_t*, const int);
+
+// #include <openssl/aead.h>
+/*unchecked (opaque)*/ typedef struct GO_EVP_AEAD { char data[1]; } GO_EVP_AEAD;
+/*unchecked (opaque)*/ typedef struct GO_ENGINE { char data[1]; } GO_ENGINE;
+const GO_EVP_AEAD* _goboringcrypto_EVP_aead_aes_128_gcm(void);
+const GO_EVP_AEAD* _goboringcrypto_EVP_aead_aes_256_gcm(void);
+enum {
+ GO_EVP_AEAD_DEFAULT_TAG_LENGTH = 0
+};
+size_t _goboringcrypto_EVP_AEAD_key_length(const GO_EVP_AEAD*);
+size_t _goboringcrypto_EVP_AEAD_nonce_length(const GO_EVP_AEAD*);
+size_t _goboringcrypto_EVP_AEAD_max_overhead(const GO_EVP_AEAD*);
+size_t _goboringcrypto_EVP_AEAD_max_tag_len(const GO_EVP_AEAD*);
+typedef struct GO_EVP_AEAD_CTX { char data[600]; } GO_EVP_AEAD_CTX;
+void _goboringcrypto_EVP_AEAD_CTX_zero(GO_EVP_AEAD_CTX*);
+int _goboringcrypto_EVP_AEAD_CTX_init(GO_EVP_AEAD_CTX*, const GO_EVP_AEAD*, const uint8_t*, size_t, size_t, GO_ENGINE*);
+void _goboringcrypto_EVP_AEAD_CTX_cleanup(GO_EVP_AEAD_CTX*);
+int _goboringcrypto_EVP_AEAD_CTX_seal(const GO_EVP_AEAD_CTX*, uint8_t*, size_t*, size_t, const uint8_t*, size_t, const uint8_t*, size_t, const uint8_t*, size_t);
+int _goboringcrypto_EVP_AEAD_CTX_open(const GO_EVP_AEAD_CTX*, uint8_t*, size_t*, size_t, const uint8_t*, size_t, const uint8_t*, size_t, const uint8_t*, size_t);
+const GO_EVP_AEAD* _goboringcrypto_EVP_aead_aes_128_gcm_tls12(void);
+const GO_EVP_AEAD* _goboringcrypto_EVP_aead_aes_256_gcm_tls12(void);
+enum go_evp_aead_direction_t {
+ go_evp_aead_open = 0,
+ go_evp_aead_seal = 1
+};
+int _goboringcrypto_EVP_AEAD_CTX_init_with_direction(GO_EVP_AEAD_CTX*, const GO_EVP_AEAD*, const uint8_t*, size_t, size_t, enum go_evp_aead_direction_t);
+
+// #include <openssl/bn.h>
+/*unchecked (opaque)*/ typedef struct GO_BN_CTX { char data[1]; } GO_BN_CTX;
+typedef struct GO_BIGNUM { char data[24]; } GO_BIGNUM;
+GO_BIGNUM* _goboringcrypto_BN_new(void);
+void _goboringcrypto_BN_free(GO_BIGNUM*);
+unsigned _goboringcrypto_BN_num_bits(const GO_BIGNUM*);
+unsigned _goboringcrypto_BN_num_bytes(const GO_BIGNUM*);
+int _goboringcrypto_BN_is_negative(const GO_BIGNUM*);
+GO_BIGNUM* _goboringcrypto_BN_bin2bn(const uint8_t*, size_t, GO_BIGNUM*);
+GO_BIGNUM* _goboringcrypto_BN_le2bn(const uint8_t*, size_t, GO_BIGNUM*);
+size_t _goboringcrypto_BN_bn2bin(const GO_BIGNUM*, uint8_t*);
+int _goboringcrypto_BN_bn2le_padded(uint8_t*, size_t, const GO_BIGNUM*);
+int _goboringcrypto_BN_bn2bin_padded(uint8_t*, size_t, const GO_BIGNUM*);
+
+// #include <openssl/ec.h>
+/*unchecked (opaque)*/ typedef struct GO_EC_GROUP { char data[1]; } GO_EC_GROUP;
+GO_EC_GROUP* _goboringcrypto_EC_GROUP_new_by_curve_name(int);
+void _goboringcrypto_EC_GROUP_free(GO_EC_GROUP*);
+
+/*unchecked (opaque)*/ typedef struct GO_EC_POINT { char data[1]; } GO_EC_POINT;
+GO_EC_POINT* _goboringcrypto_EC_POINT_new(const GO_EC_GROUP*);
+int _goboringcrypto_EC_POINT_mul(const GO_EC_GROUP*, GO_EC_POINT*, const GO_BIGNUM*, const GO_EC_POINT*, const GO_BIGNUM*, GO_BN_CTX*);
+void _goboringcrypto_EC_POINT_free(GO_EC_POINT*);
+int _goboringcrypto_EC_POINT_get_affine_coordinates_GFp(const GO_EC_GROUP*, const GO_EC_POINT*, GO_BIGNUM*, GO_BIGNUM*, GO_BN_CTX*);
+int _goboringcrypto_EC_POINT_set_affine_coordinates_GFp(const GO_EC_GROUP*, GO_EC_POINT*, const GO_BIGNUM*, const GO_BIGNUM*, GO_BN_CTX*);
+int _goboringcrypto_EC_POINT_oct2point(const GO_EC_GROUP*, GO_EC_POINT*, const uint8_t*, size_t, GO_BN_CTX*);
+GO_EC_POINT* _goboringcrypto_EC_POINT_dup(const GO_EC_POINT*, const GO_EC_GROUP*);
+int _goboringcrypto_EC_POINT_is_on_curve(const GO_EC_GROUP*, const GO_EC_POINT*, GO_BN_CTX*);
+#ifndef OPENSSL_HEADER_EC_H
+typedef enum {
+ GO_POINT_CONVERSION_COMPRESSED = 2,
+ GO_POINT_CONVERSION_UNCOMPRESSED = 4,
+ GO_POINT_CONVERSION_HYBRID = 6,
+} go_point_conversion_form_t;
+#endif
+size_t _goboringcrypto_EC_POINT_point2oct(const GO_EC_GROUP*, const GO_EC_POINT*, go_point_conversion_form_t, uint8_t*, size_t, GO_BN_CTX*);
+
+// #include <openssl/ec_key.h>
+/*unchecked (opaque)*/ typedef struct GO_EC_KEY { char data[1]; } GO_EC_KEY;
+GO_EC_KEY* _goboringcrypto_EC_KEY_new(void);
+GO_EC_KEY* _goboringcrypto_EC_KEY_new_by_curve_name(int);
+void _goboringcrypto_EC_KEY_free(GO_EC_KEY*);
+const GO_EC_GROUP* _goboringcrypto_EC_KEY_get0_group(const GO_EC_KEY*);
+int _goboringcrypto_EC_KEY_generate_key_fips(GO_EC_KEY*);
+int _goboringcrypto_EC_KEY_set_private_key(GO_EC_KEY*, const GO_BIGNUM*);
+int _goboringcrypto_EC_KEY_set_public_key(GO_EC_KEY*, const GO_EC_POINT*);
+int _goboringcrypto_EC_KEY_is_opaque(const GO_EC_KEY*);
+const GO_BIGNUM* _goboringcrypto_EC_KEY_get0_private_key(const GO_EC_KEY*);
+const GO_EC_POINT* _goboringcrypto_EC_KEY_get0_public_key(const GO_EC_KEY*);
+// TODO: EC_KEY_check_fips?
+
+// #include <openssl/ecdh.h>
+int _goboringcrypto_ECDH_compute_key_fips(uint8_t*, size_t, const GO_EC_POINT*, const GO_EC_KEY*);
+
+// #include <openssl/ecdsa.h>
+typedef struct GO_ECDSA_SIG { char data[16]; } GO_ECDSA_SIG;
+GO_ECDSA_SIG* _goboringcrypto_ECDSA_SIG_new(void);
+void _goboringcrypto_ECDSA_SIG_free(GO_ECDSA_SIG*);
+GO_ECDSA_SIG* _goboringcrypto_ECDSA_do_sign(const uint8_t*, size_t, const GO_EC_KEY*);
+int _goboringcrypto_ECDSA_do_verify(const uint8_t*, size_t, const GO_ECDSA_SIG*, const GO_EC_KEY*);
+int _goboringcrypto_ECDSA_sign(int, const uint8_t*, size_t, uint8_t*, unsigned int*, const GO_EC_KEY*);
+size_t _goboringcrypto_ECDSA_size(const GO_EC_KEY*);
+int _goboringcrypto_ECDSA_verify(int, const uint8_t*, size_t, const uint8_t*, size_t, const GO_EC_KEY*);
+
+// #include <openssl/rsa.h>
+
+// Note: order of struct fields here is unchecked.
+typedef struct GO_RSA { void *meth; GO_BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; char data[168]; } GO_RSA;
+/*unchecked (opaque)*/ typedef struct GO_BN_GENCB { char data[1]; } GO_BN_GENCB;
+GO_RSA* _goboringcrypto_RSA_new(void);
+void _goboringcrypto_RSA_free(GO_RSA*);
+void _goboringcrypto_RSA_get0_key(const GO_RSA*, const GO_BIGNUM **n, const GO_BIGNUM **e, const GO_BIGNUM **d);
+void _goboringcrypto_RSA_get0_factors(const GO_RSA*, const GO_BIGNUM **p, const GO_BIGNUM **q);
+void _goboringcrypto_RSA_get0_crt_params(const GO_RSA*, const GO_BIGNUM **dmp1, const GO_BIGNUM **dmp2, const GO_BIGNUM **iqmp);
+int _goboringcrypto_RSA_generate_key_ex(GO_RSA*, int, const GO_BIGNUM*, GO_BN_GENCB*);
+int _goboringcrypto_RSA_generate_key_fips(GO_RSA*, int, GO_BN_GENCB*);
+enum {
+ GO_RSA_PKCS1_PADDING = 1,
+ GO_RSA_NO_PADDING = 3,
+ GO_RSA_PKCS1_OAEP_PADDING = 4,
+ GO_RSA_PKCS1_PSS_PADDING = 6,
+};
+int _goboringcrypto_RSA_encrypt(GO_RSA*, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding);
+int _goboringcrypto_RSA_decrypt(GO_RSA*, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding);
+int _goboringcrypto_RSA_sign(int hash_nid, const uint8_t* in, unsigned int in_len, uint8_t *out, unsigned int *out_len, GO_RSA*);
+int _goboringcrypto_RSA_sign_pss_mgf1(GO_RSA*, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, const GO_EVP_MD *md, const GO_EVP_MD *mgf1_md, int salt_len);
+int _goboringcrypto_RSA_sign_raw(GO_RSA*, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding);
+int _goboringcrypto_RSA_verify(int hash_nid, const uint8_t *msg, size_t msg_len, const uint8_t *sig, size_t sig_len, GO_RSA*);
+int _goboringcrypto_RSA_verify_pss_mgf1(GO_RSA*, const uint8_t *msg, size_t msg_len, const GO_EVP_MD *md, const GO_EVP_MD *mgf1_md, int salt_len, const uint8_t *sig, size_t sig_len);
+int _goboringcrypto_RSA_verify_raw(GO_RSA*, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding);
+unsigned _goboringcrypto_RSA_size(const GO_RSA*);
+int _goboringcrypto_RSA_is_opaque(const GO_RSA*);
+int _goboringcrypto_RSA_check_key(const GO_RSA*);
+int _goboringcrypto_RSA_check_fips(GO_RSA*);
+GO_RSA* _goboringcrypto_RSA_public_key_from_bytes(const uint8_t*, size_t);
+GO_RSA* _goboringcrypto_RSA_private_key_from_bytes(const uint8_t*, size_t);
+int _goboringcrypto_RSA_public_key_to_bytes(uint8_t**, size_t*, const GO_RSA*);
+int _goboringcrypto_RSA_private_key_to_bytes(uint8_t**, size_t*, const GO_RSA*);
+
+// #include <openssl/evp.h>
+/*unchecked (opaque)*/ typedef struct GO_EVP_PKEY { char data[1]; } GO_EVP_PKEY;
+GO_EVP_PKEY* _goboringcrypto_EVP_PKEY_new(void);
+void _goboringcrypto_EVP_PKEY_free(GO_EVP_PKEY*);
+int _goboringcrypto_EVP_PKEY_set1_RSA(GO_EVP_PKEY*, GO_RSA*);
+
+/*unchecked (opaque)*/ typedef struct GO_EVP_PKEY_CTX { char data[1]; } GO_EVP_PKEY_CTX;
+
+GO_EVP_PKEY_CTX* _goboringcrypto_EVP_PKEY_CTX_new(GO_EVP_PKEY*, GO_ENGINE*);
+void _goboringcrypto_EVP_PKEY_CTX_free(GO_EVP_PKEY_CTX*);
+int _goboringcrypto_EVP_PKEY_CTX_set0_rsa_oaep_label(GO_EVP_PKEY_CTX*, uint8_t*, size_t);
+int _goboringcrypto_EVP_PKEY_CTX_set_rsa_oaep_md(GO_EVP_PKEY_CTX*, const GO_EVP_MD*);
+int _goboringcrypto_EVP_PKEY_CTX_set_rsa_padding(GO_EVP_PKEY_CTX*, int padding);
+int _goboringcrypto_EVP_PKEY_decrypt(GO_EVP_PKEY_CTX*, uint8_t*, size_t*, const uint8_t*, size_t);
+int _goboringcrypto_EVP_PKEY_encrypt(GO_EVP_PKEY_CTX*, uint8_t*, size_t*, const uint8_t*, size_t);
+int _goboringcrypto_EVP_PKEY_decrypt_init(GO_EVP_PKEY_CTX*);
+int _goboringcrypto_EVP_PKEY_encrypt_init(GO_EVP_PKEY_CTX*);
+int _goboringcrypto_EVP_PKEY_CTX_set_rsa_mgf1_md(GO_EVP_PKEY_CTX*, const GO_EVP_MD*);
+int _goboringcrypto_EVP_PKEY_CTX_set_rsa_pss_saltlen(GO_EVP_PKEY_CTX*, int);
+int _goboringcrypto_EVP_PKEY_sign_init(GO_EVP_PKEY_CTX*);
+int _goboringcrypto_EVP_PKEY_verify_init(GO_EVP_PKEY_CTX*);
+int _goboringcrypto_EVP_PKEY_sign(GO_EVP_PKEY_CTX*, uint8_t*, size_t*, const uint8_t*, size_t);
diff --git a/src/crypto/internal/boring/hmac.go b/src/crypto/internal/boring/hmac.go
new file mode 100644
index 0000000..6241a65
--- /dev/null
+++ b/src/crypto/internal/boring/hmac.go
@@ -0,0 +1,153 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+// #include "goboringcrypto.h"
+import "C"
+import (
+ "bytes"
+ "crypto"
+ "hash"
+ "runtime"
+ "unsafe"
+)
+
+// hashToMD converts a hash.Hash implementation from this package
+// to a BoringCrypto *C.GO_EVP_MD.
+func hashToMD(h hash.Hash) *C.GO_EVP_MD {
+ switch h.(type) {
+ case *sha1Hash:
+ return C._goboringcrypto_EVP_sha1()
+ case *sha224Hash:
+ return C._goboringcrypto_EVP_sha224()
+ case *sha256Hash:
+ return C._goboringcrypto_EVP_sha256()
+ case *sha384Hash:
+ return C._goboringcrypto_EVP_sha384()
+ case *sha512Hash:
+ return C._goboringcrypto_EVP_sha512()
+ }
+ return nil
+}
+
+// cryptoHashToMD converts a crypto.Hash
+// to a BoringCrypto *C.GO_EVP_MD.
+func cryptoHashToMD(ch crypto.Hash) *C.GO_EVP_MD {
+ switch ch {
+ case crypto.MD5:
+ return C._goboringcrypto_EVP_md5()
+ case crypto.MD5SHA1:
+ return C._goboringcrypto_EVP_md5_sha1()
+ case crypto.SHA1:
+ return C._goboringcrypto_EVP_sha1()
+ case crypto.SHA224:
+ return C._goboringcrypto_EVP_sha224()
+ case crypto.SHA256:
+ return C._goboringcrypto_EVP_sha256()
+ case crypto.SHA384:
+ return C._goboringcrypto_EVP_sha384()
+ case crypto.SHA512:
+ return C._goboringcrypto_EVP_sha512()
+ }
+ return nil
+}
+
+// NewHMAC returns a new HMAC using BoringCrypto.
+// The function h must return a hash implemented by
+// BoringCrypto (for example, h could be boring.NewSHA256).
+// If h is not recognized, NewHMAC returns nil.
+func NewHMAC(h func() hash.Hash, key []byte) hash.Hash {
+ ch := h()
+ md := hashToMD(ch)
+ if md == nil {
+ return nil
+ }
+
+ // Note: Could hash down long keys here using EVP_Digest.
+ hkey := bytes.Clone(key)
+ hmac := &boringHMAC{
+ md: md,
+ size: ch.Size(),
+ blockSize: ch.BlockSize(),
+ key: hkey,
+ }
+ hmac.Reset()
+ return hmac
+}
+
+type boringHMAC struct {
+ md *C.GO_EVP_MD
+ ctx C.GO_HMAC_CTX
+ ctx2 C.GO_HMAC_CTX
+ size int
+ blockSize int
+ key []byte
+ sum []byte
+ needCleanup bool
+}
+
+func (h *boringHMAC) Reset() {
+ if h.needCleanup {
+ C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx)
+ } else {
+ h.needCleanup = true
+ // Note: Because of the finalizer, any time h.ctx is passed to cgo,
+ // that call must be followed by a call to runtime.KeepAlive(h),
+ // to make sure h is not collected (and finalized) before the cgo
+ // call returns.
+ runtime.SetFinalizer(h, (*boringHMAC).finalize)
+ }
+ C._goboringcrypto_HMAC_CTX_init(&h.ctx)
+
+ if C._goboringcrypto_HMAC_Init(&h.ctx, unsafe.Pointer(base(h.key)), C.int(len(h.key)), h.md) == 0 {
+ panic("boringcrypto: HMAC_Init failed")
+ }
+ if int(C._goboringcrypto_HMAC_size(&h.ctx)) != h.size {
+ println("boringcrypto: HMAC size:", C._goboringcrypto_HMAC_size(&h.ctx), "!=", h.size)
+ panic("boringcrypto: HMAC size mismatch")
+ }
+ runtime.KeepAlive(h) // Next line will keep h alive too; just making doubly sure.
+ h.sum = nil
+}
+
+func (h *boringHMAC) finalize() {
+ C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx)
+}
+
+func (h *boringHMAC) Write(p []byte) (int, error) {
+ if len(p) > 0 {
+ C._goboringcrypto_HMAC_Update(&h.ctx, (*C.uint8_t)(unsafe.Pointer(&p[0])), C.size_t(len(p)))
+ }
+ runtime.KeepAlive(h)
+ return len(p), nil
+}
+
+func (h *boringHMAC) Size() int {
+ return h.size
+}
+
+func (h *boringHMAC) BlockSize() int {
+ return h.blockSize
+}
+
+func (h *boringHMAC) Sum(in []byte) []byte {
+ if h.sum == nil {
+ size := h.Size()
+ h.sum = make([]byte, size)
+ }
+ // Make copy of context because Go hash.Hash mandates
+ // that Sum has no effect on the underlying stream.
+ // In particular it is OK to Sum, then Write more, then Sum again,
+ // and the second Sum acts as if the first didn't happen.
+ C._goboringcrypto_HMAC_CTX_init(&h.ctx2)
+ if C._goboringcrypto_HMAC_CTX_copy_ex(&h.ctx2, &h.ctx) == 0 {
+ panic("boringcrypto: HMAC_CTX_copy_ex failed")
+ }
+ C._goboringcrypto_HMAC_Final(&h.ctx2, (*C.uint8_t)(unsafe.Pointer(&h.sum[0])), nil)
+ C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx2)
+ return append(in, h.sum...)
+}
diff --git a/src/crypto/internal/boring/notboring.go b/src/crypto/internal/boring/notboring.go
new file mode 100644
index 0000000..1c5e4c7
--- /dev/null
+++ b/src/crypto/internal/boring/notboring.go
@@ -0,0 +1,122 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !(boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan && cgo)
+
+package boring
+
+import (
+ "crypto"
+ "crypto/cipher"
+ "crypto/internal/boring/sig"
+ "hash"
+)
+
+const available = false
+
+// Unreachable marks code that should be unreachable
+// when BoringCrypto is in use. It is a no-op without BoringCrypto.
+func Unreachable() {
+ // Code that's unreachable when using BoringCrypto
+ // is exactly the code we want to detect for reporting
+ // standard Go crypto.
+ sig.StandardCrypto()
+}
+
+// UnreachableExceptTests marks code that should be unreachable
+// when BoringCrypto is in use. It is a no-op without BoringCrypto.
+func UnreachableExceptTests() {}
+
+type randReader int
+
+func (randReader) Read(b []byte) (int, error) { panic("boringcrypto: not available") }
+
+const RandReader = randReader(0)
+
+func NewSHA1() hash.Hash { panic("boringcrypto: not available") }
+func NewSHA224() hash.Hash { panic("boringcrypto: not available") }
+func NewSHA256() hash.Hash { panic("boringcrypto: not available") }
+func NewSHA384() hash.Hash { panic("boringcrypto: not available") }
+func NewSHA512() hash.Hash { panic("boringcrypto: not available") }
+
+func SHA1([]byte) [20]byte { panic("boringcrypto: not available") }
+func SHA224([]byte) [28]byte { panic("boringcrypto: not available") }
+func SHA256([]byte) [32]byte { panic("boringcrypto: not available") }
+func SHA384([]byte) [48]byte { panic("boringcrypto: not available") }
+func SHA512([]byte) [64]byte { panic("boringcrypto: not available") }
+
+func NewHMAC(h func() hash.Hash, key []byte) hash.Hash { panic("boringcrypto: not available") }
+
+func NewAESCipher(key []byte) (cipher.Block, error) { panic("boringcrypto: not available") }
+func NewGCMTLS(cipher.Block) (cipher.AEAD, error) { panic("boringcrypto: not available") }
+
+type PublicKeyECDSA struct{ _ int }
+type PrivateKeyECDSA struct{ _ int }
+
+func GenerateKeyECDSA(curve string) (X, Y, D BigInt, err error) {
+ panic("boringcrypto: not available")
+}
+func NewPrivateKeyECDSA(curve string, X, Y, D BigInt) (*PrivateKeyECDSA, error) {
+ panic("boringcrypto: not available")
+}
+func NewPublicKeyECDSA(curve string, X, Y BigInt) (*PublicKeyECDSA, error) {
+ panic("boringcrypto: not available")
+}
+func SignMarshalECDSA(priv *PrivateKeyECDSA, hash []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func VerifyECDSA(pub *PublicKeyECDSA, hash []byte, sig []byte) bool {
+ panic("boringcrypto: not available")
+}
+
+type PublicKeyRSA struct{ _ int }
+type PrivateKeyRSA struct{ _ int }
+
+func DecryptRSAOAEP(h, mgfHash hash.Hash, priv *PrivateKeyRSA, ciphertext, label []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func DecryptRSAPKCS1(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func DecryptRSANoPadding(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func EncryptRSAOAEP(h, mgfHash hash.Hash, pub *PublicKeyRSA, msg, label []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func EncryptRSAPKCS1(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func EncryptRSANoPadding(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func GenerateKeyRSA(bits int) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error) {
+ panic("boringcrypto: not available")
+}
+func NewPrivateKeyRSA(N, E, D, P, Q, Dp, Dq, Qinv BigInt) (*PrivateKeyRSA, error) {
+ panic("boringcrypto: not available")
+}
+func NewPublicKeyRSA(N, E BigInt) (*PublicKeyRSA, error) { panic("boringcrypto: not available") }
+func SignRSAPKCS1v15(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func SignRSAPSS(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte, saltLen int) ([]byte, error) {
+ panic("boringcrypto: not available")
+}
+func VerifyRSAPKCS1v15(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte) error {
+ panic("boringcrypto: not available")
+}
+func VerifyRSAPSS(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte, saltLen int) error {
+ panic("boringcrypto: not available")
+}
+
+type PublicKeyECDH struct{}
+type PrivateKeyECDH struct{}
+
+func ECDH(*PrivateKeyECDH, *PublicKeyECDH) ([]byte, error) { panic("boringcrypto: not available") }
+func GenerateKeyECDH(string) (*PrivateKeyECDH, []byte, error) { panic("boringcrypto: not available") }
+func NewPrivateKeyECDH(string, []byte) (*PrivateKeyECDH, error) { panic("boringcrypto: not available") }
+func NewPublicKeyECDH(string, []byte) (*PublicKeyECDH, error) { panic("boringcrypto: not available") }
+func (*PublicKeyECDH) Bytes() []byte { panic("boringcrypto: not available") }
+func (*PrivateKeyECDH) PublicKey() (*PublicKeyECDH, error) { panic("boringcrypto: not available") }
diff --git a/src/crypto/internal/boring/rand.go b/src/crypto/internal/boring/rand.go
new file mode 100644
index 0000000..7639c01
--- /dev/null
+++ b/src/crypto/internal/boring/rand.go
@@ -0,0 +1,24 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+// #include "goboringcrypto.h"
+import "C"
+import "unsafe"
+
+type randReader int
+
+func (randReader) Read(b []byte) (int, error) {
+ // Note: RAND_bytes should never fail; the return value exists only for historical reasons.
+ // We check it even so.
+ if len(b) > 0 && C._goboringcrypto_RAND_bytes((*C.uint8_t)(unsafe.Pointer(&b[0])), C.size_t(len(b))) == 0 {
+ return 0, fail("RAND_bytes")
+ }
+ return len(b), nil
+}
+
+const RandReader = randReader(0)
diff --git a/src/crypto/internal/boring/rsa.go b/src/crypto/internal/boring/rsa.go
new file mode 100644
index 0000000..fa693ea
--- /dev/null
+++ b/src/crypto/internal/boring/rsa.go
@@ -0,0 +1,379 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+// #include "goboringcrypto.h"
+import "C"
+import (
+ "crypto"
+ "crypto/subtle"
+ "errors"
+ "hash"
+ "runtime"
+ "strconv"
+ "unsafe"
+)
+
+func GenerateKeyRSA(bits int) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error) {
+ bad := func(e error) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error) {
+ return nil, nil, nil, nil, nil, nil, nil, nil, e
+ }
+
+ key := C._goboringcrypto_RSA_new()
+ if key == nil {
+ return bad(fail("RSA_new"))
+ }
+ defer C._goboringcrypto_RSA_free(key)
+
+ if C._goboringcrypto_RSA_generate_key_fips(key, C.int(bits), nil) == 0 {
+ return bad(fail("RSA_generate_key_fips"))
+ }
+
+ var n, e, d, p, q, dp, dq, qinv *C.GO_BIGNUM
+ C._goboringcrypto_RSA_get0_key(key, &n, &e, &d)
+ C._goboringcrypto_RSA_get0_factors(key, &p, &q)
+ C._goboringcrypto_RSA_get0_crt_params(key, &dp, &dq, &qinv)
+ return bnToBig(n), bnToBig(e), bnToBig(d), bnToBig(p), bnToBig(q), bnToBig(dp), bnToBig(dq), bnToBig(qinv), nil
+}
+
+type PublicKeyRSA struct {
+ // _key MUST NOT be accessed directly. Instead, use the withKey method.
+ _key *C.GO_RSA
+}
+
+func NewPublicKeyRSA(N, E BigInt) (*PublicKeyRSA, error) {
+ key := C._goboringcrypto_RSA_new()
+ if key == nil {
+ return nil, fail("RSA_new")
+ }
+ if !bigToBn(&key.n, N) ||
+ !bigToBn(&key.e, E) {
+ return nil, fail("BN_bin2bn")
+ }
+ k := &PublicKeyRSA{_key: key}
+ runtime.SetFinalizer(k, (*PublicKeyRSA).finalize)
+ return k, nil
+}
+
+func (k *PublicKeyRSA) finalize() {
+ C._goboringcrypto_RSA_free(k._key)
+}
+
+func (k *PublicKeyRSA) withKey(f func(*C.GO_RSA) C.int) C.int {
+ // Because of the finalizer, any time _key is passed to cgo, that call must
+ // be followed by a call to runtime.KeepAlive, to make sure k is not
+ // collected (and finalized) before the cgo call returns.
+ defer runtime.KeepAlive(k)
+ return f(k._key)
+}
+
+type PrivateKeyRSA struct {
+ // _key MUST NOT be accessed directly. Instead, use the withKey method.
+ _key *C.GO_RSA
+}
+
+func NewPrivateKeyRSA(N, E, D, P, Q, Dp, Dq, Qinv BigInt) (*PrivateKeyRSA, error) {
+ key := C._goboringcrypto_RSA_new()
+ if key == nil {
+ return nil, fail("RSA_new")
+ }
+ if !bigToBn(&key.n, N) ||
+ !bigToBn(&key.e, E) ||
+ !bigToBn(&key.d, D) ||
+ !bigToBn(&key.p, P) ||
+ !bigToBn(&key.q, Q) ||
+ !bigToBn(&key.dmp1, Dp) ||
+ !bigToBn(&key.dmq1, Dq) ||
+ !bigToBn(&key.iqmp, Qinv) {
+ return nil, fail("BN_bin2bn")
+ }
+ k := &PrivateKeyRSA{_key: key}
+ runtime.SetFinalizer(k, (*PrivateKeyRSA).finalize)
+ return k, nil
+}
+
+func (k *PrivateKeyRSA) finalize() {
+ C._goboringcrypto_RSA_free(k._key)
+}
+
+func (k *PrivateKeyRSA) withKey(f func(*C.GO_RSA) C.int) C.int {
+ // Because of the finalizer, any time _key is passed to cgo, that call must
+ // be followed by a call to runtime.KeepAlive, to make sure k is not
+ // collected (and finalized) before the cgo call returns.
+ defer runtime.KeepAlive(k)
+ return f(k._key)
+}
+
+func setupRSA(withKey func(func(*C.GO_RSA) C.int) C.int,
+ padding C.int, h, mgfHash hash.Hash, label []byte, saltLen int, ch crypto.Hash,
+ init func(*C.GO_EVP_PKEY_CTX) C.int) (pkey *C.GO_EVP_PKEY, ctx *C.GO_EVP_PKEY_CTX, err error) {
+ defer func() {
+ if err != nil {
+ if pkey != nil {
+ C._goboringcrypto_EVP_PKEY_free(pkey)
+ pkey = nil
+ }
+ if ctx != nil {
+ C._goboringcrypto_EVP_PKEY_CTX_free(ctx)
+ ctx = nil
+ }
+ }
+ }()
+
+ pkey = C._goboringcrypto_EVP_PKEY_new()
+ if pkey == nil {
+ return nil, nil, fail("EVP_PKEY_new")
+ }
+ if withKey(func(key *C.GO_RSA) C.int {
+ return C._goboringcrypto_EVP_PKEY_set1_RSA(pkey, key)
+ }) == 0 {
+ return nil, nil, fail("EVP_PKEY_set1_RSA")
+ }
+ ctx = C._goboringcrypto_EVP_PKEY_CTX_new(pkey, nil)
+ if ctx == nil {
+ return nil, nil, fail("EVP_PKEY_CTX_new")
+ }
+ if init(ctx) == 0 {
+ return nil, nil, fail("EVP_PKEY_operation_init")
+ }
+ if C._goboringcrypto_EVP_PKEY_CTX_set_rsa_padding(ctx, padding) == 0 {
+ return nil, nil, fail("EVP_PKEY_CTX_set_rsa_padding")
+ }
+ if padding == C.GO_RSA_PKCS1_OAEP_PADDING {
+ md := hashToMD(h)
+ if md == nil {
+ return nil, nil, errors.New("crypto/rsa: unsupported hash function")
+ }
+ mgfMD := hashToMD(mgfHash)
+ if mgfMD == nil {
+ return nil, nil, errors.New("crypto/rsa: unsupported hash function")
+ }
+ if C._goboringcrypto_EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md) == 0 {
+ return nil, nil, fail("EVP_PKEY_set_rsa_oaep_md")
+ }
+ if C._goboringcrypto_EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, mgfMD) == 0 {
+ return nil, nil, fail("EVP_PKEY_set_rsa_mgf1_md")
+ }
+ // ctx takes ownership of label, so malloc a copy for BoringCrypto to free.
+ clabel := (*C.uint8_t)(C._goboringcrypto_OPENSSL_malloc(C.size_t(len(label))))
+ if clabel == nil {
+ return nil, nil, fail("OPENSSL_malloc")
+ }
+ copy((*[1 << 30]byte)(unsafe.Pointer(clabel))[:len(label)], label)
+ if C._goboringcrypto_EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, clabel, C.size_t(len(label))) == 0 {
+ return nil, nil, fail("EVP_PKEY_CTX_set0_rsa_oaep_label")
+ }
+ }
+ if padding == C.GO_RSA_PKCS1_PSS_PADDING {
+ if saltLen != 0 {
+ if C._goboringcrypto_EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, C.int(saltLen)) == 0 {
+ return nil, nil, fail("EVP_PKEY_set_rsa_pss_saltlen")
+ }
+ }
+ md := cryptoHashToMD(ch)
+ if md == nil {
+ return nil, nil, errors.New("crypto/rsa: unsupported hash function")
+ }
+ if C._goboringcrypto_EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, md) == 0 {
+ return nil, nil, fail("EVP_PKEY_set_rsa_mgf1_md")
+ }
+ }
+
+ return pkey, ctx, nil
+}
+
+func cryptRSA(withKey func(func(*C.GO_RSA) C.int) C.int,
+ padding C.int, h, mgfHash hash.Hash, label []byte, saltLen int, ch crypto.Hash,
+ init func(*C.GO_EVP_PKEY_CTX) C.int,
+ crypt func(*C.GO_EVP_PKEY_CTX, *C.uint8_t, *C.size_t, *C.uint8_t, C.size_t) C.int,
+ in []byte) ([]byte, error) {
+
+ pkey, ctx, err := setupRSA(withKey, padding, h, mgfHash, label, saltLen, ch, init)
+ if err != nil {
+ return nil, err
+ }
+ defer C._goboringcrypto_EVP_PKEY_free(pkey)
+ defer C._goboringcrypto_EVP_PKEY_CTX_free(ctx)
+
+ var outLen C.size_t
+ if crypt(ctx, nil, &outLen, base(in), C.size_t(len(in))) == 0 {
+ return nil, fail("EVP_PKEY_decrypt/encrypt")
+ }
+ out := make([]byte, outLen)
+ if crypt(ctx, base(out), &outLen, base(in), C.size_t(len(in))) == 0 {
+ return nil, fail("EVP_PKEY_decrypt/encrypt")
+ }
+ return out[:outLen], nil
+}
+
+func DecryptRSAOAEP(h, mgfHash hash.Hash, priv *PrivateKeyRSA, ciphertext, label []byte) ([]byte, error) {
+ return cryptRSA(priv.withKey, C.GO_RSA_PKCS1_OAEP_PADDING, h, mgfHash, label, 0, 0, decryptInit, decrypt, ciphertext)
+}
+
+func EncryptRSAOAEP(h, mgfHash hash.Hash, pub *PublicKeyRSA, msg, label []byte) ([]byte, error) {
+ return cryptRSA(pub.withKey, C.GO_RSA_PKCS1_OAEP_PADDING, h, mgfHash, label, 0, 0, encryptInit, encrypt, msg)
+}
+
+func DecryptRSAPKCS1(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
+ return cryptRSA(priv.withKey, C.GO_RSA_PKCS1_PADDING, nil, nil, nil, 0, 0, decryptInit, decrypt, ciphertext)
+}
+
+func EncryptRSAPKCS1(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
+ return cryptRSA(pub.withKey, C.GO_RSA_PKCS1_PADDING, nil, nil, nil, 0, 0, encryptInit, encrypt, msg)
+}
+
+func DecryptRSANoPadding(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
+ return cryptRSA(priv.withKey, C.GO_RSA_NO_PADDING, nil, nil, nil, 0, 0, decryptInit, decrypt, ciphertext)
+}
+
+func EncryptRSANoPadding(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
+ return cryptRSA(pub.withKey, C.GO_RSA_NO_PADDING, nil, nil, nil, 0, 0, encryptInit, encrypt, msg)
+}
+
+// These dumb wrappers work around the fact that cgo functions cannot be used as values directly.
+
+func decryptInit(ctx *C.GO_EVP_PKEY_CTX) C.int {
+ return C._goboringcrypto_EVP_PKEY_decrypt_init(ctx)
+}
+
+func decrypt(ctx *C.GO_EVP_PKEY_CTX, out *C.uint8_t, outLen *C.size_t, in *C.uint8_t, inLen C.size_t) C.int {
+ return C._goboringcrypto_EVP_PKEY_decrypt(ctx, out, outLen, in, inLen)
+}
+
+func encryptInit(ctx *C.GO_EVP_PKEY_CTX) C.int {
+ return C._goboringcrypto_EVP_PKEY_encrypt_init(ctx)
+}
+
+func encrypt(ctx *C.GO_EVP_PKEY_CTX, out *C.uint8_t, outLen *C.size_t, in *C.uint8_t, inLen C.size_t) C.int {
+ return C._goboringcrypto_EVP_PKEY_encrypt(ctx, out, outLen, in, inLen)
+}
+
+var invalidSaltLenErr = errors.New("crypto/rsa: PSSOptions.SaltLength cannot be negative")
+
+func SignRSAPSS(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte, saltLen int) ([]byte, error) {
+ md := cryptoHashToMD(h)
+ if md == nil {
+ return nil, errors.New("crypto/rsa: unsupported hash function")
+ }
+
+ // A salt length of -2 is valid in BoringSSL, but not in crypto/rsa, so reject
+ // it, and lengths < -2, before we convert to the BoringSSL sentinel values.
+ if saltLen <= -2 {
+ return nil, invalidSaltLenErr
+ }
+
+ // BoringSSL uses sentinel salt length values like we do, but the values don't
+ // fully match what we use. We both use -1 for salt length equal to hash length,
+ // but BoringSSL uses -2 to mean maximal size where we use 0. In the latter
+ // case convert to the BoringSSL version.
+ if saltLen == 0 {
+ saltLen = -2
+ }
+
+ var out []byte
+ var outLen C.size_t
+ if priv.withKey(func(key *C.GO_RSA) C.int {
+ out = make([]byte, C._goboringcrypto_RSA_size(key))
+ return C._goboringcrypto_RSA_sign_pss_mgf1(key, &outLen, base(out), C.size_t(len(out)),
+ base(hashed), C.size_t(len(hashed)), md, nil, C.int(saltLen))
+ }) == 0 {
+ return nil, fail("RSA_sign_pss_mgf1")
+ }
+
+ return out[:outLen], nil
+}
+
+func VerifyRSAPSS(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte, saltLen int) error {
+ md := cryptoHashToMD(h)
+ if md == nil {
+ return errors.New("crypto/rsa: unsupported hash function")
+ }
+
+ // A salt length of -2 is valid in BoringSSL, but not in crypto/rsa, so reject
+ // it, and lengths < -2, before we convert to the BoringSSL sentinel values.
+ if saltLen <= -2 {
+ return invalidSaltLenErr
+ }
+
+ // BoringSSL uses sentinel salt length values like we do, but the values don't
+ // fully match what we use. We both use -1 for salt length equal to hash length,
+ // but BoringSSL uses -2 to mean maximal size where we use 0. In the latter
+ // case convert to the BoringSSL version.
+ if saltLen == 0 {
+ saltLen = -2
+ }
+
+ if pub.withKey(func(key *C.GO_RSA) C.int {
+ return C._goboringcrypto_RSA_verify_pss_mgf1(key, base(hashed), C.size_t(len(hashed)),
+ md, nil, C.int(saltLen), base(sig), C.size_t(len(sig)))
+ }) == 0 {
+ return fail("RSA_verify_pss_mgf1")
+ }
+ return nil
+}
+
+func SignRSAPKCS1v15(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte) ([]byte, error) {
+ if h == 0 {
+ // No hashing.
+ var out []byte
+ var outLen C.size_t
+ if priv.withKey(func(key *C.GO_RSA) C.int {
+ out = make([]byte, C._goboringcrypto_RSA_size(key))
+ return C._goboringcrypto_RSA_sign_raw(key, &outLen, base(out), C.size_t(len(out)),
+ base(hashed), C.size_t(len(hashed)), C.GO_RSA_PKCS1_PADDING)
+ }) == 0 {
+ return nil, fail("RSA_sign_raw")
+ }
+ return out[:outLen], nil
+ }
+
+ md := cryptoHashToMD(h)
+ if md == nil {
+ return nil, errors.New("crypto/rsa: unsupported hash function: " + strconv.Itoa(int(h)))
+ }
+ nid := C._goboringcrypto_EVP_MD_type(md)
+ var out []byte
+ var outLen C.uint
+ if priv.withKey(func(key *C.GO_RSA) C.int {
+ out = make([]byte, C._goboringcrypto_RSA_size(key))
+ return C._goboringcrypto_RSA_sign(nid, base(hashed), C.uint(len(hashed)),
+ base(out), &outLen, key)
+ }) == 0 {
+ return nil, fail("RSA_sign")
+ }
+ return out[:outLen], nil
+}
+
+func VerifyRSAPKCS1v15(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte) error {
+ if h == 0 {
+ var out []byte
+ var outLen C.size_t
+ if pub.withKey(func(key *C.GO_RSA) C.int {
+ out = make([]byte, C._goboringcrypto_RSA_size(key))
+ return C._goboringcrypto_RSA_verify_raw(key, &outLen, base(out),
+ C.size_t(len(out)), base(sig), C.size_t(len(sig)), C.GO_RSA_PKCS1_PADDING)
+ }) == 0 {
+ return fail("RSA_verify")
+ }
+ if subtle.ConstantTimeCompare(hashed, out[:outLen]) != 1 {
+ return fail("RSA_verify")
+ }
+ return nil
+ }
+ md := cryptoHashToMD(h)
+ if md == nil {
+ return errors.New("crypto/rsa: unsupported hash function")
+ }
+ nid := C._goboringcrypto_EVP_MD_type(md)
+ if pub.withKey(func(key *C.GO_RSA) C.int {
+ return C._goboringcrypto_RSA_verify(nid, base(hashed), C.size_t(len(hashed)),
+ base(sig), C.size_t(len(sig)), key)
+ }) == 0 {
+ return fail("RSA_verify")
+ }
+ return nil
+}
diff --git a/src/crypto/internal/boring/sha.go b/src/crypto/internal/boring/sha.go
new file mode 100644
index 0000000..cf82f3f
--- /dev/null
+++ b/src/crypto/internal/boring/sha.go
@@ -0,0 +1,599 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto && linux && (amd64 || arm64) && !android && !cmd_go_bootstrap && !msan
+
+package boring
+
+/*
+#include "goboringcrypto.h"
+
+int
+_goboringcrypto_gosha1(void *p, size_t n, void *out)
+{
+ GO_SHA_CTX ctx;
+ _goboringcrypto_SHA1_Init(&ctx);
+ return _goboringcrypto_SHA1_Update(&ctx, p, n) &&
+ _goboringcrypto_SHA1_Final(out, &ctx);
+}
+
+int
+_goboringcrypto_gosha224(void *p, size_t n, void *out)
+{
+ GO_SHA256_CTX ctx;
+ _goboringcrypto_SHA224_Init(&ctx);
+ return _goboringcrypto_SHA224_Update(&ctx, p, n) &&
+ _goboringcrypto_SHA224_Final(out, &ctx);
+}
+
+int
+_goboringcrypto_gosha256(void *p, size_t n, void *out)
+{
+ GO_SHA256_CTX ctx;
+ _goboringcrypto_SHA256_Init(&ctx);
+ return _goboringcrypto_SHA256_Update(&ctx, p, n) &&
+ _goboringcrypto_SHA256_Final(out, &ctx);
+}
+
+int
+_goboringcrypto_gosha384(void *p, size_t n, void *out)
+{
+ GO_SHA512_CTX ctx;
+ _goboringcrypto_SHA384_Init(&ctx);
+ return _goboringcrypto_SHA384_Update(&ctx, p, n) &&
+ _goboringcrypto_SHA384_Final(out, &ctx);
+}
+
+int
+_goboringcrypto_gosha512(void *p, size_t n, void *out)
+{
+ GO_SHA512_CTX ctx;
+ _goboringcrypto_SHA512_Init(&ctx);
+ return _goboringcrypto_SHA512_Update(&ctx, p, n) &&
+ _goboringcrypto_SHA512_Final(out, &ctx);
+}
+
+*/
+import "C"
+import (
+ "errors"
+ "hash"
+ "unsafe"
+)
+
+// NOTE: The cgo calls in this file are arranged to avoid marking the parameters as escaping.
+// To do that, we call noescape (including via addr).
+// We must also make sure that the data pointer arguments have the form unsafe.Pointer(&...)
+// so that cgo does not annotate them with cgoCheckPointer calls. If it did that, it might look
+// beyond the byte slice and find Go pointers in unprocessed parts of a larger allocation.
+// To do both of these simultaneously, the idiom is unsafe.Pointer(&*addr(p)),
+// where addr returns the base pointer of p, substituting a non-nil pointer for nil,
+// and applying a noescape along the way.
+// This is all to preserve compatibility with the allocation behavior of the non-boring implementations.
+
+func SHA1(p []byte) (sum [20]byte) {
+ if C._goboringcrypto_gosha1(unsafe.Pointer(&*addr(p)), C.size_t(len(p)), unsafe.Pointer(&*addr(sum[:]))) == 0 {
+ panic("boringcrypto: SHA1 failed")
+ }
+ return
+}
+
+func SHA224(p []byte) (sum [28]byte) {
+ if C._goboringcrypto_gosha224(unsafe.Pointer(&*addr(p)), C.size_t(len(p)), unsafe.Pointer(&*addr(sum[:]))) == 0 {
+ panic("boringcrypto: SHA224 failed")
+ }
+ return
+}
+
+func SHA256(p []byte) (sum [32]byte) {
+ if C._goboringcrypto_gosha256(unsafe.Pointer(&*addr(p)), C.size_t(len(p)), unsafe.Pointer(&*addr(sum[:]))) == 0 {
+ panic("boringcrypto: SHA256 failed")
+ }
+ return
+}
+
+func SHA384(p []byte) (sum [48]byte) {
+ if C._goboringcrypto_gosha384(unsafe.Pointer(&*addr(p)), C.size_t(len(p)), unsafe.Pointer(&*addr(sum[:]))) == 0 {
+ panic("boringcrypto: SHA384 failed")
+ }
+ return
+}
+
+func SHA512(p []byte) (sum [64]byte) {
+ if C._goboringcrypto_gosha512(unsafe.Pointer(&*addr(p)), C.size_t(len(p)), unsafe.Pointer(&*addr(sum[:]))) == 0 {
+ panic("boringcrypto: SHA512 failed")
+ }
+ return
+}
+
+// NewSHA1 returns a new SHA1 hash.
+func NewSHA1() hash.Hash {
+ h := new(sha1Hash)
+ h.Reset()
+ return h
+}
+
+type sha1Hash struct {
+ ctx C.GO_SHA_CTX
+ out [20]byte
+}
+
+type sha1Ctx struct {
+ h [5]uint32
+ nl, nh uint32
+ x [64]byte
+ nx uint32
+}
+
+func (h *sha1Hash) noescapeCtx() *C.GO_SHA_CTX {
+ return (*C.GO_SHA_CTX)(noescape(unsafe.Pointer(&h.ctx)))
+}
+
+func (h *sha1Hash) Reset() {
+ C._goboringcrypto_SHA1_Init(h.noescapeCtx())
+}
+
+func (h *sha1Hash) Size() int { return 20 }
+func (h *sha1Hash) BlockSize() int { return 64 }
+func (h *sha1Hash) Sum(dst []byte) []byte { return h.sum(dst) }
+
+func (h *sha1Hash) Write(p []byte) (int, error) {
+ if len(p) > 0 && C._goboringcrypto_SHA1_Update(h.noescapeCtx(), unsafe.Pointer(&*addr(p)), C.size_t(len(p))) == 0 {
+ panic("boringcrypto: SHA1_Update failed")
+ }
+ return len(p), nil
+}
+
+func (h0 *sha1Hash) sum(dst []byte) []byte {
+ h := *h0 // make copy so future Write+Sum is valid
+ if C._goboringcrypto_SHA1_Final((*C.uint8_t)(noescape(unsafe.Pointer(&h.out[0]))), h.noescapeCtx()) == 0 {
+ panic("boringcrypto: SHA1_Final failed")
+ }
+ return append(dst, h.out[:]...)
+}
+
+const (
+ sha1Magic = "sha\x01"
+ sha1MarshaledSize = len(sha1Magic) + 5*4 + 64 + 8
+)
+
+func (h *sha1Hash) MarshalBinary() ([]byte, error) {
+ d := (*sha1Ctx)(unsafe.Pointer(&h.ctx))
+ b := make([]byte, 0, sha1MarshaledSize)
+ b = append(b, sha1Magic...)
+ b = appendUint32(b, d.h[0])
+ b = appendUint32(b, d.h[1])
+ b = appendUint32(b, d.h[2])
+ b = appendUint32(b, d.h[3])
+ b = appendUint32(b, d.h[4])
+ b = append(b, d.x[:d.nx]...)
+ b = b[:len(b)+len(d.x)-int(d.nx)] // already zero
+ b = appendUint64(b, uint64(d.nl)>>3|uint64(d.nh)<<29)
+ return b, nil
+}
+
+func (h *sha1Hash) UnmarshalBinary(b []byte) error {
+ if len(b) < len(sha1Magic) || string(b[:len(sha1Magic)]) != sha1Magic {
+ return errors.New("crypto/sha1: invalid hash state identifier")
+ }
+ if len(b) != sha1MarshaledSize {
+ return errors.New("crypto/sha1: invalid hash state size")
+ }
+ d := (*sha1Ctx)(unsafe.Pointer(&h.ctx))
+ b = b[len(sha1Magic):]
+ b, d.h[0] = consumeUint32(b)
+ b, d.h[1] = consumeUint32(b)
+ b, d.h[2] = consumeUint32(b)
+ b, d.h[3] = consumeUint32(b)
+ b, d.h[4] = consumeUint32(b)
+ b = b[copy(d.x[:], b):]
+ b, n := consumeUint64(b)
+ d.nl = uint32(n << 3)
+ d.nh = uint32(n >> 29)
+ d.nx = uint32(n) % 64
+ return nil
+}
+
+// NewSHA224 returns a new SHA224 hash.
+func NewSHA224() hash.Hash {
+ h := new(sha224Hash)
+ h.Reset()
+ return h
+}
+
+type sha224Hash struct {
+ ctx C.GO_SHA256_CTX
+ out [224 / 8]byte
+}
+
+func (h *sha224Hash) noescapeCtx() *C.GO_SHA256_CTX {
+ return (*C.GO_SHA256_CTX)(noescape(unsafe.Pointer(&h.ctx)))
+}
+
+func (h *sha224Hash) Reset() {
+ C._goboringcrypto_SHA224_Init(h.noescapeCtx())
+}
+func (h *sha224Hash) Size() int { return 224 / 8 }
+func (h *sha224Hash) BlockSize() int { return 64 }
+func (h *sha224Hash) Sum(dst []byte) []byte { return h.sum(dst) }
+
+func (h *sha224Hash) Write(p []byte) (int, error) {
+ if len(p) > 0 && C._goboringcrypto_SHA224_Update(h.noescapeCtx(), unsafe.Pointer(&*addr(p)), C.size_t(len(p))) == 0 {
+ panic("boringcrypto: SHA224_Update failed")
+ }
+ return len(p), nil
+}
+
+func (h0 *sha224Hash) sum(dst []byte) []byte {
+ h := *h0 // make copy so future Write+Sum is valid
+ if C._goboringcrypto_SHA224_Final((*C.uint8_t)(noescape(unsafe.Pointer(&h.out[0]))), h.noescapeCtx()) == 0 {
+ panic("boringcrypto: SHA224_Final failed")
+ }
+ return append(dst, h.out[:]...)
+}
+
+// NewSHA256 returns a new SHA256 hash.
+func NewSHA256() hash.Hash {
+ h := new(sha256Hash)
+ h.Reset()
+ return h
+}
+
+type sha256Hash struct {
+ ctx C.GO_SHA256_CTX
+ out [256 / 8]byte
+}
+
+func (h *sha256Hash) noescapeCtx() *C.GO_SHA256_CTX {
+ return (*C.GO_SHA256_CTX)(noescape(unsafe.Pointer(&h.ctx)))
+}
+
+func (h *sha256Hash) Reset() {
+ C._goboringcrypto_SHA256_Init(h.noescapeCtx())
+}
+func (h *sha256Hash) Size() int { return 256 / 8 }
+func (h *sha256Hash) BlockSize() int { return 64 }
+func (h *sha256Hash) Sum(dst []byte) []byte { return h.sum(dst) }
+
+func (h *sha256Hash) Write(p []byte) (int, error) {
+ if len(p) > 0 && C._goboringcrypto_SHA256_Update(h.noescapeCtx(), unsafe.Pointer(&*addr(p)), C.size_t(len(p))) == 0 {
+ panic("boringcrypto: SHA256_Update failed")
+ }
+ return len(p), nil
+}
+
+func (h0 *sha256Hash) sum(dst []byte) []byte {
+ h := *h0 // make copy so future Write+Sum is valid
+ if C._goboringcrypto_SHA256_Final((*C.uint8_t)(noescape(unsafe.Pointer(&h.out[0]))), h.noescapeCtx()) == 0 {
+ panic("boringcrypto: SHA256_Final failed")
+ }
+ return append(dst, h.out[:]...)
+}
+
+const (
+ magic224 = "sha\x02"
+ magic256 = "sha\x03"
+ marshaledSize256 = len(magic256) + 8*4 + 64 + 8
+)
+
+type sha256Ctx struct {
+ h [8]uint32
+ nl, nh uint32
+ x [64]byte
+ nx uint32
+}
+
+func (h *sha224Hash) MarshalBinary() ([]byte, error) {
+ d := (*sha256Ctx)(unsafe.Pointer(&h.ctx))
+ b := make([]byte, 0, marshaledSize256)
+ b = append(b, magic224...)
+ b = appendUint32(b, d.h[0])
+ b = appendUint32(b, d.h[1])
+ b = appendUint32(b, d.h[2])
+ b = appendUint32(b, d.h[3])
+ b = appendUint32(b, d.h[4])
+ b = appendUint32(b, d.h[5])
+ b = appendUint32(b, d.h[6])
+ b = appendUint32(b, d.h[7])
+ b = append(b, d.x[:d.nx]...)
+ b = b[:len(b)+len(d.x)-int(d.nx)] // already zero
+ b = appendUint64(b, uint64(d.nl)>>3|uint64(d.nh)<<29)
+ return b, nil
+}
+
+func (h *sha256Hash) MarshalBinary() ([]byte, error) {
+ d := (*sha256Ctx)(unsafe.Pointer(&h.ctx))
+ b := make([]byte, 0, marshaledSize256)
+ b = append(b, magic256...)
+ b = appendUint32(b, d.h[0])
+ b = appendUint32(b, d.h[1])
+ b = appendUint32(b, d.h[2])
+ b = appendUint32(b, d.h[3])
+ b = appendUint32(b, d.h[4])
+ b = appendUint32(b, d.h[5])
+ b = appendUint32(b, d.h[6])
+ b = appendUint32(b, d.h[7])
+ b = append(b, d.x[:d.nx]...)
+ b = b[:len(b)+len(d.x)-int(d.nx)] // already zero
+ b = appendUint64(b, uint64(d.nl)>>3|uint64(d.nh)<<29)
+ return b, nil
+}
+
+func (h *sha224Hash) UnmarshalBinary(b []byte) error {
+ if len(b) < len(magic224) || string(b[:len(magic224)]) != magic224 {
+ return errors.New("crypto/sha256: invalid hash state identifier")
+ }
+ if len(b) != marshaledSize256 {
+ return errors.New("crypto/sha256: invalid hash state size")
+ }
+ d := (*sha256Ctx)(unsafe.Pointer(&h.ctx))
+ b = b[len(magic224):]
+ b, d.h[0] = consumeUint32(b)
+ b, d.h[1] = consumeUint32(b)
+ b, d.h[2] = consumeUint32(b)
+ b, d.h[3] = consumeUint32(b)
+ b, d.h[4] = consumeUint32(b)
+ b, d.h[5] = consumeUint32(b)
+ b, d.h[6] = consumeUint32(b)
+ b, d.h[7] = consumeUint32(b)
+ b = b[copy(d.x[:], b):]
+ b, n := consumeUint64(b)
+ d.nl = uint32(n << 3)
+ d.nh = uint32(n >> 29)
+ d.nx = uint32(n) % 64
+ return nil
+}
+
+func (h *sha256Hash) UnmarshalBinary(b []byte) error {
+ if len(b) < len(magic256) || string(b[:len(magic256)]) != magic256 {
+ return errors.New("crypto/sha256: invalid hash state identifier")
+ }
+ if len(b) != marshaledSize256 {
+ return errors.New("crypto/sha256: invalid hash state size")
+ }
+ d := (*sha256Ctx)(unsafe.Pointer(&h.ctx))
+ b = b[len(magic256):]
+ b, d.h[0] = consumeUint32(b)
+ b, d.h[1] = consumeUint32(b)
+ b, d.h[2] = consumeUint32(b)
+ b, d.h[3] = consumeUint32(b)
+ b, d.h[4] = consumeUint32(b)
+ b, d.h[5] = consumeUint32(b)
+ b, d.h[6] = consumeUint32(b)
+ b, d.h[7] = consumeUint32(b)
+ b = b[copy(d.x[:], b):]
+ b, n := consumeUint64(b)
+ d.nl = uint32(n << 3)
+ d.nh = uint32(n >> 29)
+ d.nx = uint32(n) % 64
+ return nil
+}
+
+// NewSHA384 returns a new SHA384 hash.
+func NewSHA384() hash.Hash {
+ h := new(sha384Hash)
+ h.Reset()
+ return h
+}
+
+type sha384Hash struct {
+ ctx C.GO_SHA512_CTX
+ out [384 / 8]byte
+}
+
+func (h *sha384Hash) noescapeCtx() *C.GO_SHA512_CTX {
+ return (*C.GO_SHA512_CTX)(noescape(unsafe.Pointer(&h.ctx)))
+}
+
+func (h *sha384Hash) Reset() {
+ C._goboringcrypto_SHA384_Init(h.noescapeCtx())
+}
+func (h *sha384Hash) Size() int { return 384 / 8 }
+func (h *sha384Hash) BlockSize() int { return 128 }
+func (h *sha384Hash) Sum(dst []byte) []byte { return h.sum(dst) }
+
+func (h *sha384Hash) Write(p []byte) (int, error) {
+ if len(p) > 0 && C._goboringcrypto_SHA384_Update(h.noescapeCtx(), unsafe.Pointer(&*addr(p)), C.size_t(len(p))) == 0 {
+ panic("boringcrypto: SHA384_Update failed")
+ }
+ return len(p), nil
+}
+
+func (h0 *sha384Hash) sum(dst []byte) []byte {
+ h := *h0 // make copy so future Write+Sum is valid
+ if C._goboringcrypto_SHA384_Final((*C.uint8_t)(noescape(unsafe.Pointer(&h.out[0]))), h.noescapeCtx()) == 0 {
+ panic("boringcrypto: SHA384_Final failed")
+ }
+ return append(dst, h.out[:]...)
+}
+
+// NewSHA512 returns a new SHA512 hash.
+func NewSHA512() hash.Hash {
+ h := new(sha512Hash)
+ h.Reset()
+ return h
+}
+
+type sha512Hash struct {
+ ctx C.GO_SHA512_CTX
+ out [512 / 8]byte
+}
+
+func (h *sha512Hash) noescapeCtx() *C.GO_SHA512_CTX {
+ return (*C.GO_SHA512_CTX)(noescape(unsafe.Pointer(&h.ctx)))
+}
+
+func (h *sha512Hash) Reset() {
+ C._goboringcrypto_SHA512_Init(h.noescapeCtx())
+}
+func (h *sha512Hash) Size() int { return 512 / 8 }
+func (h *sha512Hash) BlockSize() int { return 128 }
+func (h *sha512Hash) Sum(dst []byte) []byte { return h.sum(dst) }
+
+func (h *sha512Hash) Write(p []byte) (int, error) {
+ if len(p) > 0 && C._goboringcrypto_SHA512_Update(h.noescapeCtx(), unsafe.Pointer(&*addr(p)), C.size_t(len(p))) == 0 {
+ panic("boringcrypto: SHA512_Update failed")
+ }
+ return len(p), nil
+}
+
+func (h0 *sha512Hash) sum(dst []byte) []byte {
+ h := *h0 // make copy so future Write+Sum is valid
+ if C._goboringcrypto_SHA512_Final((*C.uint8_t)(noescape(unsafe.Pointer(&h.out[0]))), h.noescapeCtx()) == 0 {
+ panic("boringcrypto: SHA512_Final failed")
+ }
+ return append(dst, h.out[:]...)
+}
+
+type sha512Ctx struct {
+ h [8]uint64
+ nl, nh uint64
+ x [128]byte
+ nx uint32
+}
+
+const (
+ magic384 = "sha\x04"
+ magic512_224 = "sha\x05"
+ magic512_256 = "sha\x06"
+ magic512 = "sha\x07"
+ marshaledSize512 = len(magic512) + 8*8 + 128 + 8
+)
+
+func (h *sha384Hash) MarshalBinary() ([]byte, error) {
+ d := (*sha512Ctx)(unsafe.Pointer(&h.ctx))
+ b := make([]byte, 0, marshaledSize512)
+ b = append(b, magic384...)
+ b = appendUint64(b, d.h[0])
+ b = appendUint64(b, d.h[1])
+ b = appendUint64(b, d.h[2])
+ b = appendUint64(b, d.h[3])
+ b = appendUint64(b, d.h[4])
+ b = appendUint64(b, d.h[5])
+ b = appendUint64(b, d.h[6])
+ b = appendUint64(b, d.h[7])
+ b = append(b, d.x[:d.nx]...)
+ b = b[:len(b)+len(d.x)-int(d.nx)] // already zero
+ b = appendUint64(b, d.nl>>3|d.nh<<61)
+ return b, nil
+}
+
+func (h *sha512Hash) MarshalBinary() ([]byte, error) {
+ d := (*sha512Ctx)(unsafe.Pointer(&h.ctx))
+ b := make([]byte, 0, marshaledSize512)
+ b = append(b, magic512...)
+ b = appendUint64(b, d.h[0])
+ b = appendUint64(b, d.h[1])
+ b = appendUint64(b, d.h[2])
+ b = appendUint64(b, d.h[3])
+ b = appendUint64(b, d.h[4])
+ b = appendUint64(b, d.h[5])
+ b = appendUint64(b, d.h[6])
+ b = appendUint64(b, d.h[7])
+ b = append(b, d.x[:d.nx]...)
+ b = b[:len(b)+len(d.x)-int(d.nx)] // already zero
+ b = appendUint64(b, d.nl>>3|d.nh<<61)
+ return b, nil
+}
+
+func (h *sha384Hash) UnmarshalBinary(b []byte) error {
+ if len(b) < len(magic512) {
+ return errors.New("crypto/sha512: invalid hash state identifier")
+ }
+ if string(b[:len(magic384)]) != magic384 {
+ return errors.New("crypto/sha512: invalid hash state identifier")
+ }
+ if len(b) != marshaledSize512 {
+ return errors.New("crypto/sha512: invalid hash state size")
+ }
+ d := (*sha512Ctx)(unsafe.Pointer(&h.ctx))
+ b = b[len(magic512):]
+ b, d.h[0] = consumeUint64(b)
+ b, d.h[1] = consumeUint64(b)
+ b, d.h[2] = consumeUint64(b)
+ b, d.h[3] = consumeUint64(b)
+ b, d.h[4] = consumeUint64(b)
+ b, d.h[5] = consumeUint64(b)
+ b, d.h[6] = consumeUint64(b)
+ b, d.h[7] = consumeUint64(b)
+ b = b[copy(d.x[:], b):]
+ b, n := consumeUint64(b)
+ d.nl = n << 3
+ d.nh = n >> 61
+ d.nx = uint32(n) % 128
+ return nil
+}
+
+func (h *sha512Hash) UnmarshalBinary(b []byte) error {
+ if len(b) < len(magic512) {
+ return errors.New("crypto/sha512: invalid hash state identifier")
+ }
+ if string(b[:len(magic512)]) != magic512 {
+ return errors.New("crypto/sha512: invalid hash state identifier")
+ }
+ if len(b) != marshaledSize512 {
+ return errors.New("crypto/sha512: invalid hash state size")
+ }
+ d := (*sha512Ctx)(unsafe.Pointer(&h.ctx))
+ b = b[len(magic512):]
+ b, d.h[0] = consumeUint64(b)
+ b, d.h[1] = consumeUint64(b)
+ b, d.h[2] = consumeUint64(b)
+ b, d.h[3] = consumeUint64(b)
+ b, d.h[4] = consumeUint64(b)
+ b, d.h[5] = consumeUint64(b)
+ b, d.h[6] = consumeUint64(b)
+ b, d.h[7] = consumeUint64(b)
+ b = b[copy(d.x[:], b):]
+ b, n := consumeUint64(b)
+ d.nl = n << 3
+ d.nh = n >> 61
+ d.nx = uint32(n) % 128
+ return nil
+}
+
+func appendUint64(b []byte, x uint64) []byte {
+ var a [8]byte
+ putUint64(a[:], x)
+ return append(b, a[:]...)
+}
+
+func appendUint32(b []byte, x uint32) []byte {
+ var a [4]byte
+ putUint32(a[:], x)
+ return append(b, a[:]...)
+}
+
+func consumeUint64(b []byte) ([]byte, uint64) {
+ _ = b[7]
+ x := uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
+ uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
+ return b[8:], x
+}
+
+func consumeUint32(b []byte) ([]byte, uint32) {
+ _ = b[3]
+ x := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
+ return b[4:], x
+}
+
+func putUint64(x []byte, s uint64) {
+ _ = x[7]
+ x[0] = byte(s >> 56)
+ x[1] = byte(s >> 48)
+ x[2] = byte(s >> 40)
+ x[3] = byte(s >> 32)
+ x[4] = byte(s >> 24)
+ x[5] = byte(s >> 16)
+ x[6] = byte(s >> 8)
+ x[7] = byte(s)
+}
+
+func putUint32(x []byte, s uint32) {
+ _ = x[3]
+ x[0] = byte(s >> 24)
+ x[1] = byte(s >> 16)
+ x[2] = byte(s >> 8)
+ x[3] = byte(s)
+}
diff --git a/src/crypto/internal/boring/sig/sig.go b/src/crypto/internal/boring/sig/sig.go
new file mode 100644
index 0000000..716c03c
--- /dev/null
+++ b/src/crypto/internal/boring/sig/sig.go
@@ -0,0 +1,17 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package sig holds “code signatures” that can be called
+// and will result in certain code sequences being linked into
+// the final binary. The functions themselves are no-ops.
+package sig
+
+// BoringCrypto indicates that the BoringCrypto module is present.
+func BoringCrypto()
+
+// FIPSOnly indicates that package crypto/tls/fipsonly is present.
+func FIPSOnly()
+
+// StandardCrypto indicates that standard Go crypto is present.
+func StandardCrypto()
diff --git a/src/crypto/internal/boring/sig/sig_amd64.s b/src/crypto/internal/boring/sig/sig_amd64.s
new file mode 100644
index 0000000..64e3462
--- /dev/null
+++ b/src/crypto/internal/boring/sig/sig_amd64.s
@@ -0,0 +1,54 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "textflag.h"
+
+// These functions are no-ops, but you can search for their implementations
+// to find out whether they are linked into a particular binary.
+//
+// Each function consists of a two-byte jump over the next 29-bytes,
+// then a 5-byte indicator sequence unlikely to occur in real x86 instructions,
+// then a randomly-chosen 24-byte sequence, and finally a return instruction
+// (the target of the jump).
+//
+// These sequences are known to rsc.io/goversion.
+
+#define START \
+ BYTE $0xEB; BYTE $0x1D; BYTE $0xF4; BYTE $0x48; BYTE $0xF4; BYTE $0x4B; BYTE $0xF4
+
+#define END \
+ BYTE $0xC3
+
+// BoringCrypto indicates that BoringCrypto (in particular, its func init) is present.
+TEXT ·BoringCrypto(SB),NOSPLIT,$0
+ START
+ BYTE $0xB3; BYTE $0x32; BYTE $0xF5; BYTE $0x28;
+ BYTE $0x13; BYTE $0xA3; BYTE $0xB4; BYTE $0x50;
+ BYTE $0xD4; BYTE $0x41; BYTE $0xCC; BYTE $0x24;
+ BYTE $0x85; BYTE $0xF0; BYTE $0x01; BYTE $0x45;
+ BYTE $0x4E; BYTE $0x92; BYTE $0x10; BYTE $0x1B;
+ BYTE $0x1D; BYTE $0x2F; BYTE $0x19; BYTE $0x50;
+ END
+
+// StandardCrypto indicates that standard Go crypto is present.
+TEXT ·StandardCrypto(SB),NOSPLIT,$0
+ START
+ BYTE $0xba; BYTE $0xee; BYTE $0x4d; BYTE $0xfa;
+ BYTE $0x98; BYTE $0x51; BYTE $0xca; BYTE $0x56;
+ BYTE $0xa9; BYTE $0x11; BYTE $0x45; BYTE $0xe8;
+ BYTE $0x3e; BYTE $0x99; BYTE $0xc5; BYTE $0x9c;
+ BYTE $0xf9; BYTE $0x11; BYTE $0xcb; BYTE $0x8e;
+ BYTE $0x80; BYTE $0xda; BYTE $0xf1; BYTE $0x2f;
+ END
+
+// FIPSOnly indicates that crypto/tls/fipsonly is present.
+TEXT ·FIPSOnly(SB),NOSPLIT,$0
+ START
+ BYTE $0x36; BYTE $0x3C; BYTE $0xB9; BYTE $0xCE;
+ BYTE $0x9D; BYTE $0x68; BYTE $0x04; BYTE $0x7D;
+ BYTE $0x31; BYTE $0xF2; BYTE $0x8D; BYTE $0x32;
+ BYTE $0x5D; BYTE $0x5C; BYTE $0xA5; BYTE $0x87;
+ BYTE $0x3F; BYTE $0x5D; BYTE $0x80; BYTE $0xCA;
+ BYTE $0xF6; BYTE $0xD6; BYTE $0x15; BYTE $0x1B;
+ END
diff --git a/src/crypto/internal/boring/sig/sig_other.s b/src/crypto/internal/boring/sig/sig_other.s
new file mode 100644
index 0000000..2bbb1df
--- /dev/null
+++ b/src/crypto/internal/boring/sig/sig_other.s
@@ -0,0 +1,20 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// These functions are no-ops.
+// On amd64 they have recognizable implementations, so that you can
+// search a particular binary to see if they are present.
+// On other platforms (those using this source file), they don't.
+
+//go:build !amd64
+// +build !amd64
+
+TEXT ·BoringCrypto(SB),$0
+ RET
+
+TEXT ·FIPSOnly(SB),$0
+ RET
+
+TEXT ·StandardCrypto(SB),$0
+ RET
diff --git a/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso b/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso
new file mode 100644
index 0000000..6cea789
--- /dev/null
+++ b/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso
Binary files differ
diff --git a/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso b/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso
new file mode 100644
index 0000000..9659aa1
--- /dev/null
+++ b/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso
Binary files differ
diff --git a/src/crypto/internal/boring/syso/syso.go b/src/crypto/internal/boring/syso/syso.go
new file mode 100644
index 0000000..b338754
--- /dev/null
+++ b/src/crypto/internal/boring/syso/syso.go
@@ -0,0 +1,9 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build boringcrypto
+
+// This package only exists with GOEXPERIMENT=boringcrypto.
+// It provides the actual syso file.
+package syso