Guia rápido de conversão e criação de certificados

Esse é um guia rápido de referência para a conversão de certificados e a criação de certificados. Todos os comandos para a conversão ou a criação foram feitos no shell do Linux, a distro que usei foi o Gentoo.

Gerar uma chave RSA(RSA Key) 

Chave de 1024 bits

openssl genrsa -out  chave_privada.key 1024

Chave de 2048 bits

openssl genrsa -out chave_privada.key 2048

Gerando um CSR (Certificate Signing Request) a partir de uma RSA Key

openssl req -new -key chave_privada.key -out req_cert.csr

Converter .CER para .CRT

openssl x509 -inform DER -in cert.cer -out cert.crt

 Gerando um certificado auto assinado
Você pode usar internamente esse tipo de certificado para validar seus sites rodando localmente.

openssl x509 -req -in req_cert.csr -signkey chave_privada.key -out meu_certificado.crt

O conteúdo desse post é baseado nas minhas experiências implicando diretamente na quantidade de conteúdo escrito aqui, ou seja conforme for encontrando a necessidade de aprender algo novo sobre OpenSSL, certificados, chaves RSA vou postando aqui.

Referencia:
http://www.openssl.org/docs/apps/genrsa.html
http://www.openssl.org/docs/apps/req.html
http://www.akadia.com/services/ssh_test_certificate.html 

 


Comentários

7 respostas para “Guia rápido de conversão e criação de certificados”

  1. Avatar de RSimom
    RSimom

    Tiago, como faço caso eu queira gerar um certificado com AES 256???

    1. Opa!

      Basta adiciona o parametro -aes256 quando for criar a sua chave

      [pre]openssl genrsa -aes256 -out chave_privada.key 1024[/pre]

      Abraço,

  2. Avatar de Igor rocha
    Igor rocha

    Muito obrigado, me ajudou bastante..

    abraço..

  3. Muito obrigado pelo post! Foi muito útil!
    Precisava converter os certificados v1, v2 e v3 da Receita Federal (CER) para CRT para importá-los ao Firefox.

    Desenvolvi um script em VBScript que converte arquivos CER para CRT.
    Ele possui uma caixa de diálogo que permite selecionarmos o certificado para conversão. É necessário possuir o GetGnuWin32 instalado em %ProgramFiles% (%ProgramFiles(x86)% no Windows x64).
    Para quem se interessar:

    openssl-cer-para-crt.wsf

    Set oShell = CreateObject("WScript.Shell")
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    Dim PROCESSOR_ARCHITECTURE : PROCESSOR_ARCHITECTURE = oShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
    Dim ProgramFiles : ProgramFiles = oShell.ExpandEnvironmentStrings("%ProgramFiles%")

    If PROCESSOR_ARCHITECTURE = "AMD64" Then
    ProgramFiles = oShell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
    End If

    Dim Dlg, s
    Set Dlg = new Dialogs

    '-- To provide for 1 or more file type filters just put the name followed by one or more file
    '-- extensions. The class with construct the filter as long as the paramter is formatted
    '-- like this comma-delimited sample: type, extension, type, extension, type, extension
    '-- ....etc. There can be any number of filters. Use "All Files, *" to also have a general filter
    '-- option that shows all files. If more than 1 extension applies to a file type, separate each
    '-- with a space, as done here with the "HTML Files" type.

    s = Dlg.FileOpenDlg("Selecionar arquivo contendo os certificados de CA a converter", "", "Arquivos de certificados , cer")

    'MsgBox s
    'MsgBox Quotes(ProgramFiles & "\GetGnuWin32\bin\openssl.exe") & " x509 -in " & Quotes(s) & " -out " & Quotes(Mid(s, 1, Len(s) - 4) & ".crt")

    oShell.Run Quotes(ProgramFiles & "\GetGnuWin32\bin\openssl.exe") & " x509 -in " & Quotes(s) & " -out " & Quotes(Mid(s, 1, Len(s) - 4) & ".crt"), 0, True

    If Not oFSO.FileExists(Mid(s, 1, Len(s) - 4) & ".crt") Then
    oShell.Run Quotes(ProgramFiles & "\GetGnuWin32\bin\openssl.exe") & " x509 -inform DER -print_certs -in " & Quotes(s) & " -out " & Quotes(Mid(s, 1, Len(s) - 4) & ".cer"), 0, True
    End If

    Set Dlg = Nothing

    Function Quotes(strString)
    Quotes = Chr(34) & strString & Chr(34)
    End Function

    Dependência para que o Diálogo possa funcionar. Salve no mesmo local do script anterior.
    HtmlDlgHelp.vbs

    'Dim Dlg, s
    'Set Dlg = new Dialogs

    '-- To provide for 1 or more file type filters just put the name followed by one or more file
    '-- extensions. The class with construct the filter as long as the paramter is formatted
    '-- like this comma-delimited sample: type, extension, type, extension, type, extension
    '-- ....etc. There can be any number of filters. Use "All Files, *" to also have a general filter
    '-- option that shows all files. If more than 1 extension applies to a file type, separate each
    '-- with a space, as done here with the "HTML Files" type.

    's = Dlg.FileOpenDlg("Choose File", "", "Text Files, txt, Log Files, log, HTML Files, htm html php asp hta")

    'MsgBox s

    'Set Dlg = Nothing

    '-------------------------------------- Dialogs Class -------------------------------------------------
    '-- This is touchy code. If not written just so there will be long lags before a dialog is shown.
    '-- If HTAs are not closed at the right time they'll keep running, resulting in a new HTA left running for each call.
    '-- If the same HTA is used for the life of the class it will fail on the 2nd or 3rd call. The whole operation to
    '-- create an HTA, initialize the control, and then clean up, must be done for every call.
    '-- savefiledlg doesn't seem to work, at least on XP. It shows an openfiledlg dialog instead and then errors when the selected file doesn't exist.

    Class Dialogs
    Private Cls_Dlg, Cls_HTA, Cls_IE2

    Public Function FileOpenDlg(Title, StartDir, sFilter) '-- openfiledlg([initFile as Variant][, initDir as Variant][, Filter as Variant][, Title as Variant])
    Dim Cls_Filter, Boo1, i2_c
    On Error Resume Next
    Boo1 = InitDlg()
    If Boo1 = False Then
    CleanUp
    Boo1 = InitDlg() '-- sometimes the first init fails. ?? Reason unknown.
    End If
    If Boo1 = False Then Err.Raise 1, "Dialogs Class", "Failed to initialize HtmlDlgHelper object": Exit Function

    If Len(sFilter) > 0 Then
    Cls_Filter = GetFilterString(sFilter)
    FileOpenDlg = Cls_Dlg.openfiledlg(, CStr(StartDir), CStr(Cls_Filter), CStr(Title))
    Else
    FileOpenDlg = Cls_Dlg.openfiledlg(, CStr(StartDir), CStr("All Files(*.*)|*.*|"), CStr(Title))
    End If

    If Len(FileOpenDlg) = 0 Then Exit Function

    '--strange HTMLDlgHelper behavior. Returns a string ending with nulls.
    '-- The nulls won't affect using the string, but they will matter if you test the string.
    '-- For instance: If UCase(Right(s, 3)) = "TXT" Then .... That won't work unless the nulls are snipped.
    '-- so check for nulls. If first null is first character that will return "". Otherwise there's a path string to
    '-- extract from the string buffer.
    i2_c = InStr(FileOpenDlg, Chr(0))
    If i2_c > 1 Then FileOpenDlg = Left(FileOpenDlg, (i2_c - 1))

    CleanUp
    End Function

    Private Function GetFilterString(sFilter)
    Dim A1, i2, s1
    On Error Resume Next
    A1 = Split(sFilter, ",")
    i2 = 0
    Do While i2 < UBound(A1)
    GetFilterString = GetFilterString & Trim(A1(i2))
    s1 = Trim(A1(i2 + 1))
    s1 = "*." & s1
    s1 = Replace(s1, " ", ";*.")
    GetFilterString = GetFilterString & "(" & s1 & ")|" & s1 & "|"
    i2 = i2 + 2
    Loop
    End Function

    Private Function InitDlg()
    Dim Cls_iCount, Cls_IE, Cls_SHAp
    '-- ugly hack required to get around problem of HTMLDlgHelper.HTMLDlgHelper being a control that needs to be sited.
    '-- it's also not marked as safe for scripting. This method dynamically creates an HTA, then gets the window.
    InitDlg = False
    CreateObject("WSCript.Shell").Run "MSHTA.EXE ""javascript:new ActiveXObject('InternetExplorer.Application').PutProperty('ID1', window);""", 0, False

    '-- Next step: go through open windows and retrieve the window object for just-created HTA.
    Set Cls_SHAp = CreateObject("Shell.Application")
    On Error Resume Next
    Cls_iCount = 1
    Do Until Cls_iCount = 10
    For Each Cls_IE In Cls_SHAp.Windows
    If IsObject(Cls_IE.GetProperty("ID1")) Then
    Set Cls_IE2 = Cls_IE
    Exit Do
    End If
    Next
    WScript.sleep 100
    Cls_iCount = Cls_iCount + 1
    Loop
    Set Cls_SHAp = Nothing '-- done with Shell.Application.
    If Not IsObject(Cls_IE2) Then Exit Function

    Set Cls_HTA = Cls_IE2.GetProperty("ID1") '-- Cls_HTA is now an HTMLWindow2 object.
    '-- instantiate the HTMLDlgHelper.HTMLDlgHelper control.
    Cls_HTA.document.body.innerHTML = " "
    Set Cls_Dlg = Cls_HTA.Dlg.Object '-- get a reference to the control.
    Cls_IE2.quit '-- this seems to be necessary, but if done elsewhere it may cause an odd lag of 4-5 seconds.

    If IsObject(Cls_Dlg) Then InitDlg = True
    End Function

    Private Sub CleanUp()
    On Error Resume Next
    Set Cls_Dlg = Nothing
    If IsObject(Cls_HTA) Then
    Cls_HTA.Close
    Set Cls_HTA = Nothing
    End If
    If IsObject(Cls_IE2) Then
    Cls_IE2.quit
    Set Cls_IE2 = Nothing
    End If
    End Sub

    '-- this shouldn't be necessary because each HTA is closed after a call is made.
    Private Sub Class_Terminate()
    CleanUp
    End Sub

    End Class

  4. Há um no primeiro script. Esqueci a parte da importação da dependência.
    Adicione ao topo do script:

    E ao final:

  5. Erro do WordPress. Não postou meu último comentário corretamente.

    Há um no primeiro script. Esqueci a parte da importação da dependência.
    Adicione ao topo do script:


    <job id="Install-Firefox">
    <script language="VBScript" src="HtmlDlgHelp.vbs"/>
    <script language="VBScript">

    E ao final:


    </script>
    </job>

  6. Avatar de Ricardo Almeida
    Ricardo Almeida

    Muito bem didático vlewww pela ajuda.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.