Generating an RSA key pair in powershell The Next CEO of Stack OverflowWhat is the difference between encrypting and signing in asymmetric encryption?Determine installed PowerShell versionPowerShell says “execution of scripts is disabled on this system.”Encrypt and Decrypt text with RSA in PHPRSA: how to generate RSA public and private keys based on a passphrase (.net)Extract public/private key from PKCS12 file for later use in SSH-PK-AuthenticationHow do I find my RSA key fingerprint?Generate RSA key pair in javascript, based on a passwordRSA Key pair Exception on importing the private keyC# RSA encryption/decryption with transmission

Why does standard notation not preserve intervals (visually)

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

How long to clear the 'suck zone' of a turbofan after start is initiated?

Can I equip Skullclamp on a creature I am sacrificing?

Opposite of a diet

How to safely derail a train during transit?

Implement the Thanos sorting algorithm

How easy is it to start Magic from scratch?

MAZDA 3 2006 (UK) - poor acceleration then takes off at 3250 revs

Why does C# sound extremely flat when saxophone is tuned to G?

Rotate a column

What's the point of interval inversion?

Why didn't Khan get resurrected in the Genesis Explosion?

Why do remote companies require working in the US?

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Can the Reverse Gravity spell affect the Meteor Swarm spell?

Does it take more energy to get to Venus or to Mars?

How to make a variable always equal to the result of some calculations?

Why is there a PLL in CPU?

What makes a siege story/plot interesting?

Anatomically Correct Strange Women In Ponds Distributing Swords

Why did we only see the N-1 starfighters in one film?

Why do professional authors make "consistency" mistakes? And how to avoid them?



Generating an RSA key pair in powershell



The Next CEO of Stack OverflowWhat is the difference between encrypting and signing in asymmetric encryption?Determine installed PowerShell versionPowerShell says “execution of scripts is disabled on this system.”Encrypt and Decrypt text with RSA in PHPRSA: how to generate RSA public and private keys based on a passphrase (.net)Extract public/private key from PKCS12 file for later use in SSH-PK-AuthenticationHow do I find my RSA key fingerprint?Generate RSA key pair in javascript, based on a passwordRSA Key pair Exception on importing the private keyC# RSA encryption/decryption with transmission










2















I want to generate an RSA public private key pair in powershell without using external software and I want to test it. It should be able to encrypt/decrypt data on any online public/private key verification service.



Purpose- Strictly Educational. I'm very well aware that you shouldn't export your private key online for security purposes.



So far I've tried
ssh-keygen and



$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)
[System.Convert]::ToBase64String($rsa.ExportCspBlob(1))
[System.Convert]::ToBase64String($rsa.ExportCspBlob(0))


System.Security.Cryptography.RSACryptoServiceProvider creates P, Q etc. all the raw material for calculating public/private key, but I don't want the raw material.



ExportCspBlob(x) provides a key, but when I try to verify it online, the key pair verification fails.



So, is there any way to create RSA public private key pair in powershell without using any external programs, which can be directly copy-pasted into a certificate format(the one with -----BEGIN PRIVATE KEY---- stuff)?










share|improve this question






















  • do you need these keys for SSH?

    – Mike Twc
    Mar 21 at 17:06











  • @MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

    – Jaspal Singh
    Mar 22 at 1:54
















2















I want to generate an RSA public private key pair in powershell without using external software and I want to test it. It should be able to encrypt/decrypt data on any online public/private key verification service.



Purpose- Strictly Educational. I'm very well aware that you shouldn't export your private key online for security purposes.



So far I've tried
ssh-keygen and



$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)
[System.Convert]::ToBase64String($rsa.ExportCspBlob(1))
[System.Convert]::ToBase64String($rsa.ExportCspBlob(0))


System.Security.Cryptography.RSACryptoServiceProvider creates P, Q etc. all the raw material for calculating public/private key, but I don't want the raw material.



ExportCspBlob(x) provides a key, but when I try to verify it online, the key pair verification fails.



So, is there any way to create RSA public private key pair in powershell without using any external programs, which can be directly copy-pasted into a certificate format(the one with -----BEGIN PRIVATE KEY---- stuff)?










share|improve this question






















  • do you need these keys for SSH?

    – Mike Twc
    Mar 21 at 17:06











  • @MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

    – Jaspal Singh
    Mar 22 at 1:54














2












2








2








I want to generate an RSA public private key pair in powershell without using external software and I want to test it. It should be able to encrypt/decrypt data on any online public/private key verification service.



Purpose- Strictly Educational. I'm very well aware that you shouldn't export your private key online for security purposes.



So far I've tried
ssh-keygen and



$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)
[System.Convert]::ToBase64String($rsa.ExportCspBlob(1))
[System.Convert]::ToBase64String($rsa.ExportCspBlob(0))


System.Security.Cryptography.RSACryptoServiceProvider creates P, Q etc. all the raw material for calculating public/private key, but I don't want the raw material.



ExportCspBlob(x) provides a key, but when I try to verify it online, the key pair verification fails.



So, is there any way to create RSA public private key pair in powershell without using any external programs, which can be directly copy-pasted into a certificate format(the one with -----BEGIN PRIVATE KEY---- stuff)?










share|improve this question














I want to generate an RSA public private key pair in powershell without using external software and I want to test it. It should be able to encrypt/decrypt data on any online public/private key verification service.



Purpose- Strictly Educational. I'm very well aware that you shouldn't export your private key online for security purposes.



So far I've tried
ssh-keygen and



$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)
[System.Convert]::ToBase64String($rsa.ExportCspBlob(1))
[System.Convert]::ToBase64String($rsa.ExportCspBlob(0))


System.Security.Cryptography.RSACryptoServiceProvider creates P, Q etc. all the raw material for calculating public/private key, but I don't want the raw material.



ExportCspBlob(x) provides a key, but when I try to verify it online, the key pair verification fails.



So, is there any way to create RSA public private key pair in powershell without using any external programs, which can be directly copy-pasted into a certificate format(the one with -----BEGIN PRIVATE KEY---- stuff)?







windows powershell command-line certificate rsa






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 21 at 15:57









Jaspal SinghJaspal Singh

113




113












  • do you need these keys for SSH?

    – Mike Twc
    Mar 21 at 17:06











  • @MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

    – Jaspal Singh
    Mar 22 at 1:54


















  • do you need these keys for SSH?

    – Mike Twc
    Mar 21 at 17:06











  • @MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

    – Jaspal Singh
    Mar 22 at 1:54

















do you need these keys for SSH?

– Mike Twc
Mar 21 at 17:06





do you need these keys for SSH?

– Mike Twc
Mar 21 at 17:06













@MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

– Jaspal Singh
Mar 22 at 1:54






@MikeTwc no, as I said, educational purpose. So, I just want to create a key pair, and test it by encrypting and decrypting a string.

– Jaspal Singh
Mar 22 at 1:54













1 Answer
1






active

oldest

votes


















1














If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below



$store = "cert:CurrentUserMy"

$params = @
CertStoreLocation = $store
Subject = "CN=Test1"
KeyLength = 2048
KeyAlgorithm = "RSA"
KeyUsage = "DataEncipherment"
Type = "DocumentEncryptionCert"


# generate new certificate and add it to certificate store
$cert = New-SelfSignedCertificate @params


# list all certs
# Get-ChildItem -path $store

# Encryption / Decryption

$message = "My secret message"

$cipher = $message | Protect-CmsMessage -To "CN=Test1"
Write-Host "Cipher:" -ForegroundColor Green
$cipher

Write-Host "Decrypted message:" -ForegroundColor Green
$cipher | Unprotect-CmsMessage


# Exporting/Importing certificate

$pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
$privateKey = "$homeDocumentsTest1.pfx"
$publicKey = "$homeDocumentsTest1.cer"

# Export private key as PFX certificate, to use those Keys on different machine/user
Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

# Export Public key, to share with other users
Export-Certificate -FilePath $publicKey -Cert $cert

#Remove certificate from store
$cert | Remove-Item

# Add them back:
# Add private key on your machine
Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

# This is for other users (so they can send you encrypted messages)
Import-Certificate -FilePath $publicKey -CertStoreLocation $store





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55284511%2fgenerating-an-rsa-key-pair-in-powershell%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below



    $store = "cert:CurrentUserMy"

    $params = @
    CertStoreLocation = $store
    Subject = "CN=Test1"
    KeyLength = 2048
    KeyAlgorithm = "RSA"
    KeyUsage = "DataEncipherment"
    Type = "DocumentEncryptionCert"


    # generate new certificate and add it to certificate store
    $cert = New-SelfSignedCertificate @params


    # list all certs
    # Get-ChildItem -path $store

    # Encryption / Decryption

    $message = "My secret message"

    $cipher = $message | Protect-CmsMessage -To "CN=Test1"
    Write-Host "Cipher:" -ForegroundColor Green
    $cipher

    Write-Host "Decrypted message:" -ForegroundColor Green
    $cipher | Unprotect-CmsMessage


    # Exporting/Importing certificate

    $pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
    $privateKey = "$homeDocumentsTest1.pfx"
    $publicKey = "$homeDocumentsTest1.cer"

    # Export private key as PFX certificate, to use those Keys on different machine/user
    Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

    # Export Public key, to share with other users
    Export-Certificate -FilePath $publicKey -Cert $cert

    #Remove certificate from store
    $cert | Remove-Item

    # Add them back:
    # Add private key on your machine
    Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

    # This is for other users (so they can send you encrypted messages)
    Import-Certificate -FilePath $publicKey -CertStoreLocation $store





    share|improve this answer



























      1














      If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below



      $store = "cert:CurrentUserMy"

      $params = @
      CertStoreLocation = $store
      Subject = "CN=Test1"
      KeyLength = 2048
      KeyAlgorithm = "RSA"
      KeyUsage = "DataEncipherment"
      Type = "DocumentEncryptionCert"


      # generate new certificate and add it to certificate store
      $cert = New-SelfSignedCertificate @params


      # list all certs
      # Get-ChildItem -path $store

      # Encryption / Decryption

      $message = "My secret message"

      $cipher = $message | Protect-CmsMessage -To "CN=Test1"
      Write-Host "Cipher:" -ForegroundColor Green
      $cipher

      Write-Host "Decrypted message:" -ForegroundColor Green
      $cipher | Unprotect-CmsMessage


      # Exporting/Importing certificate

      $pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
      $privateKey = "$homeDocumentsTest1.pfx"
      $publicKey = "$homeDocumentsTest1.cer"

      # Export private key as PFX certificate, to use those Keys on different machine/user
      Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

      # Export Public key, to share with other users
      Export-Certificate -FilePath $publicKey -Cert $cert

      #Remove certificate from store
      $cert | Remove-Item

      # Add them back:
      # Add private key on your machine
      Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

      # This is for other users (so they can send you encrypted messages)
      Import-Certificate -FilePath $publicKey -CertStoreLocation $store





      share|improve this answer

























        1












        1








        1







        If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below



        $store = "cert:CurrentUserMy"

        $params = @
        CertStoreLocation = $store
        Subject = "CN=Test1"
        KeyLength = 2048
        KeyAlgorithm = "RSA"
        KeyUsage = "DataEncipherment"
        Type = "DocumentEncryptionCert"


        # generate new certificate and add it to certificate store
        $cert = New-SelfSignedCertificate @params


        # list all certs
        # Get-ChildItem -path $store

        # Encryption / Decryption

        $message = "My secret message"

        $cipher = $message | Protect-CmsMessage -To "CN=Test1"
        Write-Host "Cipher:" -ForegroundColor Green
        $cipher

        Write-Host "Decrypted message:" -ForegroundColor Green
        $cipher | Unprotect-CmsMessage


        # Exporting/Importing certificate

        $pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
        $privateKey = "$homeDocumentsTest1.pfx"
        $publicKey = "$homeDocumentsTest1.cer"

        # Export private key as PFX certificate, to use those Keys on different machine/user
        Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

        # Export Public key, to share with other users
        Export-Certificate -FilePath $publicKey -Cert $cert

        #Remove certificate from store
        $cert | Remove-Item

        # Add them back:
        # Add private key on your machine
        Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

        # This is for other users (so they can send you encrypted messages)
        Import-Certificate -FilePath $publicKey -CertStoreLocation $store





        share|improve this answer













        If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below



        $store = "cert:CurrentUserMy"

        $params = @
        CertStoreLocation = $store
        Subject = "CN=Test1"
        KeyLength = 2048
        KeyAlgorithm = "RSA"
        KeyUsage = "DataEncipherment"
        Type = "DocumentEncryptionCert"


        # generate new certificate and add it to certificate store
        $cert = New-SelfSignedCertificate @params


        # list all certs
        # Get-ChildItem -path $store

        # Encryption / Decryption

        $message = "My secret message"

        $cipher = $message | Protect-CmsMessage -To "CN=Test1"
        Write-Host "Cipher:" -ForegroundColor Green
        $cipher

        Write-Host "Decrypted message:" -ForegroundColor Green
        $cipher | Unprotect-CmsMessage


        # Exporting/Importing certificate

        $pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
        $privateKey = "$homeDocumentsTest1.pfx"
        $publicKey = "$homeDocumentsTest1.cer"

        # Export private key as PFX certificate, to use those Keys on different machine/user
        Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

        # Export Public key, to share with other users
        Export-Certificate -FilePath $publicKey -Cert $cert

        #Remove certificate from store
        $cert | Remove-Item

        # Add them back:
        # Add private key on your machine
        Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

        # This is for other users (so they can send you encrypted messages)
        Import-Certificate -FilePath $publicKey -CertStoreLocation $store






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 17:53









        Mike TwcMike Twc

        1,2211713




        1,2211713





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55284511%2fgenerating-an-rsa-key-pair-in-powershell%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript