Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/crypto/cipher/otp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cipher

import "crypto/rand"

func KeyGen(message string) []byte {
key := make([]byte, len(message))

_, err := rand.Read(key)
if err != nil {
panic(err)
}
return key
}

func OTPEncrypt(message string) (encrypted, key []byte) {
encrypted = make([]byte, len(message))
key = KeyGen(message)
for i := 0; i < len(message); i++ {
encrypted[i] = message[i] ^ key[i]
}
return
}

func OTPDecrypt(encrypted, key []byte) []byte {
decrypted := make([]byte, len(encrypted))
for i := 0; i < len(encrypted); i++ {
decrypted[i] = encrypted[i] ^ key[i]
}
return decrypted
}
16 changes: 16 additions & 0 deletions src/crypto/cipher/otp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cipher

import (
"bytes"
"testing"
)

func TestOTP(t *testing.T) {
msg := []byte("Hello OTP!")
ciphertext, key := OTPEncrypt(string(msg))
decrypted := OTPDecrypt(ciphertext, key)

if !bytes.Equal([]byte(decrypted), msg) {
t.Errorf("Decrypted message does not match original")
}
}