ChatGPT Generate Phishing Mail And Describe Image With .NetCore Microservice

Bora Kaşmer
9 min readJun 11, 2024

--

Atomic Heart’s Annihilation Instinct DLC

Hi,

Today we will talk about how to generate phishing mail and describe any image with ChatGPT 4.0 Turbo.

Firstly, we will create an ASP.NET Core Web API application on Visual Studio 2022. And don’t forget to select .NET 8.0 for the .Net version.

I checked official Open AI .Net Libraries from here. I preferred Betalgo libraries.

Our Creating Phishing mail content takes time. So I prefer using RabbitMQ and listen a channel with Microservice.

This is our RabbitMQ Interface. And we will send mail to RabbitMQ Cannel.

“Success in creating AI would be the biggest event in human history. Unfortunately, it might also be the last, unless we learn how to avoid the risks.”

— Stephen Hawking

IRabbitMQClient.cs:

    public interface IRabbitMQClient
{
public bool PostPhisihnigmail(string channelName, ChatGPTImageContentModel prompt);
}

RabbitMQClient.cs:We will get Phishing mail content and push it to the specific channel.

using RabbitMQ.Client;
using System.Text.Json;

namespace ChatGPTService
{
public class RabbitMQClient : IRabbitMQClient
{
public bool PostPhisihnigmail(string channelName, ChatGPTImageContentModel prompt)
{
try
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(channelName, false, false, false, null);

var tempData = JsonSerializer.Serialize(prompt);
var data = System.Text.Encoding.UTF8.GetBytes(tempData);

channel.BasicPublish("", channelName, null, data);
return true;
}
}
catch (Exception ex) { return false; }
}
}
}

ChatGPTController.cs: We will write two endpoints. One of them is “PostPhishingMail”. We will send a prompt to Queue for creating Phishing mail to the ChatGPT.

namespace ChatGPTService.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class ChatGPTController : ControllerBase
{
public IRabbitMQClient _rabbitmQClient;
public ChatGPTController(IRabbitMQClient rabbitmQClient)
{
_rabbitmQClient = rabbitmQClient;
}

[HttpPost(Name = "PostPhishingMail")]
public bool Post(string? channelName = "PhishingMail", string? prompt = "Write an email to Bora Kasmer offering the recipient a chance to win a $50\r\nAmazon gift card when they click a link to complete an employee satisfaction survey. Let the connection path be https://borakasmer.com?id=5. Create a beautifully formatted output using HTML and CSS.")
{
ChatGPTImageContentModel data = new() { Image = null, Prompt = prompt };
return _rabbitmQClient.PostPhisihnigmail(channelName, data);
}

“Intelligence is the ability to adapt to change.”

— Stephen Hawking

The second one is “PostImageReport”. We will send an image to the queue(RabbitMQ) to ask ChatGPT to explain it to us in detail.

 [HttpPost(Name = "PostImageReport")]
public bool PostImageReport(IFormFile file, string? channelName = "PhishingImageMail", string? prompt = "What is in detail in the picture?")
{
try
{
if (file != null)
{
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
byte[] image = memoryStream.ToArray();
ChatGPTImageContentModel data = new() { Image = image, Prompt = prompt };
return _rabbitmQClient.PostPhisihnigmail(channelName, data);
}
}
return true;
}
catch (Exception ex)
{
return false;
}
return true;
}

ChatGPTImageContentModel:

namespace ChatGPTService
{
public class ChatGPTImageContentModel
{
public string Prompt { get; set; }
public byte[] Image { get; set; }
}
}

This is the Swagger Document of two WebApi’s.

Program.cs:

using ChatGPTService;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSingleton<IRabbitMQClient, RabbitMQClient>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

“AI is neither good nor evil. It’s a tool. It’s a technology for us to use.”

— 0ren Etzioni

Now Let’s Create The Microservice For Asking All Questions To The ChatGPT

We will create .NET 8.0 Console Application. “ChatGPTMicroservice”

We will listen to specific channels of RabbitMQ. And we will run different scenarios for each different channel type.

RabbitMQClient.cs: EventingBasicConsumer is listening to channelName which is given as a parameter. The “QueueExists()” method is used to determine whether the consuming channel exists or not. If not exist, we won’t throw an exception.

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatGPTMicroservice
{
public class RabbitMQClient : IDisposable
{
public void Dispose()
{
//throw new NotImplementedException();
}
public EventingBasicConsumer GetConsumer(string channelName)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
//Check is RabbitMQ Channel Exists
if (QueueExists(channel, channelName))
{

var consumer = new EventingBasicConsumer(channel);
channel.BasicConsume(channelName, true, consumer);

return consumer;
}
else
{
return null;
}
}

private bool QueueExists(IModel channel, string channelName)
{
try
{
// Passive declare to check if the queue exists
channel.QueueDeclarePassive(channelName);
return true;
}
catch (OperationInterruptedException ex)
{
// If the queue does not exist, an OperationInterruptedException will be thrown
if (ex.ShutdownReason.ReplyCode == 404)
{
return false;
}

// Re-throw the exception if it's not a 404 error
throw;
}
}
}
}

I prefer to use the Betalgo .Net Library for OpenAI. You can find all supported OpenAI libraries list from here.

Program.cs (Consumer):

We will listen to two channels. “PhishingMail” and “PhishingImageMail”. Which channel is consumed, its method will be called.

  • PhishingMail”: We will write a phishing e-mail to ChatGPT
  • PhishingImageMail”: We will annotate an image to ChatGPT.
using ChatGPTMicroservice;
using System.Text.Json;

using (RabbitMQClient rabbitMQClient = new())
using (ChatGPTClient chatGPTClient = new())
{

//Prompt for ChatGPT
var consumer = rabbitMQClient.GetConsumer("PhishingMail");
if (consumer != null)
{
consumer.Received += (model, ea) =>
{
var tempData = ea.Body.ToArray();
var data = System.Text.Encoding.UTF8.GetString(tempData);

var chatImageModel = JsonSerializer.Deserialize<ChatGPTImageContentModel>(data);
var phishingMail = chatGPTClient.GetPhishingMail(chatImageModel.Prompt);
Console.WriteLine(phishingMail);
};
}
//Image for ChatGPT
var consumer2 = rabbitMQClient.GetConsumer("PhishingImageMail");
if (consumer2 != null)
{
consumer2.Received += (model, ea) =>
{
var tempData = ea.Body.ToArray();
var data = System.Text.Encoding.UTF8.GetString(tempData);

var chatImageModel = JsonSerializer.Deserialize<ChatGPTImageContentModel>(data);
var phishingMail = chatGPTClient.GetPhishingImageMail(chatImageModel);
Console.WriteLine(phishingMail);
};
}
Console.WriteLine("press any key to Exit");
Console.ReadLine();
}

ChatGPTClient (PhishingMail):

1-) GetPhisingMail is used to generate Phishing Email Content. We will set OpenAI ApiKey and use the “ChatCompletion.CreateCompletion” service. With this service, we can use the latest Gpt_4_turbo model.

2-) We will set the Message property with a List of ChatMessage. These three kind of roles for chat message

  • System”: We tell ChatGPT which role it should play. The aim here is to enable the chatbot to provide faster answers by defining a more accurate and specific area.
  • User”: It is the client role that we asked the question about.
  • Assistant”: This is the role where the questions asked by the chatbot are written so that it can give us better answers. Exp: ChatMessage.FromAssistant(“I am a helpful assistant.”)

In this way, the most accurate result can be achieved by defining the relevant roles in this conversation.

3-) Other properties are also assigned depending on the purpose.

  • Model”: We will use the lateset Get_4_turbo model.
  • MaxTokens”: All words mean money. It would be logical to limit the answer given to a certain word.
  • FrequencyPenalty”: The number between 2.0 and 2.0. Positive values ​​penalize new tokens based on their current frequency in the text so far, making it less likely that the model will repeat the same line verbatim.
  • Temperature”: Which sampling temperature to use between 0 and 2. Higher values, such as 0.8, make the output more random, while lower values, such as 0.2, make it more focused and deterministic. We usually recommend changing either this or top_p, but not both.
  • PresencePenalty”: The number between -2.0 and 2.0. Positive values ​​penalize new tokens based on whether they have already appeared in the text and increase the likelihood that the model will talk about new topics.

4-) Finally we will return the ChatGPT result.

“Software is eating the world, but AI is going to eat software. “

— Jensen Huang

ChatGPTClient.cs:

using OpenAI;
using OpenAI.Managers;
using OpenAI.ObjectModels;
using OpenAI.ObjectModels.RequestModels;
using static OpenAI.ObjectModels.StaticValues;

//https://github.com/betalgo/openai
namespace ChatGPTMicroservice
{
public class ChatGPTClient : IDisposable
{
public void Dispose()
{
//throw new NotImplementedException();
}

public string GetPhishingMail(string prompt)
{
var openAiService = new OpenAIService(new OpenAiOptions()
{
ApiKey = "Your-ApiKey"
});

var completionResult = openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest()
{
Messages = new List<ChatMessage>
{
ChatMessage.FromSystem("You are a helpful assistant."),
ChatMessage.FromUser(prompt),
},

Model = Models.Gpt_4_turbo,
MaxTokens = 2000,
FrequencyPenalty = 0,
Temperature = (float?)0.7,
PresencePenalty = 0,
});

if (completionResult.Result.Successful)
{
return completionResult.Result.Choices.FirstOrDefault().Message.Content;
}
else
{
if (completionResult.Result.Error == null)
{
throw new Exception("Unknown Error");
}
return $"{completionResult.Result.Error.Code}: {completionResult.Result.Error.Message}";
}
}
}
}

Result:

Write an email to Bora Kasmer offering the recipient a chance to win a $50\r\nAmazon gift card when they click a link to complete an employee satisfaction survey. Let the connection path be https://borakasmer.com?id=5. Create a beautifully formatted output using HTML and CSS.

This Mail Created By ChatGPT OpenAI

ChatGPTClient (PhishingImageMail):

1-)GetPhisingImageMail is used to declare Imag Content. We will set OpenAI ApiKey and use the “ChatCompletion.CreateCompletion” service. We will get a binary image from the Image property of ChatGPTImageContentModel class with this service, we can use the latest Gpt_4_turbo model.

2-) We will set the Message property with a List of ChatMessage. There are three kinds of roles for chat message.

  • System”: We tell ChatGPT which role it should play. The aim here is to enable ChatGPT to provide faster answers by defining a more accurate and specific area.
  • User”: It is the client role that we asked the question about. We will declare a List of MessageContent.
  • “MessageContent.TextContent(chatImageModel.Prompt)”: We will set the client question to the TextContent.
  • “MessageContent.ImageBinaryContent”: We will add ImageBinaryContent, which we will ask to describe to the ChatGPT. We can also use ImageURL instead of BinaryImage. I gave an example as seen below.
     MessageContent.ImageUrlContent(
"http://www.borakasmer.com/wp-content/uploads/2019/09/profile.jpg",
ImageStatics.ImageDetailTypes.High)
  • “binaryImage, ImageStatics.ImageFileTypes.Png, ImageStatics.ImageDetailTypes.High)” : We will add binaryImage, its extension, and detail type as a parameter.

3-) We will set other properties as above exampleModel, ModelTokens, FrequencyPenalty, Temperature, PresencePenalty.

4-) Finally we will return the ChatGPT result. Declaration of the giving picture.

 public string GetPhishingImageMail(ChatGPTImageContentModel chatImageModel)
{
var openAiService = new OpenAIService(new OpenAiOptions()
{
ApiKey = "Your-ApiKey"
});

var binaryImage = chatImageModel.Image;

var completionResult = openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest()
{
Messages = new List<ChatMessage>
{
ChatMessage.FromSystem("You are a helpful assistant."),

ChatMessage.FromUser(
new List<MessageContent>
{
//MessageContent.TextContent("What is on the picture in details?"),
MessageContent.TextContent(chatImageModel.Prompt),
MessageContent.ImageBinaryContent(
binaryImage,
ImageStatics.ImageFileTypes.Png,
ImageStatics.ImageDetailTypes.High)
}),
},
Model = Models.Gpt_4_turbo,
MaxTokens = 500,
FrequencyPenalty = 0,
Temperature = (float?)0.7,
PresencePenalty = 0,
});

if (completionResult.Result.Successful)
{
return completionResult.Result.Choices.FirstOrDefault().Message.Content;
}
else
{
if (completionResult.Result.Error == null)
{
throw new Exception("Unknown Error");
}
return $"{completionResult.Result.Error.Code}: {completionResult.Result.Error.Message}";
}
}

Result:

What is in detail in the picture?

ChatGPT Answer

“The thing that’s going to make artificial intelligence so powerful is its ability to learn, and the way AI learns is to look at human culture.”

— Dan Brown

Conclusion:

In this article, I wanted to show how we can use ChatGPT in professional life. With the image upload feature, monthly Web Report pages can be snapshotted and interpreted in ChatGPT, and e-mails can be sent to subscribers monthly by printing the Subject and body in ChatGPT with HangFire.

Monthly Report
Swagger Request Explain Report Image To The ChatGPT

Result:

Can you explain this monthly blanco?

ChatGPT Answer

“I definitely fall into the camp of thinking of AI as augmenting human capability and capacity.”

— Satya Nadella

I don’t think ChatGPT will be able to replace us developers anytime soon. But by using it as a tool, we can do more and more accurate work in a short time with less effort.

Good Bye!

See you until the next article.

“If you have read so far, first of all, thank you for your patience and support. I welcome all of you to my blog for more!”

Source Code [Github]:

--

--

Bora Kaşmer

I have been coding since 1993. I am computer and civil engineer. Microsoft MVP. Software Architect(Cyber Security). https://www.linkedin.com/in/borakasmer/