Can I remotely force a locked Mac to sleep or shutdown? Is there any way to remotely make a Mac which is powered on – but locked – to go to sleep and/or shut down? If so, how?

E.g. can I use another Mac B to login via screen sharing to Mac A even if it's locked, and shut it down? Or can I use some other tool, like a remote Alfred script that can execute in the background even if the target computer is locked?

For this question, we are assuming that I am an administrator and have the login details to the target computer.
In order for a user on a remote computer to shut down another computer whether it's a Mac or a PC, they have to have access to it first.
Whether you are using screen sharing or doing this via terminal, regardless of the computer's state (locked or unlocked), if the user has access and the requisite privilege , they can log in and initiate a shutdown.
It's very important to recognize that to shutdown a Mac, you don't need another Mac.  You can do it from Windows, FreeBSD, or Linux.

In terminal
Using an SSH client (Terminal on a OS X) you would log into the remote machine with username/password and machine IP/DNS Name
ssh username@foo.bar
Password:

If you have the appropriate credentials, you would issue the command
sudo shutdown -h now

You could issue these commands regardless if the system was locked or not, even if someone was logged in and working at the time.
Screen Sharing
By using another Mac and it's screen sharing capability or via VNC, you could easily connect to the remote screen, and shutdown the machine even from the lock screen (notice the bottom icons):