-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicroCrypt.go
More file actions
866 lines (732 loc) · 25 KB
/
MicroCrypt.go
File metadata and controls
866 lines (732 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"strings"
"sync"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"github.com/awnumar/memguard"
"golang.org/x/crypto/argon2"
)
const (
// Argon2 parameters following OWASP recommendations
argon2Time = 3 // Number of passes/iterations
argon2Memory = 64 * 1024 // Memory usage in KB (64 MB)
argon2Threads = 4 // Degree of parallelism
argon2KeyLen = 32 // Output key length in bytes (256 bits)
// Cryptographic parameters
saltLen = 16 // Salt length in bytes (128 bits)
nonceLen = 12 // Nonce length in bytes for AES-GCM (96 bits)
// Security and rate limiting
maxDecryptAttempts = 5 // Maximum failed decryption attempts
rateLimitDuration = time.Minute // Time window for rate limiting
autoClearDuration = 5 * time.Minute // Auto-clear timeout for inactivity
)
// SecureEntry wraps a Fyne entry widget and stores its content in memguard-protected memory
type SecureEntry struct {
widget.BaseWidget
buffer *memguard.LockedBuffer // Protected memory buffer for sensitive text
placeholder string // Placeholder text when buffer is empty
mu sync.Mutex // Mutex for thread-safe access
onChanged func() // Callback triggered when content changes
internalEntry *widget.Entry // Reference to the underlying Fyne entry widget
lastActivity time.Time // Timestamp of last user activity (for auto-clear)
}
// NewSecureEntry creates and initializes a new SecureEntry widget
func NewSecureEntry() *SecureEntry {
se := &SecureEntry{
placeholder: "Enter text...",
lastActivity: time.Now(),
}
se.ExtendBaseWidget(se)
return se
}
// SetText securely stores the provided text in a memguard-protected buffer
func (se *SecureEntry) SetText(text string) {
se.mu.Lock()
// Securely destroy any existing buffer before replacing it
if se.buffer != nil {
se.buffer.Destroy()
}
// Allocate new protected buffer if text is non-empty
if text != "" {
se.buffer = memguard.NewBufferFromBytes([]byte(text))
} else {
se.buffer = nil
}
se.lastActivity = time.Now()
se.mu.Unlock()
se.Refresh()
// Trigger change callback if registered
if se.onChanged != nil {
se.onChanged()
}
}
// GetText returns the current content as a plain string.
// SECURITY WARNING: The returned string resides in standard heap memory
// and is NOT protected by memguard. It may persist in memory until GC runs.
// Use only for short-lived operations (e.g., clipboard copy) and avoid storing the result.
func (se *SecureEntry) GetText() string {
se.mu.Lock()
defer se.mu.Unlock()
if se.buffer == nil {
return ""
}
return string(se.buffer.Bytes())
}
// WithBuffer executes the provided function with direct access to the protected buffer.
// This avoids creating unprotected string copies and is the preferred way to process sensitive data.
func (se *SecureEntry) WithBuffer(fn func(*memguard.LockedBuffer) error) error {
se.mu.Lock()
defer se.mu.Unlock()
if se.buffer == nil {
return errors.New("buffer is nil")
}
return fn(se.buffer)
}
// GetBuffer returns direct access to the protected buffer for secure operations.
// Use WithBuffer() when possible to avoid accidental exposure.
func (se *SecureEntry) GetBuffer() *memguard.LockedBuffer {
se.mu.Lock()
defer se.mu.Unlock()
return se.buffer
}
// Clear securely wipes and deallocates the protected buffer
func (se *SecureEntry) Clear() {
se.mu.Lock()
if se.buffer != nil {
se.buffer.Destroy()
se.buffer = nil
}
se.mu.Unlock()
se.Refresh()
if se.onChanged != nil {
se.onChanged()
}
}
// SetPlaceHolder sets the placeholder text displayed when the entry is empty
func (se *SecureEntry) SetPlaceHolder(text string) {
se.mu.Lock()
se.placeholder = text
se.mu.Unlock()
se.Refresh()
}
// SetOnChanged registers a callback function to be invoked on content changes
func (se *SecureEntry) SetOnChanged(callback func()) {
se.mu.Lock()
se.onChanged = callback
se.mu.Unlock()
}
// SelectAll selects all text in the internal entry widget
func (se *SecureEntry) SelectAll() {
se.mu.Lock()
internal := se.internalEntry
se.mu.Unlock()
if internal != nil {
if canvas := fyne.CurrentApp().Driver().CanvasForObject(se); canvas != nil {
canvas.Focus(internal)
}
internal.TypedShortcut(&fyne.ShortcutSelectAll{})
}
}
// CreateRenderer implements the fyne.Widget interface for custom rendering
func (se *SecureEntry) CreateRenderer() fyne.WidgetRenderer {
// Initialize the internal multi-line entry widget
internalEntry := widget.NewMultiLineEntry()
internalEntry.SetPlaceHolder(se.placeholder)
internalEntry.Wrapping = fyne.TextWrapWord
internalEntry.TextStyle = fyne.TextStyle{Monospace: true}
// Store reference for later access
se.mu.Lock()
se.internalEntry = internalEntry
se.mu.Unlock()
// Sync initial content from secure buffer to display widget
se.mu.Lock()
if se.buffer != nil {
internalEntry.Text = string(se.buffer.Bytes())
}
se.mu.Unlock()
// Bind real-time user input to secure buffer updates
internalEntry.OnChanged = func(newText string) {
var callback func()
se.mu.Lock()
se.lastActivity = time.Now()
// Securely replace the old buffer
if se.buffer != nil {
se.buffer.Destroy()
}
if newText != "" {
se.buffer = memguard.NewBufferFromBytes([]byte(newText))
} else {
se.buffer = nil
}
callback = se.onChanged
se.mu.Unlock()
if callback != nil {
callback()
}
}
return &secureEntryRenderer{
secureEntry: se,
internalEntry: internalEntry,
}
}
type secureEntryRenderer struct {
secureEntry *SecureEntry
internalEntry *widget.Entry
}
func (r *secureEntryRenderer) Layout(size fyne.Size) {
r.internalEntry.Resize(size)
}
func (r *secureEntryRenderer) MinSize() fyne.Size {
return r.internalEntry.MinSize()
}
func (r *secureEntryRenderer) Refresh() {
r.secureEntry.mu.Lock()
var bufferText string
if r.secureEntry.buffer != nil {
bufferText = string(r.secureEntry.buffer.Bytes())
}
placeholder := r.secureEntry.placeholder
r.secureEntry.mu.Unlock()
// Sync internal entry if content has changed
if bufferText != r.internalEntry.Text {
r.internalEntry.SetText(bufferText)
}
if placeholder != r.internalEntry.PlaceHolder {
r.internalEntry.PlaceHolder = placeholder
}
r.internalEntry.Refresh()
}
func (r *secureEntryRenderer) Objects() []fyne.CanvasObject {
return []fyne.CanvasObject{r.internalEntry}
}
func (r *secureEntryRenderer) Destroy() {}
func (se *SecureEntry) FocusGained() { se.Refresh() }
func (se *SecureEntry) FocusLost() { se.Refresh() }
func (se *SecureEntry) TypedRune(r rune) {
if se.internalEntry != nil {
se.internalEntry.TypedRune(r)
}
}
func (se *SecureEntry) TypedKey(key *fyne.KeyEvent) {
if se.internalEntry != nil {
se.internalEntry.TypedKey(key)
}
}
func (se *SecureEntry) AcceptsTab() bool { return false }
// SecureEditor represents the main application structure for the secure text editor
type SecureEditor struct {
app fyne.App
window fyne.Window
textArea *SecureEntry // Main text input/output area
passphrase *memguard.LockedBuffer // Protected storage for current passphrase
secureText *memguard.LockedBuffer // Protected storage for processed text
isDarkTheme bool // Current theme state
isMobile bool // Device type flag for responsive layout
mu sync.RWMutex // Mutex for thread-safe state access
// Audit and rate-limiting fields
decryptAttempts int
lastAttempt time.Time
lastOperation string
operationTime time.Time
// Reference to theme toggle button for dynamic icon updates
themeSwitch *widget.Button
}
// main initializes the application and starts the UI event loop
func main() {
// Ensure all sensitive memory is purged on exit
defer memguard.Purge()
memguard.CatchInterrupt()
myApp := app.NewWithID("oc2mx.net.microcrypt")
editor := &SecureEditor{
app: myApp,
isDarkTheme: true,
isMobile: fyne.CurrentDevice().IsMobile(),
}
editor.window = myApp.NewWindow("MicroCrypt")
myApp.Settings().SetTheme(theme.DarkTheme())
content := editor.setupMobileUI()
editor.window.SetContent(content)
editor.window.SetPadded(false)
editor.window.SetMaster()
// Set initial window size based on device type
if editor.isMobile {
editor.window.Resize(fyne.NewSize(360, 640))
} else {
editor.window.Resize(fyne.NewSize(400, 640))
}
// Start background auto-clear task for security audit compliance
go func() {
for {
time.Sleep(5 * time.Second)
if editor.textArea != nil {
editor.textArea.mu.Lock()
if editor.textArea.buffer != nil && time.Since(editor.textArea.lastActivity) > autoClearDuration {
editor.textArea.mu.Unlock()
editor.clearEditor()
// Use fyne.Do to ensure dialog runs on main UI thread
fyne.Do(func() {
dialog.ShowInformation("", "Sensitive data auto-cleared\ndue to inactivity", editor.window)
})
} else {
editor.textArea.mu.Unlock()
}
}
}
}()
// Intercept window close to perform secure cleanup
editor.window.SetCloseIntercept(func() {
editor.cleanup()
editor.window.Close()
})
editor.window.ShowAndRun()
}
// getThemeIcon returns the appropriate emoji for the current theme state
func (e *SecureEditor) getThemeIcon() string {
if e.isDarkTheme {
return "☀️"
}
return "🌙"
}
// setupMobileUI constructs the responsive user interface layout
func (e *SecureEditor) setupMobileUI() fyne.CanvasObject {
e.textArea = NewSecureEntry()
e.textArea.SetPlaceHolder("Enter text...")
// Primary action buttons
encryptBtn := widget.NewButton("Encrypt", e.encryptText)
encryptBtn.Importance = widget.HighImportance
decryptBtn := widget.NewButton("Decrypt", e.decryptText)
decryptBtn.Importance = widget.HighImportance
clearBtn := widget.NewButton("Clear", e.clearEditor)
clearBtn.Importance = widget.MediumImportance
// Secondary utility buttons
selectAllBtn := widget.NewButton("Select All", e.selectAll)
selectAllBtn.Importance = widget.MediumImportance
copyBtn := widget.NewButton("Copy", e.copyToClipboard)
copyBtn.Importance = widget.MediumImportance
pasteBtn := widget.NewButton("Paste", e.pasteFromClipboard)
pasteBtn.Importance = widget.MediumImportance
// Theme toggle button with emoji icon (Android-compatible)
e.themeSwitch = widget.NewButton(e.getThemeIcon(), e.toggleTheme)
e.themeSwitch.Importance = widget.LowImportance
topBar := container.NewHBox(layout.NewSpacer(), e.themeSwitch)
// Responsive layout based on screen size
var firstButtonRow fyne.CanvasObject
var secondButtonRow fyne.CanvasObject
if e.isVerySmallScreen() {
firstButtonRow = container.NewVBox(encryptBtn, decryptBtn, clearBtn)
secondButtonRow = container.NewVBox(selectAllBtn, copyBtn, pasteBtn)
} else if e.isMobile {
firstButtonRow = container.New(layout.NewGridLayoutWithColumns(3),
encryptBtn, decryptBtn, clearBtn)
secondButtonRow = container.New(layout.NewGridLayoutWithColumns(3),
selectAllBtn, copyBtn, pasteBtn)
} else {
firstButtonRow = container.New(layout.NewGridLayoutWithColumns(3),
encryptBtn, decryptBtn, clearBtn)
secondButtonRow = container.New(layout.NewGridLayoutWithColumns(3),
selectAllBtn, copyBtn, pasteBtn)
}
headerContainer := container.NewVBox(
topBar,
widget.NewSeparator(),
container.NewPadded(firstButtonRow),
container.NewPadded(secondButtonRow),
widget.NewSeparator(),
)
return container.NewPadded(
container.NewBorder(headerContainer, nil, nil, nil, container.NewVScroll(e.textArea)),
)
}
// isVerySmallScreen checks if the window width is below the mobile threshold
func (e *SecureEditor) isVerySmallScreen() bool {
width := e.window.Canvas().Size().Width
return width > 0 && width < 360
}
// selectAll triggers text selection in the secure text area
func (e *SecureEditor) selectAll() {
if e.textArea != nil {
e.textArea.SelectAll()
}
}
// copyToClipboard copies the current text to the system clipboard with security warning and auto-clear
func (e *SecureEditor) copyToClipboard() {
e.mu.RLock()
text := e.textArea.GetText()
e.mu.RUnlock()
if text == "" {
dialog.ShowInformation("", "Nothing to copy", e.window)
return
}
// Convert line endings for Windows compatibility
e.window.Clipboard().SetContent(strings.ReplaceAll(text, "\n", "\r\n"))
// Auto-clear clipboard after delay for security
go func() {
time.Sleep(15 * time.Second)
if e.window != nil && e.window.Clipboard() != nil {
e.window.Clipboard().SetContent("")
}
}()
}
// pasteFromClipboard appends clipboard content to the secure text area
func (e *SecureEditor) pasteFromClipboard() {
e.mu.Lock()
defer e.mu.Unlock()
text := e.window.Clipboard().Content()
if text == "" {
dialog.ShowInformation("", "Clipboard is empty", e.window)
return
}
// Normalize line endings
text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\r", "\n")
e.textArea.SetText(e.textArea.GetText() + text)
}
// toggleTheme switches between dark and light UI themes
func (e *SecureEditor) toggleTheme() {
e.mu.Lock()
defer e.mu.Unlock()
if e.isDarkTheme {
e.app.Settings().SetTheme(theme.LightTheme())
e.isDarkTheme = false
} else {
e.app.Settings().SetTheme(theme.DarkTheme())
e.isDarkTheme = true
}
// Update theme button icon to reflect new state and refresh UI
if e.themeSwitch != nil {
e.themeSwitch.SetText(e.getThemeIcon())
e.themeSwitch.Refresh()
}
e.window.Content().Refresh()
}
// askPassword prompts the user for a password with minimum length validation
func (e *SecureEditor) askPassword(callback func(*memguard.LockedBuffer, error)) {
passEntry := widget.NewPasswordEntry()
passEntry.SetPlaceHolder("")
formItems := []*widget.FormItem{widget.NewFormItem("Password", passEntry)}
dlg := dialog.NewForm("", "OK", "Cancel", formItems, func(confirmed bool) {
if !confirmed {
callback(nil, errors.New("cancelled"))
return
}
if len(passEntry.Text) < 15 {
dialog.ShowInformation("", "Password too short\nMinimum 15 characters required", e.window)
return
}
result := memguard.NewBufferFromBytes([]byte(passEntry.Text))
passEntry.Text = ""
passEntry.Refresh()
callback(result, nil)
}, e.window)
if fyne.CurrentDevice().IsMobile() {
dlg.Resize(fyne.NewSize(320, 100))
} else {
dlg.Resize(fyne.NewSize(350, 180))
}
dlg.Show()
// Focus password field after dialog renders
time.AfterFunc(50*time.Millisecond, func() {
fyne.Do(func() {
e.window.Canvas().Focus(passEntry)
})
})
}
// formatBase64Short formats base64 output with line breaks for readability
func formatBase64Short(data string) string {
const lineLength = 24
var result strings.Builder
for i := 0; i < len(data); i += lineLength {
end := i + lineLength
if end > len(data) {
end = len(data)
}
result.WriteString(data[i:end])
if end < len(data) {
result.WriteString("\n")
}
}
return result.String()
}
// decodeFormattedBase64 removes whitespace and decodes formatted base64 input
func decodeFormattedBase64(data string) ([]byte, error) {
cleanData := strings.Map(func(r rune) rune {
if r == '\n' || r == '\r' || r == ' ' || r == '\t' {
return -1
}
return r
}, data)
return base64.StdEncoding.DecodeString(cleanData)
}
// cleanup securely destroys all sensitive data in memory.
// Note: Go's GC may retain copies of sensitive data in heap until collection.
// memguard protects our LockedBuffers; for strings/[]byte we rely on zeroing
// and hope GC collects them promptly. Perfect memory hygiene is not possible
// in pure Go without unsafe operations.
func (e *SecureEditor) cleanup() {
e.mu.Lock()
defer e.mu.Unlock()
if e.passphrase != nil {
e.passphrase.Destroy()
e.passphrase = nil
}
if e.secureText != nil {
e.secureText.Destroy()
e.secureText = nil
}
if e.textArea != nil {
e.textArea.Clear()
}
if e.window != nil && e.window.Clipboard() != nil {
e.window.Clipboard().SetContent("")
}
// runtime.GC() intentionally omitted: not guaranteed to run immediately,
// and memguard already handles secure memory regions.
}
// clearEditor securely wipes the text area and associated buffers
func (e *SecureEditor) clearEditor() {
if e.textArea.GetText() == "" {
dialog.ShowInformation("", "Text area is already empty", e.window)
return
}
e.cleanup()
}
// encryptText handles the encryption workflow with input validation.
// It uses an asynchronous password prompt and ensures thread safety by
// locking the editor's state only when the encryption process begins.
func (e *SecureEditor) encryptText() {
// 1. Initial check of the UI state (Read-Lock)
e.mu.RLock()
if e.textArea == nil {
e.mu.RUnlock()
return
}
text := e.textArea.GetText()
e.mu.RUnlock()
// Validate input before prompting for password
if text == "" {
dialog.ShowInformation("", "Please enter text to encrypt", e.window)
return
}
// 2. Request password from user (Asynchronous UI Dialog)
e.askPassword(func(passphrase *memguard.LockedBuffer, err error) {
if err != nil {
// User cancelled or validation failed
return
}
// Ensure the sensitive passphrase buffer is destroyed after this callback
defer passphrase.Destroy()
// 3. Perform encryption (Write-Lock)
// We lock here to protect the operation metadata and internal state
e.mu.Lock()
// Update operation tracking for audit/state purposes
e.lastOperation = "encrypt"
e.operationTime = time.Now()
// Execute the cryptographic logic
// We use a helper to keep the encryption logic clean
encryptedData, encErr := e.internalEncrypt([]byte(text), passphrase)
if encErr != nil {
e.mu.Unlock()
dialog.ShowError(encErr, e.window)
return
}
// Update the UI with the result and release the lock
e.textArea.SetText(encryptedData)
e.mu.Unlock()
})
}
// internalEncrypt contains the core cryptographic logic for AES-GCM.
// It assumes the caller handles mutex locking.
func (e *SecureEditor) internalEncrypt(textBytes []byte, passphrase *memguard.LockedBuffer) (string, error) {
// Apply padding to obscure plaintext length (traffic analysis resistance)
paddedText := padTo1024Multiple(textBytes)
textBuffer := memguard.NewBufferFromBytes(paddedText)
defer textBuffer.Destroy()
// Generate random salt and nonce
salt, nonce := make([]byte, saltLen), make([]byte, nonceLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
if _, err := rand.Read(nonce); err != nil {
return "", err
}
// Derive encryption key using Argon2id
key := argon2.IDKey(passphrase.Bytes(), salt, argon2Time, argon2Memory, argon2Threads, argon2KeyLen)
// Securely zero the key after the block cipher is initialized
defer func() {
for i := range key {
key[i] = 0
}
}()
// Initialize AES-GCM
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// Encrypt the padded data
ciphertext := aesgcm.Seal(nil, nonce, textBuffer.Bytes(), nil)
// Combine components: Salt + Nonce + Ciphertext
combinedPayload := append(salt, append(nonce, ciphertext...)...)
// Return as formatted Base64 for easy copy-pasting
return formatBase64Short(base64.StdEncoding.EncodeToString(combinedPayload)), nil
}
// decryptText handles the decryption workflow with input validation and rate limiting.
// It uses an asynchronous callback for password entry, ensuring thread safety
// by locking the mutex only when the actual processing begins.
func (e *SecureEditor) decryptText() {
// 1. Initial check of the UI state (Read-Lock)
e.mu.RLock()
if e.textArea == nil {
e.mu.RUnlock()
return
}
text := e.textArea.GetText()
e.mu.RUnlock()
// Validate input before prompting for password
if text == "" {
dialog.ShowInformation("", "Please paste encrypted text to decrypt", e.window)
return
}
// 2. Request password from user (Asynchronous UI Dialog)
e.askPassword(func(passphrase *memguard.LockedBuffer, err error) {
if err != nil {
// User cancelled or password too short
return
}
// Ensure the sensitive passphrase buffer is destroyed after this callback
defer passphrase.Destroy()
// 3. Start sensitive operations (Write-Lock)
// We lock here because we are about to modify/read rate-limiting state
// and perform the cryptographic operations.
e.mu.Lock()
// Update operation tracking
e.lastOperation = "decrypt"
e.operationTime = time.Now()
// Rate limiting: check if the user is currently blocked
now := time.Now()
if now.Sub(e.lastAttempt) > rateLimitDuration {
e.decryptAttempts = 0
}
e.lastAttempt = now
if e.decryptAttempts >= maxDecryptAttempts {
e.mu.Unlock() // Unlock before showing dialog to prevent UI deadlocks
dialog.ShowError(errors.New("rate limited: too many failed attempts"), e.window)
return
}
// Perform the actual decryption
// Note: performDecryption logic is moved/integrated here or called with
// the understanding that the lock is already held.
decryptedText, decErr := e.internalDecrypt(text, passphrase)
if decErr != nil {
e.decryptAttempts++
e.mu.Unlock()
dialog.ShowError(decErr, e.window)
return
}
// Success: Reset attempts and update UI
e.decryptAttempts = 0
e.textArea.SetText(decryptedText)
e.mu.Unlock()
})
}
// internalDecrypt performs the cryptographic heavy lifting.
// It assumes the caller handles mutex locking for shared state.
func (e *SecureEditor) internalDecrypt(encryptedData string, passphrase *memguard.LockedBuffer) (string, error) {
// Decode and parse the encrypted payload
encryptedBytes, err := decodeFormattedBase64(encryptedData)
if err != nil || len(encryptedBytes) < saltLen+nonceLen {
return "", errors.New("invalid encrypted data format")
}
salt := encryptedBytes[:saltLen]
nonce := encryptedBytes[saltLen : saltLen+nonceLen]
ciphertext := encryptedBytes[saltLen+nonceLen:]
// Derive decryption key using Argon2id
// Use passphrase.Bytes() directly from protected memory
key := argon2.IDKey(passphrase.Bytes(), salt, argon2Time, argon2Memory, argon2Threads, argon2KeyLen)
defer func() {
// Manual zeroing of the derived key for extra safety
for i := range key {
key[i] = 0
}
}()
// Initialize AES-GCM
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// Decrypt and verify authentication tag
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", errors.New("authentication failed: incorrect password or corrupted data")
}
// Remove security padding (traffic analysis resistance)
plaintextBuffer := memguard.NewBufferFromBytes(plaintext)
defer plaintextBuffer.Destroy()
cleanText, err := remove1024Padding(plaintextBuffer.Bytes())
if err != nil {
return "", err
}
return string(cleanText), nil
}
// padTo1024Multiple adds minimal padding to obscure plaintext length patterns.
// Uses ISO/IEC 7816-4 style padding: 0x80 marker followed by zero bytes.
// This is NOT for cryptographic padding (AES-GCM doesn't need it) but for
// traffic analysis resistance by aligning output to fixed boundaries.
func padTo1024Multiple(data []byte) []byte {
const blockSize = 1024
remainder := len(data) % blockSize
// Already aligned → no padding needed
if remainder == 0 {
return data
}
paddingNeeded := blockSize - remainder
paddedData := make([]byte, len(data)+paddingNeeded)
copy(paddedData, data)
// ISO/IEC 7816-4 padding marker
paddedData[len(data)] = 0x80
// Remaining bytes stay 0x00 (zero-initialized by make)
return paddedData
}
// remove1024Padding strips padding added by padTo1024Multiple.
// Returns error if padding marker is missing or malformed.
func remove1024Padding(data []byte) ([]byte, error) {
if len(data) == 0 {
return nil, errors.New("cannot remove padding from empty data")
}
// Data already aligned? Check if padding is actually present
if len(data)%1024 != 0 {
// Not aligned → likely unpadded, return as-is
return data, nil
}
// Search backwards for the 0x80 marker
for i := len(data) - 1; i >= 0; i-- {
if data[i] == 0x80 {
return data[:i], nil
}
// If we hit non-zero bytes before finding 0x80, data may be corrupted
// or legitimately contain binary data. Conservative approach: return as-is.
if data[i] != 0x00 {
break
}
}
// No marker found → assume data was stored without padding
return data, nil
}