dhparam.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (C) 2017. See AUTHORS.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package openssl
  15. // #include "shim.h"
  16. import "C"
  17. import (
  18. "errors"
  19. "runtime"
  20. "unsafe"
  21. )
  22. type DH struct {
  23. dh *C.struct_dh_st
  24. }
  25. // LoadDHParametersFromPEM loads the Diffie-Hellman parameters from
  26. // a PEM-encoded block.
  27. func LoadDHParametersFromPEM(pem_block []byte) (*DH, error) {
  28. if len(pem_block) == 0 {
  29. return nil, errors.New("empty pem block")
  30. }
  31. bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]),
  32. C.int(len(pem_block)))
  33. if bio == nil {
  34. return nil, errors.New("failed creating bio")
  35. }
  36. defer C.BIO_free(bio)
  37. params := C.PEM_read_bio_DHparams(bio, nil, nil, nil)
  38. if params == nil {
  39. return nil, errors.New("failed reading dh parameters")
  40. }
  41. dhparams := &DH{dh: params}
  42. runtime.SetFinalizer(dhparams, func(dhparams *DH) {
  43. C.DH_free(dhparams.dh)
  44. })
  45. return dhparams, nil
  46. }
  47. // SetDHParameters sets the DH group (DH parameters) used to
  48. // negotiate an emphemeral DH key during handshaking.
  49. func (c *Ctx) SetDHParameters(dh *DH) error {
  50. runtime.LockOSThread()
  51. defer runtime.UnlockOSThread()
  52. if int(C.X_SSL_CTX_set_tmp_dh(c.ctx, dh.dh)) != 1 {
  53. return errorFromErrorQueue()
  54. }
  55. return nil
  56. }