ncm_cipher.go 686 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package ncm
  2. type ncmCipher struct {
  3. key []byte
  4. box []byte
  5. }
  6. func newNcmCipher(key []byte) *ncmCipher {
  7. return &ncmCipher{
  8. key: key,
  9. box: buildKeyBox(key),
  10. }
  11. }
  12. func (c *ncmCipher) Decrypt(buf []byte, offset int) {
  13. for i := 0; i < len(buf); i++ {
  14. buf[i] ^= c.box[(i+offset)&0xff]
  15. }
  16. }
  17. func buildKeyBox(key []byte) []byte {
  18. box := make([]byte, 256)
  19. for i := 0; i < 256; i++ {
  20. box[i] = byte(i)
  21. }
  22. var j byte
  23. for i := 0; i < 256; i++ {
  24. j = box[i] + j + key[i%len(key)]
  25. box[i], box[j] = box[j], box[i]
  26. }
  27. ret := make([]byte, 256)
  28. var _i byte
  29. for i := 0; i < 256; i++ {
  30. _i = byte(i + 1)
  31. si := box[_i]
  32. sj := box[_i+si]
  33. ret[i] = box[si+sj]
  34. }
  35. return ret
  36. }