TextCrypto.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <div class="crypto">
  3. <h1>Testing Text Crypto <small>(text encryption then decryption)</small></h1>
  4. <div v-if="rsaPvtKey">
  5. <form @submit.prevent="encryptText(text, rsaPvtKey);">
  6. <input type="text" v-model="text" />
  7. <button>Submit</button>
  8. <button type="button"
  9. aria-label="Clear"
  10. v-show="text || encr || decr"
  11. v-on:click="clear()">
  12. X</button>
  13. </form>
  14. <pre v-show="text">{{text}}</pre>
  15. <pre v-show="encr">{{encr}}</pre>
  16. <pre v-show="decr">{{decr}}</pre>
  17. <pre v-if="done && !matchesVal">
  18. {{done}}
  19. {{matchesVal}}
  20. {{matchesTyp}}
  21. {{textType}}
  22. {{decrType}}
  23. {{decr.length}}
  24. {{text.length}}
  25. </pre>
  26. </div>
  27. <div v-else>
  28. <p>no private key</p>
  29. </div>
  30. </div>
  31. </template>
  32. <script>
  33. export default {
  34. name: "TextCrypto",
  35. props: [
  36. "rsaPvtKey"
  37. ],
  38. data() {
  39. return {
  40. done: true,
  41. text: "",
  42. encr: "",
  43. decr: ""
  44. }
  45. },
  46. computed: {
  47. matchesVal() { return this.text === this.decr },
  48. matchesTyp() { return this.textType === this.decrType },
  49. textType() { return typeof this.text },
  50. decrType() { return typeof this.decr },
  51. },
  52. methods: {
  53. clear: function() {
  54. this.text = ""
  55. this.encr = ""
  56. this.decr = ""
  57. },
  58. encryptText: function(toEncrypt, privatekey) {
  59. this.encr = ""
  60. this.decr = ""
  61. const crypto = require("crypto");
  62. const constants = require("constants");
  63. const bufferToEncrypt = new Buffer(toEncrypt);
  64. const padding = constants.RSA_PKCS1_PADDING;
  65. const encrypted = crypto.publicEncrypt(
  66. {
  67. key: privatekey,
  68. padding: padding,
  69. },
  70. bufferToEncrypt);
  71. this.encr = encrypted.toString("base64");
  72. this.decr = crypto.privateDecrypt(
  73. {
  74. key: privatekey,
  75. padding: padding,
  76. },
  77. new Buffer(this.encr, "base64"))
  78. .toString();
  79. },
  80. },
  81. watch: {
  82. decr() { this.done = true },
  83. text() { this.done = false },
  84. },
  85. }
  86. </script>
  87. <style scoped>
  88. .crypto {
  89. background: #ffccaa;
  90. }
  91. pre {
  92. background: #550000;
  93. color: #00ff77;
  94. }
  95. </style>