コード例 #1
0
ファイル: PKey.cpp プロジェクト: CheneyWong/fibjs
result_t PKey::encrypt(Buffer_base *data, obj_ptr<Buffer_base> &retVal,
                       exlib::AsyncEvent *ac)
{
    if (switchToAsync(ac))
        return CHECK_ERROR(CALL_E_NOSYNC);

    int ret;
    std::string str;
    std::string output;
    size_t olen;

    data->toString(str);
    output.resize(POLARSSL_PREMASTER_SIZE);

    ret = pk_encrypt(&m_key, (const unsigned char *)str.c_str(), str.length(),
                     (unsigned char *)&output[0], &olen, output.length(),
                     ctr_drbg_random, &g_ssl.ctr_drbg);
    if (ret != 0)
        return CHECK_ERROR(_ssl::setError(ret));

    output.resize(olen);
    retVal = new Buffer(output);

    return 0;
}
コード例 #2
0
ファイル: keyserv.c プロジェクト: AhmadTux/DragonFlyBSD
cryptkeyres *
key_encrypt_1_svc_prog(uid_t uid, cryptkeyarg *arg)
{
	static cryptkeyres res;

	if (debugging) {
		fprintf(stderr, "encrypt(%ld, %s, %08x%08x) = ", uid,
				arg->remotename, arg->deskey.key.high,
				arg->deskey.key.low);
	}
	res.cryptkeyres_u.deskey = arg->deskey;
	res.status = pk_encrypt(uid, arg->remotename, NULL,
				&res.cryptkeyres_u.deskey);
	if (debugging) {
		if (res.status == KEY_SUCCESS) {
			fprintf(stderr, "%08x%08x\n",
					res.cryptkeyres_u.deskey.key.high,
					res.cryptkeyres_u.deskey.key.low);
		} else {
			fprintf(stderr, "%s\n", strstatus(res.status));
		}
		fflush(stderr);
	}
	return (&res);
}
コード例 #3
0
ファイル: encrypt.c プロジェクト: gilbert-fernandes/gnupg
/*
 * Write a pubkey-enc packet for the public key PK to OUT.
 */
int
write_pubkey_enc (ctrl_t ctrl,
                  PKT_public_key *pk, int throw_keyid, DEK *dek, iobuf_t out)
{
  PACKET pkt;
  PKT_pubkey_enc *enc;
  int rc;
  gcry_mpi_t frame;

  print_pubkey_algo_note ( pk->pubkey_algo );
  enc = xmalloc_clear ( sizeof *enc );
  enc->pubkey_algo = pk->pubkey_algo;
  keyid_from_pk( pk, enc->keyid );
  enc->throw_keyid = throw_keyid;

  /* Okay, what's going on: We have the session key somewhere in
   * the structure DEK and want to encode this session key in an
   * integer value of n bits. pubkey_nbits gives us the number of
   * bits we have to use.  We then encode the session key in some
   * way and we get it back in the big intger value FRAME.  Then
   * we use FRAME, the public key PK->PKEY and the algorithm
   * number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
   * returns the encrypted value in the array ENC->DATA.  This
   * array has a size which depends on the used algorithm (e.g. 2
   * for Elgamal).  We don't need frame anymore because we have
   * everything now in enc->data which is the passed to
   * build_packet().  */
  frame = encode_session_key (pk->pubkey_algo, dek,
                              pubkey_nbits (pk->pubkey_algo, pk->pkey));
  rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk, pk->pkey);
  gcry_mpi_release (frame);
  if (rc)
    log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
  else
    {
      if ( opt.verbose )
        {
          char *ustr = get_user_id_string_native (ctrl, enc->keyid);
          log_info (_("%s/%s.%s encrypted for: \"%s\"\n"),
                    openpgp_pk_algo_name (enc->pubkey_algo),
                    openpgp_cipher_algo_name (dek->algo),
                    dek->use_aead? openpgp_aead_algo_name (dek->use_aead)
                    /**/         : "CFB",
                    ustr );
          xfree (ustr);
        }
      /* And write it. */
      init_packet (&pkt);
      pkt.pkttype = PKT_PUBKEY_ENC;
      pkt.pkt.pubkey_enc = enc;
      rc = build_packet (out, &pkt);
      if (rc)
        log_error ("build_packet(pubkey_enc) failed: %s\n",
                   gpg_strerror (rc));
    }
  free_pubkey_enc(enc);
  return rc;
}
コード例 #4
0
int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
{
	size_t EncryptedLength = a_EncryptedMaxLength;
	int res = pk_encrypt(&m_Pk,
		a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
		ctr_drbg_random, &m_Ctr_drbg
	);
	if (res != 0)
	{
		return res;
	}
	return (int)EncryptedLength;
}
コード例 #5
0
ファイル: CryptoKey.cpp プロジェクト: ChriPiv/MCServer
int cCryptoKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
{
	ASSERT(IsValid());
	
	size_t EncryptedLength = a_EncryptedMaxLength;
	int res = pk_encrypt(&m_Pk,
		a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
		ctr_drbg_random, m_CtrDrbg.GetInternal()
	);
	if (res != 0)
	{
		return res;
	}
	return (int)EncryptedLength;
}
コード例 #6
0
struct item *asymmetric_encryption(struct item *key, struct item *payload)
  /*@ requires [?f]world(?pub, ?key_clsfy) &*&
               principal(?principal1, ?count1) &*&
               item(payload, ?pay, pub) &*& item(key, ?k, pub) &*&
               k == public_key_item(?principal2, ?count2); @*/
  /*@ ensures  [f]world(pub, key_clsfy) &*&
               principal(principal1, count1 + 1) &*&
               item(payload, pay, pub) &*& item(key, k, pub) &*&
               item(result, ?enc, pub) &*&
               col ? true :
                 enc == asymmetric_encrypted_item(principal2, count2,
                                                  some(pay), ?ent); @*/
{
  debug_print("ASYM ENCRYPTING:\n");
  print_item(payload);

  struct item* result;
  result = malloc(sizeof(struct item));
  if (result == 0) abort_crypto_lib("Malloc failed");

  {
    pk_context context;
    unsigned int olen;
    char output[MAX_PACKAGE_SIZE];

    // Key
    //@ close pk_context(&context);
    //@ open [f]world(pub, key_clsfy);
    pk_init(&context);
    //@ close [f]world(pub, key_clsfy);
    set_public_key(&context, key);
    //@ open [f]world(pub, key_clsfy);
    /*@ assert pk_context_with_key(&context, pk_public,
                                   ?principal, ?count, RSA_BIT_KEY_SIZE); @*/
    //@ assert col || principal == principal2;
    //@ assert col || count == count2;

    // Encryption
    //@ open item(payload, pay, pub);
    //@ assert [_]item_constraints(pay, ?pay_cs, pub);
    if (payload->size > RSA_KEY_SIZE)
      abort_crypto_lib("Asymmetric encryption failed: incorrect sizes");
    void *random_state = nonces_expose_state();
    //@ close random_state_predicate(havege_state_initialized);
    /*@ produce_function_pointer_chunk random_function(
                      asym_enc_havege_random_stub)
                     (havege_state_initialized)(state, out, len) { call(); } @*/
    //@ open principal(principal1, count1);
    if(pk_encrypt(&context, payload->content, (unsigned int) payload->size,
                  output, &olen, MAX_PACKAGE_SIZE,
                  asym_enc_havege_random_stub, random_state) != 0)
      abort_crypto_lib("Encryption failed");
    //@ close principal(principal1, count1 + 1);
    //@ open cryptogram(output, ?enc_length, ?enc_cs, ?enc_cg);
    //@ assert enc_cg == cg_asym_encrypted(principal, count, pay_cs, ?ent);
    //@ assert u_integer(&olen, enc_length);
    //@ assert enc_length > 0 &*& enc_length < MAX_PACKAGE_SIZE;
    //@ assert enc_length > 0 &*& enc_length <= RSA_SERIALIZED_KEY_SIZE;
    nonces_hide_state(random_state);
    //@ pk_release_context_with_key(&context);
    pk_free(&context);
    //@ open pk_context(&context);
    //@ close [f]world(pub, key_clsfy);

    // Create item
    result->size = TAG_LENGTH + (int) olen;
    result->content = malloc(result->size);
    if (result->content == 0) {abort_crypto_lib("Malloc failed");}
    write_tag(result->content, TAG_ASYMMETRIC_ENC);
    //@ assert result->content |-> ?cont &*& result->size |-> ?size;
    if (olen < MINIMAL_STRING_SIZE) {abort_crypto_lib("Asymmetric encryption failed: to small");}
    memcpy(result->content + TAG_LENGTH, output, olen);
    //@ assert chars(cont, TAG_LENGTH, ?cs_tag);
    //@ public_chars(cont, TAG_LENGTH);
    //@ chars_to_secret_crypto_chars(cont, TAG_LENGTH);
    //@ assert cs_tag == full_tag(TAG_ASYMMETRIC_ENC);
    //@ crypto_chars_join(cont);

    //@ item enc = asymmetric_encrypted_item(principal, count, some(pay), ent);
    //@ list<char> cs = append(cs_tag, enc_cs);
    //@ WELL_FORMED(cs_tag, enc_cs, TAG_ASYMMETRIC_ENC)
    //@ close ic_parts(enc)(cs_tag, enc_cs);
    //@ close ic_cg(enc)(enc_cs, enc_cg);
    /*@ if (col)
      {
        crypto_chars_to_chars(cont, size);
        public_chars(cont, size);
        chars_to_secret_crypto_chars(cont, size);
        public_generated_split(polarssl_pub(pub), cs, TAG_LENGTH);
      }
    @*/
    //@ well_formed_item_constraints(pay, enc);
    //@ close item_constraints(enc, cs, pub);
    //@ leak item_constraints(enc, cs, pub);
    //@ close item(result, enc, pub);
    zeroize(output, (int) olen);
    //@ chars_join(output);
    //@ close item(payload, pay, pub);
  }

  debug_print("ENCRYPTING RESULT:\n");
  print_item(result);

  return result;
}
コード例 #7
0
void receiver_msg2(int* socket, havege_state* havege_state,
                   pk_context* s_context, int receiver,
                   char* s_nonce, char* r_nonce)
  /*@ requires GENERAL_PRE(receiver) &*&
               pk_context_with_key(?r_context, pk_private,
                                   receiver, ?r_id, 8 * KEY_SIZE)  &*&
               pk_context_with_key(s_context, pk_public,
                                   ?sender, ?s_id, 8 * KEY_SIZE) &*&
               RECEIVER_INTER &*&
               cryptogram(r_nonce, NONCE_SIZE, ?r_nonce_ccs, ?r_nonce_cg) &*&
                 r_nonce_cg == cg_nonce(receiver, _) &*&
                 cg_info(r_nonce_cg) == int_pair(2, int_pair(sender,
                               int_pair(p_inst, int_pair(p_orig, c_orig)))); @*/
  /*@ ensures  GENERAL_POST(receiver) &*&
               pk_context_with_key(r_context, pk_private,
                                   receiver, r_id, 8 * KEY_SIZE)  &*&
               pk_context_with_key(s_context, pk_public,
                                   sender, s_id, 8 * KEY_SIZE) &*&
               (
                  col || bad(p_inst) || bad(receiver) ?
                    chars(s_nonce, NONCE_SIZE, ?s_nonce_cs) &*&
                    s_nonce_ccs == cs_to_ccs(s_nonce_cs)
                  :
                    cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg)
               ) &*&
               cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg); @*/
{
  //@ open principal(receiver, _);
  unsigned int size;
  char message[MSG2_SIZE];
  char encrypted[KEY_SIZE];
  //@ open receiver_inter(p_orig, c_orig, p_inst, s_nonce_ccs, s_nonce_cg);

  // Construct the message
  write_identifier(message, receiver);
  //@ list<crypto_char> rid_ccs = cs_to_ccs(identifier(receiver));
  //@ assert crypto_chars(normal, message, ID_SIZE, rid_ccs);
  //@ cs_to_ccs_crypto_chars(message, identifier(receiver));
  //@ public_chars(message, ID_SIZE);
  //@ chars_to_secret_crypto_chars(message, ID_SIZE);
  //@ bool condition =  col || bad(p_inst) || bad(receiver);
  /*@ if (!condition)
        open cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg);
      else
      {
        crypto_chars_to_chars(s_nonce, NONCE_SIZE);
        public_chars(s_nonce, NONCE_SIZE);
        chars_to_secret_crypto_chars(s_nonce, NONCE_SIZE);
      }
  @*/
  //@ open cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg);
  memcpy((void*) message + ID_SIZE, s_nonce, NONCE_SIZE);
  memcpy((void*) message + ID_SIZE + NONCE_SIZE, r_nonce, NONCE_SIZE);
  //@ crypto_chars_join(message);
  //@ crypto_chars_join(message);
  //@ list<crypto_char> msg2 = append(rid_ccs, append(s_nonce_ccs, r_nonce_ccs));
  //@ append_assoc(rid_ccs, s_nonce_ccs, r_nonce_ccs);
  //@ assert crypto_chars(secret, message, MSG2_SIZE, msg2);

  // Encrypt the message
  /*@ produce_function_pointer_chunk random_function(random_stub_nsl)
                    (havege_state_initialized)(state, out, len) { call(); } @*/
  //@ close random_state_predicate(havege_state_initialized);
  if (pk_encrypt(s_context, message, MSG2_SIZE, encrypted, &size,
                  KEY_SIZE, random_stub_nsl, havege_state) != 0)
    abort();
  //@ assert u_integer(&size, ?size_val);
  //@ assert cryptogram(encrypted, size_val, ?cs_enc, ?cg_enc);
  //@ take_append(ID_SIZE, rid_ccs, append(s_nonce_ccs, r_nonce_ccs));
  //@ drop_append(ID_SIZE, rid_ccs, append(s_nonce_ccs, r_nonce_ccs));
  //@ take_append(NONCE_SIZE, s_nonce_ccs, r_nonce_ccs);
  //@ drop_append(NONCE_SIZE, s_nonce_ccs, r_nonce_ccs);

  // Proof the message is public
  /*@ if (col || bad(sender) || bad(receiver))
      {
        assert crypto_chars(secret, message, MSG2_SIZE, msg2);
        crypto_chars_split(message, ID_SIZE);
        crypto_chars_split((void*) message + ID_SIZE, NONCE_SIZE);
        public_crypto_chars((void*) message, ID_SIZE);
        public_crypto_chars((void*) message + ID_SIZE, NONCE_SIZE);
        close nsl_pub(r_nonce_cg);
        leak nsl_pub(r_nonce_cg);
        close cryptogram((void*) message + ID_SIZE + NONCE_SIZE, NONCE_SIZE,
                         r_nonce_ccs, r_nonce_cg);
        public_cryptogram((void*) message + ID_SIZE + NONCE_SIZE, r_nonce_cg);
        
        assert chars((void*) message, ID_SIZE, ?rid_cs);
        assert chars((void*) message + ID_SIZE, NONCE_SIZE, ?s_nonce_cs);
        assert chars((void*) message + ID_SIZE + NONCE_SIZE, NONCE_SIZE, ?r_nonce_cs);        
        cs_to_ccs_append(rid_cs, s_nonce_cs);
        cs_to_ccs_append(append(rid_cs, s_nonce_cs), r_nonce_cs);

        chars_join(message);
        chars_join(message);
        public_chars(message, MSG2_SIZE);
        chars_to_secret_crypto_chars(message, MSG2_SIZE);
      }
      else
      {
        close nsl_pub_msg2(sender, receiver, s_nonce_cg, s_nonce_ccs, r_nonce_cg,
                           p_inst, p_orig, c_orig, condition);
      }
  @*/
  //@ close nsl_pub_msg_sender(receiver);
  //@ leak nsl_pub_msg_sender(receiver);
  //@ close nsl_pub(cg_enc);
  //@ leak nsl_pub(cg_enc);
  //@ public_cryptogram(encrypted, cg_enc);

  // Send the message
  net_send(socket, encrypted, size);
  zeroize(message, MSG2_SIZE);

  /*@ if (!condition)
        close cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg);
      else
        public_crypto_chars(s_nonce, NONCE_SIZE);
  @*/
  //@ close cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg);
  //@ close principal(receiver, _);
}
コード例 #8
0
void sender_msg1(int* socket, havege_state* havege_state, pk_context* r_context,
                 int sender, char* s_nonce)
  /*@ requires GENERAL_PRE(sender) &*&
               pk_context_with_key(r_context, pk_public,
                                   ?receiver, ?r_id, 8 * KEY_SIZE) &*&
               cryptogram(s_nonce, NONCE_SIZE, ?s_nonce_ccs, ?s_nonce_cg) &*&
                 s_nonce_cg == cg_nonce(sender, _) &*&
                 cg_info(s_nonce_cg) == int_pair(1, int_pair(receiver, r_id)); @*/
  /*@ ensures  GENERAL_POST(sender) &*&
               pk_context_with_key(r_context, pk_public,
                                   receiver, r_id, 8 * KEY_SIZE) &*&
               cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg); @*/
{
  //@ open principal(sender, _);
  unsigned int size;
  char message[MSG1_SIZE];
  char encrypted[KEY_SIZE];

  // Construct the message
  write_identifier(message, sender);
  //@ list<crypto_char> sid_ccs = cs_to_ccs(identifier(sender));
  //@ assert crypto_chars(normal, message, ID_SIZE, sid_ccs);
  //@ cs_to_ccs_crypto_chars(message, identifier(sender));
  //@ public_chars(message, ID_SIZE);
  //@ chars_to_secret_crypto_chars(message, ID_SIZE);

  //@ open cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg);
  memcpy((void*) message + ID_SIZE, s_nonce, NONCE_SIZE);
  //@ crypto_chars_join(message);
  //@ list<crypto_char> msg1 = append(sid_ccs, s_nonce_ccs);
  //@ assert crypto_chars(secret, message, MSG1_SIZE, msg1);

   // Encrypt the message
  /*@ produce_function_pointer_chunk random_function(random_stub_nsl)
                    (havege_state_initialized)(state, out, len) { call(); } @*/
  //@ close random_state_predicate(havege_state_initialized);
  if (pk_encrypt(r_context, message, MSG1_SIZE, encrypted, &size,
                  KEY_SIZE, random_stub_nsl, havege_state) != 0)
    abort();
  //@ assert u_integer(&size, ?size_val);
  //@ assert cryptogram(encrypted, size_val, ?cs_enc, ?cg_enc);

  // Proof the message is public
  //@ take_append(ID_SIZE, sid_ccs, s_nonce_ccs);
  //@ drop_append(ID_SIZE, sid_ccs, s_nonce_ccs);
  //@ close nsl_pub_msg_sender(sender);
  //@ leak nsl_pub_msg_sender(sender);
  /*@ if (col || bad(sender) || bad(receiver))
      {
        assert crypto_chars(secret, message, MSG1_SIZE, msg1);
        crypto_chars_split(message, ID_SIZE);
        public_crypto_chars(message, ID_SIZE);
        assert chars(message, ID_SIZE, ?sid_cs);
        cs_to_ccs_inj(sid_cs, identifier(sender));
        assert chars(message, ID_SIZE, identifier(sender));
        close nsl_pub(s_nonce_cg);
        leak nsl_pub(s_nonce_cg);

        close cryptogram((void*) message + ID_SIZE, NONCE_SIZE,
                          s_nonce_ccs, s_nonce_cg);
        public_cryptogram((void*) message + ID_SIZE, s_nonce_cg);
        assert chars((void*) message + ID_SIZE, NONCE_SIZE, ?s_nonce_cs');
        cs_to_ccs_append(identifier(sender), s_nonce_cs');
        chars_join(message);
        public_chars(message, MSG1_SIZE);
        chars_to_crypto_chars(message, MSG1_SIZE);
      }
      else
      {
        close nsl_pub_msg1(sender, receiver, s_nonce_cg);
      }
  @*/
  //@ close nsl_pub(cg_enc);
  //@ leak nsl_pub(cg_enc);
  //@ public_cryptogram(encrypted, cg_enc);

  // Send the message
  net_send(socket, encrypted, size);
  zeroize(message, MSG1_SIZE);
  //@ close cryptogram(s_nonce, NONCE_SIZE, s_nonce_ccs, s_nonce_cg);
  //@ close principal(sender, _);
}
コード例 #9
0
void sender_msg3(int* socket, havege_state* havege_state, pk_context* r_context,
                 int sender, char* r_nonce)
  /*@ requires GENERAL_PRE(sender) &*&
               pk_context_with_key(r_context, pk_public,
                                   ?recvr, ?r_id, 8 * KEY_SIZE) &*&
               SENDER_INTER; @*/
  /*@ ensures  GENERAL_POST(sender) &*&
               pk_context_with_key(r_context, pk_public,
                                   recvr, r_id, 8 * KEY_SIZE) &*&
               col || bad(sender) || bad(recvr) ?
                 chars(r_nonce, NONCE_SIZE, ?r_nonce_cs) &*&
                 r_nonce_ccs == cs_to_ccs(r_nonce_cs)
               :
                 cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg); @*/
{
  //@ open principal(sender, _);
  unsigned int size;
  char message[MSG3_SIZE];
  char encrypted[KEY_SIZE];

  // Construct the message
  //@ open sender_inter(r_nonce_ccs, r_nonce_cg);
  //@ bool condition = col || bad(sender) || bad(recvr);
  /*@ if (!condition)
        open cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg);
      else
      {
        crypto_chars_to_chars(r_nonce, NONCE_SIZE);
        public_chars(r_nonce, NONCE_SIZE);
        chars_to_secret_crypto_chars(r_nonce, NONCE_SIZE);
      }
  @*/
  memcpy((void*) message, r_nonce, NONCE_SIZE);
  /*@ if (!condition)
        close cryptogram(r_nonce, NONCE_SIZE, r_nonce_ccs, r_nonce_cg);
      else
        public_crypto_chars(r_nonce, NONCE_SIZE);
  @*/

  // Encrypt the message
  /*@ produce_function_pointer_chunk random_function(random_stub_nsl)
                    (havege_state_initialized)(state, out, len) { call(); } @*/
  //@ close random_state_predicate(havege_state_initialized);
  if (pk_encrypt(r_context, message, MSG3_SIZE, encrypted, &size,
                 KEY_SIZE, random_stub_nsl, havege_state) != 0)
    abort();
  //@ assert u_integer(&size, ?size_val);
  //@ assert cryptogram(encrypted, size_val, ?cs_enc, ?cg_enc);

  // Proof the message is public
  //@ close nsl_pub_msg_sender(sender);
  //@ leak nsl_pub_msg_sender(sender);
  //@ if (!condition) close nsl_pub_msg3(sender, recvr, r_nonce_cg);
  //@ close nsl_pub(cg_enc);
  //@ leak nsl_pub(cg_enc);
  //@ public_cryptogram(encrypted, cg_enc);

  // Send the message
  net_send(socket, encrypted, size);
  zeroize(message, MSG3_SIZE);
  //@ close principal(sender, _);
}
コード例 #10
0
ファイル: encrypt.c プロジェクト: Distrotech/gnupg
/*
 * Write pubkey-enc packets from the list of PKs to OUT.
 */
static int
write_pubkey_enc_from_list (PK_LIST pk_list, DEK *dek, iobuf_t out)
{
  PACKET pkt;
  PKT_public_key *pk;
  PKT_pubkey_enc  *enc;
  int rc;

  for ( ; pk_list; pk_list = pk_list->next )
    {
      gcry_mpi_t frame;

      pk = pk_list->pk;

      print_pubkey_algo_note ( pk->pubkey_algo );
      enc = xmalloc_clear ( sizeof *enc );
      enc->pubkey_algo = pk->pubkey_algo;
      keyid_from_pk( pk, enc->keyid );
      enc->throw_keyid = (opt.throw_keyids || (pk_list->flags&1));

      if (opt.throw_keyids && (PGP6 || PGP7 || PGP8))
        {
          log_info(_("you may not use %s while in %s mode\n"),
                   "--throw-keyids",compliance_option_string());
          compliance_failure();
        }

      /* Okay, what's going on: We have the session key somewhere in
       * the structure DEK and want to encode this session key in an
       * integer value of n bits. pubkey_nbits gives us the number of
       * bits we have to use.  We then encode the session key in some
       * way and we get it back in the big intger value FRAME.  Then
       * we use FRAME, the public key PK->PKEY and the algorithm
       * number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
       * returns the encrypted value in the array ENC->DATA.  This
       * array has a size which depends on the used algorithm (e.g. 2
       * for Elgamal).  We don't need frame anymore because we have
       * everything now in enc->data which is the passed to
       * build_packet().  */
      frame = encode_session_key (pk->pubkey_algo, dek,
                                  pubkey_nbits (pk->pubkey_algo, pk->pkey));
      rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk, pk->pkey);
      gcry_mpi_release (frame);
      if (rc)
        log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
      else
        {
          if ( opt.verbose )
            {
              char *ustr = get_user_id_string_native (enc->keyid);
              log_info (_("%s/%s encrypted for: \"%s\"\n"),
                        openpgp_pk_algo_name (enc->pubkey_algo),
                        openpgp_cipher_algo_name (dek->algo),
                        ustr );
              xfree (ustr);
	    }
          /* And write it. */
          init_packet (&pkt);
          pkt.pkttype = PKT_PUBKEY_ENC;
          pkt.pkt.pubkey_enc = enc;
          rc = build_packet (out, &pkt);
          if (rc)
            log_error ("build_packet(pubkey_enc) failed: %s\n",
                       gpg_strerror (rc));
	}
      free_pubkey_enc(enc);
      if (rc)
        return rc;
    }
  return 0;
}
コード例 #11
0
void attacker_send_asym_encrypted(havege_state *havege_state, void* socket)
  //@ requires attacker_invariant(?pub, ?pred, ?kc, havege_state, socket, ?attacker);
  //@ ensures  attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
{
  int temp;
  int size1;
  int size2;
  unsigned int osize;
  char buffer1[MAX_MESSAGE_SIZE];
  char buffer2[MAX_MESSAGE_SIZE];
  char buffer3[MAX_MESSAGE_SIZE];
  pk_context context;

  //@ open attacker_invariant(pub, pred, kc, havege_state, socket, attacker);

  size1 = net_recv(socket, buffer1, MAX_MESSAGE_SIZE);
  size2 = net_recv(socket, buffer2, MAX_MESSAGE_SIZE);
  if (size1 <= 0 || size2 < MINIMAL_STRING_SIZE)
  {
    //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
    return;
  }

  //@ close pk_context(&context);
  pk_init(&context);
  //@ interpret_public_key(buffer1, size1);
  //@ assert cryptogram(buffer1, size1, ?ccs1, ?cg_key);
  //@ assert cg_key == cg_public_key(?p, ?c);
  if (pk_parse_public_key(&context, buffer1, (unsigned int) size1) == 0)
  {
    if (size2 * 8 <= size1)
    {
      //@ close random_state_predicate(havege_state_initialized);
      /*@ produce_function_pointer_chunk random_function(
                    attacker_key_item_havege_random_stub)
                  (havege_state_initialized)(state, out, len) { call(); } @*/
      //@ chars_to_crypto_chars(buffer2, size2);
      if (pk_encrypt(&context, buffer2, (unsigned int) size2,
                    buffer3, &osize, MAX_MESSAGE_SIZE,
                    attacker_key_item_havege_random_stub, havege_state) == 0)
      {
        //@ assert u_integer(&osize, ?osize_val);
        /*@
          {
            assert cryptogram(buffer3, osize_val, ?ccs_enc, ?cg_enc);
            assert cg_enc == cg_asym_encrypted(p, c, ?cs2, _);
            assert is_public_asym_encryption_is_public(?proof, pub, pred);
            crypto_chars_to_chars(buffer2, size2);
            public_chars(buffer2, size2);
            proof(cg_enc);
            assert [_]pub(cg_enc);
            public_cryptogram(buffer3, cg_enc);
            chars_to_crypto_chars(buffer2, size2);
          }
        @*/
        net_send(socket, buffer3, osize);
      }
      //@ crypto_chars_to_chars(buffer2, size2);
    }
    //@ pk_release_context_with_key(&context);
  }
  pk_free(&context);
  //@ open pk_context(&context);
  //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
  //@ public_cryptogram(buffer1, cg_key);
}
コード例 #12
0
ファイル: pk_encrypt.c プロジェクト: ariia-git/console-client
int main( int argc, char *argv[] )
{
    FILE *f;
    int ret;
    size_t i, olen = 0;
    pk_context pk;
    entropy_context entropy;
    ctr_drbg_context ctr_drbg;
    unsigned char input[1024];
    unsigned char buf[512];
    const char *pers = "pk_encrypt";

    ret = 1;

    if( argc != 3 )
    {
        polarssl_printf( "usage: pk_encrypt <key_file> <string of max 100 characters>\n" );

#if defined(_WIN32)
        polarssl_printf( "\n" );
#endif

        goto exit;
    }

    polarssl_printf( "\n  . Seeding the random number generator..." );
    fflush( stdout );

    entropy_init( &entropy );
    if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
                               (const unsigned char *) pers,
                               strlen( pers ) ) ) != 0 )
    {
        polarssl_printf( " failed\n  ! ctr_drbg_init returned -0x%04x\n", -ret );
        goto exit;
    }

    polarssl_printf( "\n  . Reading public key from '%s'", argv[1] );
    fflush( stdout );

    pk_init( &pk );

    if( ( ret = pk_parse_public_keyfile( &pk, argv[1] ) ) != 0 )
    {
        polarssl_printf( " failed\n  ! pk_parse_public_keyfile returned -0x%04x\n", -ret );
        goto exit;
    }

    if( strlen( argv[2] ) > 100 )
    {
        polarssl_printf( " Input data larger than 100 characters.\n\n" );
        goto exit;
    }

    memcpy( input, argv[2], strlen( argv[2] ) );

    /*
     * Calculate the RSA encryption of the hash.
     */
    polarssl_printf( "\n  . Generating the encrypted value" );
    fflush( stdout );

    if( ( ret = pk_encrypt( &pk, input, strlen( argv[2] ),
                            buf, &olen, sizeof(buf),
                            ctr_drbg_random, &ctr_drbg ) ) != 0 )
    {
        polarssl_printf( " failed\n  ! pk_encrypt returned -0x%04x\n", -ret );
        goto exit;
    }

    /*
     * Write the signature into result-enc.txt
     */
    if( ( f = fopen( "result-enc.txt", "wb+" ) ) == NULL )
    {
        ret = 1;
        polarssl_printf( " failed\n  ! Could not create %s\n\n", "result-enc.txt" );
        goto exit;
    }

    for( i = 0; i < olen; i++ )
        polarssl_fprintf( f, "%02X%s", buf[i],
                 ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

    fclose( f );

    polarssl_printf( "\n  . Done (created \"%s\")\n\n", "result-enc.txt" );

exit:
    ctr_drbg_free( &ctr_drbg );
    entropy_free( &entropy );

#if defined(POLARSSL_ERROR_C)
    polarssl_strerror( ret, (char *) buf, sizeof(buf) );
    polarssl_printf( "  !  Last error was: %s\n", buf );
#endif

#if defined(_WIN32)
    polarssl_printf( "  + Press Enter to exit this program.\n" );
    fflush( stdout ); getchar();
#endif

    return( ret );
}